text:
Q: Jquery XML parsing I have this XML
<items>
  <item validate="NotEmpty ValidEmail" class="xxx yyy zzz" type="input" name="Id" value="" label="Id" />
  <item validate="NotEmpty" type="input" name="NazovProjektu" value="" label="NazovProjektu" />
  <item type="input" name="Oz" value="" label="Oz" />

I want to get the value of the attribute name of each element with attribute class containing string yyy

A: A class selector will get you the elements.  The attr() function will get you the name of the element.  Using each() on the jQuery Object will allow you to iterate through the element in the jQuery Object.
var yourXML = "...";
$("[class*='zzz']", yourXML).each(function() {
   alert($(this).attr("name"));
});

A: try following, it should help you out.
$(document).ready(function()
{
  $.ajax({
    type: "GET",
    url: "data.xml",
    dataType: "xml",
    success: function(xml)
        {
          //find every yyy classname and alert its name
          $(xml).find(".yyy").each(function()
          {
            alert($(this).attr('name'));
          });
        }
  });
});

A: I believe you can do something like
$("item[class*=yyy]", xml).each(function() {
    $(this).attr('name');
});

A: This might work, haven't tested it yet. Assuming the XML is already parsed and inside an object named xml.
$(xml).find("[class~='yyy']").each(function(i, element) {
    console.log($(element).attr("name"));
});


text:
Q: Precise definition of opaque types and where precisely are their definitions hidden from the user and how to peek at them? I'm using Visual Studio.
I have come across code like the following:
typedef struct A_def A;
typedef struct A *A_ptr;

A_def is hidden. It's an opaque type. It's implementation is hidden so when I go to its definition, nothing happens in VS.
Is this because the implementation/definition is hidden in a .dll or .lib file? And if so, how can I confirm the presence of the definition of A_def by using dumpbin or similar tool?
Also, if this is truly an opaque type why would it be referred to as a future-declared structure or a forward declaration (such definitions of opaque types are being thrown around), because it's already declared and is only hidden from the user?

A: This is just a forward declaration. The definition is needed during the compile time (unless you are using only the pointers to the struct) and is not hidden in a dll or lib.
"Go to defnition" is part of intellisense of visual studio, and it may not have found the definition of the struct in the source files that it parsed.
Structures are usually forward declared if there are cyclic dependencies or in order to separate the interface from the implementation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Async checking image width and height and if they are OK, preview image I'm trying to check width and height from an input file's images and check if they are at least equal than specific dimension (w:300px, h:300px).
I have this check:
window.onload = function () {
    var fileUpload = document.getElementById("inputFileID");
    fileUpload.onchange = function () {
        if (typeof (FileReader) != "undefined") {
            var dvPreview = document.getElementById("divToShowThumbs");
            dvPreview.innerHTML = "";
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
            for (var i = 0; i < fileUpload.files.length; i++) {
                var file = fileUpload.files[i];
                if (regex.test(file.name.toLowerCase())) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var img = document.createElement("IMG");
                        img.src = e.target.result;
                        dvPreview.appendChild(img);
                    }
                    reader.readAsDataURL(file);
                } else {
                    alert(file.name + " is not a valid image file.");
                    dvPreview.innerHTML = "";
                    return false;
                }
            }
        } else {
            alert("This browser does not support HTML5 FileReader.");
        }
    }
};

This works ok to preview each image.
But when I try to use "IF - ELSE" using img.width, it returns 0 because it works in asynchronous way!
Any light about how can I solve this situation?
All I'm trying to do is read each image, check if they area 300px (height and width) and if Ok, create the preview!

A: I got help from this - Getting width & height of an image with filereader . And here is your modified script.
        window.onload = function () {
        var fileUpload = document.getElementById("inputFileID");
        fileUpload.onchange = function () {
            if (typeof (FileReader) != "undefined") {
                var dvPreview = document.getElementById("divToShowThumbs");
                dvPreview.innerHTML = "";
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                for (var i = 0; i < fileUpload.files.length; i++) {
                    var file = fileUpload.files[i];
                    if (regex.test(file.name.toLowerCase())) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            var img = document.createElement("IMG");
                            img.src = e.target.result;

                            img.onload = function() {
                                // access image size here
                                console.log(this.width + " " + this.height);

                                if(this.width <=300 && this.height <=300 )  {
                                    dvPreview.appendChild(img);
                                }
                                else {
                                    alert("too big an image!");
                                }
                            };

                        };
                        reader.readAsDataURL(file);
                    } else {
                        alert(file.name + " is not a valid image file.");
                        dvPreview.innerHTML = "";
                        return false;
                    }
                }
            } else {
                alert("This browser does not support HTML5 FileReader.");
            }
        };
    };


text:
Q: RestKit automatically POST/PUT when back online Our app supports offline activity. Meaning we want to persist locally the creation of new core data objects as well as any modifications on existing objects. Then when the app goes online again we automatically push those changes (and any dependencies) up to the server.
I would think that RestKit would support such an operation, but currently when offline we store creations/modifications in a local cache. If I kill the app, those changes are not persisted. And also there is no attempt by RestKit to post those items to their originally intended endpoints.
I cannot find any documentation to support what we need here.
Is there a way for RestKit to do what we need?
If not, how do I get offline changes to persist to the disk (and not cache)? Then would it be appropriate to flag those as not uploaded to server, and then try uploading them when we are back online?
Any other important things I should consider?

A: At the time of writing RestKit does not support that feature.
To save to disk you need to call saveToPersistentStore: instead of just save: on the MOC.
You need to implement a scheme yourself, observing the 'online' status of the app and scanning the data store for things that need to be uploaded (which means maintaining a flag to indicate if it's happened yet).

A: I solved this issue by adding another field called 'updated' to my object.  This field is set to true or 1 when the object is created or modified.   Each time the application is started or synchronized, it iterates through the local core data copy and sends the objects with 'updated' set.  On the web service, the response ALWAYS clears 'updated' to false when returning a response.  This works well in the case where the web service and app are both online.


text:
Q: How to define whether a spring security filter should be called or not I have many beans on my applicationContext.xml but I don't want to call all of them. Before calling a bean there are some complex rules that define whether they should be called or not and I'm not able to modify their source code.
Are there some kind of special "matching" rule that I can implement?

A: Spring Security has a vast amount of configuration options. However, without more information it is very hard to figure out what exactly you are trying to do.
Some hints:

*

*All Spring Security filters are instances of javax.servlet.Filter.

*However, they are usually not declared directly as filters in your webapp, but called by org.springframework.security.web.FilterChainProxy (which is a javax.servlet.Filter, too).

*org.springframework.security.web.FilterChainProxy organizes filters in instances of org.springframework.security.web.SecurityFilterChain.

*There may be more that one SecurityFilterChain. The chains are matched to requests using org.springframework.security.web.util.matcher.RequestMatcher.

Long story short, you might be able to create multiple SecurityFilterChain instances and implement the "complex logic" in RequestMatcher instances. The way to wire everything up depends heavily on your current setup.


text:
Q: Flutter Row ignore children if it overflows How to calculate or ignore the Children widgets of Row if it gets overflow. I dont want to use Wrap to put the content to the next line, I want to hide the overflowing child widgets
Container(
                padding: EdgeInsets.only(top: 3.0),
                child: Row(
                  children: searchResult.serviceNames
                      .map((service) => getServiceLabels(service))
                      .toList(),
                ),
              ),

P.S a way to Clip the overflowing Wrap children is what Im after

A: If you don't want to wrap the child to next line, you can put the overflowing widget within a SingleChildScrollView that allows the Row in this case to expand to its outer boundary without overflowing:
SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Container(
        padding: EdgeInsets.only(top: 3.0),
        child: Row(
                  children: searchResult.serviceNames
                      .map((service) => getServiceLabels(service))
                      .toList(),
          ),
        ),
      ),
    );

In reality, if you want to display each item wholely (meaning without being cut off in the middle because of lack of screen width), based on screen size you have 2 options:

*

*Calculate the width of each item:

var itemWidth = MediaQuery.of(context).width // 3; // 3 is number of items you want to display

*

*Calculate the number of items:

var itemNumbers = MediaQuery.of(context).width // 150; // 150 is the item's width you want to display

A: Like @Bach said, you can wrap the content in a SingleChildScrollView. However, if you want to restrict the content from scrolling, you can add NeverScrollablePhysics:
return SingleChildScrollView(
          physics: const NeverScrollableScrollPhysics(),
          child: Column(
            children: [],
          ),
        );


text:
Q: ionic info shows ionic framework is unknown I would like run the ionic app in the browser.
I used this command
ionic serve
But I got this error Error: spawn EACCES
I check ionic info but I got ionic framework is unknown
global packages:

@ionic/cli-utils : 1.4.0
Cordova CLI      : 7.0.1
Gulp CLI         : CLI version 3.9.1 Local version 3.9.1
Ionic CLI        : 3.4.0

local packages:
@ionic/cli-plugin-cordova : 1.4.1
Cordova Platforms         : android 6.4.0
Ionic Framework           : unknown

System:
Node       : v7.10.1
OS         : Linux 4.13
Xcode      : not installed
ios-deploy : not installed
ios-sim    : not installed
npm        : 4.2.0

A: You have to reinstall ionic and cordova. Run this command:
npm install -g ionic cordova

A: Install ionic and Cordova globally by using these commands.
1 . sudo npm install -g ionic@latest.
2 . sudo npm install -g cordova@latest.

A: Remove and install Ionic latest/stable Version and open the project in Android Studio and perform a successful gradle.
Once done with the above procedure run the following command on your terminal in case you are using a MAC:

sudo chmod 777 "/Applications/Android
  Studio.app/Contents/gradle/gradle-4.1/bin/gradle"

A: Go to root folder of your ionic project and Follow the below instructions:
run sudo cordova prepare
run sudo chmod -R 777 ./
run ionic serve

A: This problem occurs for linux and mac system
1st add "read and write" permission to the project folder
Right click on the project folder-> click on get info -> add permissions
Now use   "sudo" before all syntax
Like , sudo ionic cordova run android

A: might you missing to add path in environment for C:\Users\username\AppData .otherwise you have install ionic CLI once again with respected node version
user name is respected  to your user name

A: Install ionic and Cordova globally by using these commands.
To install the ionic cli:
npm install -g ionic@latest
To install  the cordova cli:
npm install -g cordova@latest
Then run:
ionic serve


text:
Q: Gradle 3.0 Alpha 2 throwing exception while Alpha 1 works fine    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
    }

Alpha1 works ok for me with Android Studio 3.0 canary 2,
but when I try to use alpha2, I get this exception:
Error:C:\Users\STD1\Documents\STD1\InvistaCultura\invistacultura-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:752 invalid drawable
Error:java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed:
Error:Execution failed for task ':app:mergeDebugResources'.

Error: java.lang.RuntimeException: com.android.builder.internal.aapt.AaptException: AAPT2 compile failed:
    aapt2 compile -o C:\Users\STD1\Documents\STD1\InvistaCultura\invistacultura-android\app\build\intermediates\res\merged\debug C:\Users\STD1\Documents\STD1\InvistaCultura\invistacultura-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
    Issues:
     - ERROR: C:\Users\STD1\Documents\STD1\InvistaCultura\invistacultura-android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:752 invalid drawable

and, in values.xml:752, I find this line, which is from a third library:  Android Image Cropper
<item name="crop_image_menu_crop" type="drawable"/>

What can it be?

A: Found out that with Gradle plugin 3.0-alpha2 and above, resource values have to be defined, and the library does not define this resource.
For anyone who wants to follow up on this issue and a temporary fix Undefined Drawable
Temporary fix taken from the link
Before this gets merged and shipped, you can still use the library by declaring in your app resources
<item name="crop_image_menu_crop" type="drawable">@null</item>


text:
Q: Post process depending on input sklearn pipeline I'm looking for a way to post-process the output of my pipeline given some input.
The scenario is that I'm predicting the value of items in various currencies, I have scaled these prices to USD (pre-processed) to make it easier to work with. Now, original currency is included as a feature in my pipeline, it is 1-hot-encoded in this case.
Now, my pipeline spits out USD prices, I'd like to have a post-processing step, that somehow has access to the original feature values (in this case only the currency), so that i can look it up and convert it back.
example pipeline:
make_pipeline(
    FeatureTransformer(),
    Regressor(),
    ConvertCurrency() # how do I figure out the currency here?
)


text:
Q: NodeJs util.promisify is not a function I'm trying to promisify a mysql function but when I run it the console shows this error util.Promisify is not a function. This is my code:

var util=   require('util');
var mysql=          require('mysql');

var conection=mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'616897',
    database:'proyect'
 });

  var query = util.promisify(conection.query);

  query(data.valida_user).then((rows)=>{
 console.log(rows);
}).catch((error)=>{
 console.log(error);
})

The same error if
var query = util.promisify(mysql.query);
I´m new programming but I'm trying to learn.

A: Unless you're using Node.js 8.x this function won't be defined, that's when it was added to the core Utilities library.
As util is a core Node.js library, you shouldn't have to install it. If you're using Node.js 6.x then use a library like Bluebird which has a promisify function.

A: Other people have spoken to the solution, but here is another source of this error:
There's a NPM package es6-promisify that can also give the error message TypeError: promisify is not a function. (That's why I got to this question.)

*

*Version 5.0.0 of es6-promisifiy needed const promisify = require("es6-promisify"); then you'd use result = promisify( ... );

*Version 6.0.0 had a change of API, and the declaration changed to const { promisify } = require("es6-promisify");

A: You can promise it by yourself if you want:
const promisify = f => (...args) => new Promise((a,b)=>f(...args, (err, res) => err ? b(err) : a(res)));

A: Util is included from Node 8.x on so if you can update node I'd do that.

A: util.promisify is a part of Node 8.X version. But you can still have a polyfill for the older version of Node.

A polyfill is available to take care of the older version of node
servers you'll be running your application on. It can be installed via
npm in the following manner:
npm install util.promisify

Now you can patch module utl on older versions of Node
const util = require('util');
require('util.promisify').shim();

const fs = require('fs');
const readFileAsync = util.promisify(fs.readFile);

A: The following example should work for you:

async () => {
  const connection = await (util.promisify(pool.getConnection).bind(pool))();

  const fn2 = util.promisify(connection.query).bind(connection);
  const rows = await fn2('SELECT col1, col2 FROM Users WHERE email = ?', [email]);

  connection.release();

  return rows;
}

This example uses the standard MySQL module for Node.js. And the util.promisify is the built-in utility of Node.js. Node 8 is used.
The code is wrapped into an async function. Within it on the first line the callback function 'pool.getConnection' is converted into promises and called instantly with the additional 'await' statement. This creates a sequence of the async function and returns a value (a connection) instead of a function or promises. The next line does the same for the 'conection.query', but splits the code into two statements for the sake of simplicity. Finally the function returns the result of the query like any synchronous function.

A: If you have a webpack/babel setup, you can use babel-plugin-transform-util-promisify. It allows you to use util.promisify in node versions < 8. Also very useful if you are targeting node versions >= 8 but want to keep backward compatibility for lower versions.
The plugin transforms code written in the following two formats:
const { promisify } = require('util');

and
import { promisify } from 'util';

You would need to setup the plugin in your .babelrc:
{
  "plugins": [
    "transform-util-promisify"
    ],
    "presets": [
      ["env", {
        "targets": {
          "node": "current"
        }
      }]
    ]
}

The plugin transforms import and require to a function declaration for node versions < 8. It automatically detects version >= 8 and uses native util.promisify in those cases.
Disclosure I'm author and maintainer of babel-plugin-transform-util-promisify

A: Share my working example:
I use this Promisified MySQL middleware for Node.js
here is my database.js
var mysql = require('mysql');

// node -v must > 8.x
var util = require('util');

//  !!!!! for node version < 8.x only  !!!!!
// npm install util.promisify
//require('util.promisify').shim();
// -v < 8.x  has problem with async await so upgrade -v to v9.6.1 for this to work.

// connection pool https://github.com/mysqljs/mysql   [1]
var pool = mysql.createPool({
  connectionLimit : process.env.mysql_connection_pool_Limit, // default:10
  host     : process.env.mysql_host,
  user     : process.env.mysql_user,
  password : process.env.mysql_password,
  database : process.env.mysql_database
})

// Ping database to check for common exception errors.
pool.getConnection((err, connection) => {
if (err) {
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        console.error('Database connection was closed.')
    }
    if (err.code === 'ER_CON_COUNT_ERROR') {
        console.error('Database has too many connections.')
    }
    if (err.code === 'ECONNREFUSED') {
        console.error('Database connection was refused.')
    }
}

if (connection) connection.release()

 return
 })

// Promisify for Node.js async/await.
 pool.query = util.promisify(pool.query)

 module.exports = pool

You must upgrade node -v > 8.x
you must use async function to be able to use await.
example:
   var pool = require('./database')

  // node -v must > 8.x, --> async / await
  router.get('/:template', async function(req, res, next)
  {
      ...
    try {
         var _sql_rest_url = 'SELECT * FROM arcgis_viewer.rest_url WHERE id='+ _url_id;
         var rows = await pool.query(_sql_rest_url)

         _url  = rows[0].rest_url // first record, property name is 'rest_url'
         if (_center_lat   == null) {_center_lat = rows[0].center_lat  }
         if (_center_long  == null) {_center_long= rows[0].center_long }
         if (_center_zoom  == null) {_center_zoom= rows[0].center_zoom }
         _place = rows[0].place

       } catch(err) {
                        throw new Error(err)
       }

A: My problem was that I had not installed util in the first place.
So, npm i util solved my issue

A: Here is an implementation of promisify:

var promisify = function(fn) {
  return function(){
    var args = [].slice.apply(arguments);
    return new Promise(
      function(resolve,reject){
        fn.apply(
          null,
          args.concat([
            function(){
              var results = [].slice.apply(arguments);
              (results[0])//first argument of callback is error
                ? reject(results[0])//reject with error
                : resolve(results.slice(1,results.length))//resolve with result(s)
            }
          ])
        )
      }
    );
  }
};

//some object that has async functions using callbacks
// and using 'this' as invoking object
var callbackApi = {
  name:"callback api",
  age:22,
  asyncFunction:function(arg1,arg2,callback){
    setTimeout(
      function(){callback(null,arg1,arg2,this.name,this.age);}.bind(this),
      10
    )
  }
}

//my object that will use the api functions with promisify
//  and using 'this' as invoking object
var myObject = {
  connection:"connection",
  doSomething:function(arg){
    var asyncFnAsPromise =
      //make sure to bind asyncFunction to callbackApi
      promisify(callbackApi.asyncFunction.bind(callbackApi));
    //return promise created with result promisified callback api
    return asyncFnAsPromise(this.connection,arg)
  }
}

myObject.doSomething(44)
.then(
  resolve=>console.log("resolve:",resolve)
);


text:
Q: Get Postcode and make ajaxcall to API im have no idea if im doing it right or not, and also i cant it put it work, im tyring to make a ajax call to get some information from a API and then present in the html, but first i need to check of X shipping method is selected, and if it is, than get the postcode data to insert in the API, how can i get this information?
Here is my code:
js:
define([
    'jquery',
    'uiComponent',
], function ($,Component) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'CloudJam_Vkios/checkout/shipping/pickup-points'
        },
        getKiosPoints: function () {
            var postalCode = "4433-137"
              $.ajax
                ({
                    type: "POST",
                    beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', 'Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3h');
                    },
                    url: '...API/GetServiceDeliveryPoints',
                    dataType: 'json',
                    contentType: 'application/json',

                    async: true,
                    //json object to sent to the authentication url
                    data: JSON.stringify({
                     "PostalCodeOrLocality": postalCode,
                     "Latitude": 0,
                     "Longitude": 0,
                     "SortOrder": 0
                    }),
                    success: function (data) {
                        if(data.statusCode == 200){

                            var locations = data.response;

                            return locations;
                        }
                    },
                    error: function( jqXhr, textStatus, errorThrown ){
                        return errorThrown;
                    }
                 })

        }
    });
});

HTML:

Localizações

A:    define section
<!-- code to get zip code -->
  var zipCode = quote.shippingAddress._latestValue.postcode;

create quote Object : 'Magento_Checkout/js/model/quote' ( Add in define section)

 define([
'jquery',
'uiComponent',
'Magento_Checkout/js/model/quote'
 ], function ($,Component,quote) {
'use strict';

return Component.extend({
    defaults: {
        template: 'CloudJam_Vkios/checkout/shipping/pickup-points'
    },
    getKiosPoints: function () {
        var postalCode = quote.shippingAddress._latestValue.postcode
          $.ajax
            ({
                type: "POST",
                beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', 'Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3h');
                },
                url: '...API/GetServiceDeliveryPoints',
                dataType: 'json',
                contentType: 'application/json',

                async: true,
                //json object to sent to the authentication url
                data: JSON.stringify({
                 "PostalCodeOrLocality": postalCode,
                 "Latitude": 0,
                 "Longitude": 0,
                 "SortOrder": 0
                }),
                success: function (data) {
                    if(data.statusCode == 200){

                        var locations = data.response;

                        return locations;
                    }
                },
                error: function( jqXhr, textStatus, errorThrown ){
                    return errorThrown;
                }
             })

    }
});

});
I hope this may help you out.


text:
Q: How to place glyphicon inside a placeholder in a input form using bootstrap I am trying to place a glyphicon inside a input form using placeholder via bootstrap.
but the result is its displaying the code in input form instead icon.
here's my code:

<input type="text" class="form-control" placeholder="search">

output:
Displaying as
search

inside a input form.

sorry for unclear question
It should be actually when i click over the input form and enter some text the glyphicon should go hidden as we place in a placeholder.
Thanks in advance.

A: try like this
 <!DOCTYPE html>

<title>Timer</title>

<link href="css/bootstrap.css" type="text/css" rel="stylesheet" />

<form class="form-inline">

    Amount (in dollars)

      <input type="text" class="form-control" id="exampleInputAmount" placeholder="Amount">

</form>

Further, you can refer below URL, which gives syntax and format for many bootstap related issues.
http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-lists.php


text:
Q: Is there a way to submit a text post on reddit via a url I know there's a way to submit a link post to reddit.
https://www.reddit.com/r/test/submit?title=myTitle&url=http://www.exampledsfsd.com

which pops up a page like this with the title and url filled in

Is there a way to initiate the submission of a text post?
It really just needs to get to the "text" tab and fill on the "text" field in this page

Just to be clear, I'm aware of the Reddit API. I don't want to take an approach that requires setting up a reddit account, a reddit app, and manage authentication for the user. I actually already tried this approach but there are issues with using it with other aspects of my site. I'm looking for something simple like the submit Link Post above

A: Simply guessed at this one, but it worked for me. Use text as the parameter instead of url.
https://www.reddit.com/r/test/submit?title=myTitle&text=testing

Of course, you'll need to url encode your text.

A: As CoderDennis said, you can use the submit page with the text parameter (urlencoded).  You should also set selftext to true, which sets the displayed tab to the self post tab (although it's not required as that is inferred based off of the text parameter).
Some of the things in the doc for /api/submit still apply to that page (although only a few).  You can see exactly how it works by looking at the code used for the actual page on reddit's GitHub (here and here)
For submitting a text post, what you'll want is a URL like this:
https://www.reddit.com/r/test/submit?title=Title%20to%20use&selftext=true&text=Urlencoded%20self%20post%20text
This will open the submit page for /r/test to submit a new post with the title "Title to use", and a post body of "Urlencoded self post text".
Here are all of the parameters, for reference:

*

*title: Title of the post to submit

*url: URL to submit to

*text: Text of the self post

*selftext: Whether to default to the self text tab (true to do so).  If text is present, then it will default to displaying that tab anyways.

*resubmit: Whether to resubmit the post (if not present and submitting a link post, and another post already links there, you will be taken to that post instead with an option to resubmit it).


text:
Q: requestFeature with action bar So I was looking at google's api demos for action bars and they have this
// The Action Bar is a window feature. The feature must be requested
    // before setting a content view. Normally this is set automatically
    // by your Activity's theme in your manifest. The provided system
    // theme Theme.WithActionBar enables this for you. Use it as you would
    // use Theme.NoTitleBar. You can add an Action Bar to your own themes
    // by adding the element <item name="android:windowActionBar">true</item>
    // to your style definition.
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

but when I tried to add the last line of code getWindow().requestFeature(Window.FEATURE_ACTION_BAR);  My app just dies on start up. So what does it really do?

A: The secret is the order of the callings.The requestfeature must be called before fill nothing. I do it in this order and works fine:
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.your_activity_layout);

A: I know this is very late, did you try
requestWindowFeature(Window.FEATURE_ACTION_BAR)


text:
Q: Set LED brightness without analogwrite (Arduino) I want to set the brightness of a LED of my arduino. I know how to do this with the analogwrite() function of the arduino. Now I want to do this without the analogwrite() function and use PORT manipulations.
I can write to a port like this: PORTD = 0b00001000. This sets an output to PIN 3. But with this I cant set the brightness. Is there some trick to set the brightness for this?

A: Once your Pin is set logically HIGH, it will serve the specified voltage (probably 5V) and the current that is needed (limited by the board).
Thus, you do not have any influence on these ouptput parameters.
You might consider switching the LED on and off with a sufficiently high frequency, so that it appears to be dimmed (Pulse-width modulation).


text:
Q: Generating directory structure from string I'm trying to generate a directory tree structure from a string that I enter into my program. Example of string:
/users/username/documents/folder/file.txt

I want to create the above directory structure inside a predetermined folder e.g. "backup". When done right, the resulting directory tree would be:
/backup/users/username/documents/folder/file.txt

But I don't want to copy all the files inside the "documents" folder or "folder" folder etc. The only file I want to be copied over is the single text file at the end of the path.
Would I have to loop through the indexes of the string and separate it using the "/" ? It seems a bit tedious and I was wondering if there was a quicker more efficient way to code it?

A: If you want to use the POSIX function mkdir(2) you need to create missing directories one by one.
If you are prepared to be a bit less portable
it can be done with a single system call. How you do it depends on your OS.
In Linux/UNIX you can create all missing directories in one call with mkdir -p.
In windows you can use SHCreateDirectoryEx (according to the comment by Baldrick).

A: I tried to write a program that does the above mentioned job and found the following one to work.
You can use strtok() to extract all individual directories from the input and apply
mkdir() for each subdirectory. The string after the last / is the file name and I don't know if there is a better way to parse the string using strtok() the way I do: I call a function countChars() (borrowed from https://stackoverflow.com/a/4235545/1024474) to determine the number of / in the path to get the number of folders to be created and use a while loop accordingly to create the dirs.
Finally, I use creat() to create a file with the file name of the specified path. In your code you would copy the content of the original file to the new file.
The following code assumes that your are already in the predetermined backup/ folder and the path is something like users/username/documents/folder/file.txt
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int countChars( char* s, char c )
{
    return *s == '\0'
              ? 0
              : countChars( s + 1, c ) + (*s == c);
}

int main(int argc, char **argv) {

   mode_t mode = S_IRWXU;

   umask(0);

   char buffer[512];
   char *b;
   char c[512];
   int n, i=0;

   strcpy(buffer, argv[1]);

   n = countChars(buffer, '/');

   printf("%d\n", n);

   b = strtok(buffer, "/");

   while (i<n)
   {
    i++;
    printf("%s\n", b);
    if (mkdir(b, mode) == -1) {
        printf("error when creating dir\n");
    }
    chdir(b);
    b = strtok(NULL, "/");
   }

   if (creat(b, mode) == -1) {
       printf("error when creating file\n");
   }

   return 0;

}

If a folder already exists, the programs prints an error (i.e. a notification), but proceeds.


text:
Q: cat command appears to be adding extra $ character at the end of each line I am trying to create a file and it looks like the vi editor is adding a $ at the end of each line. I don't know what's causing this or how to prevent vi from doing it.
vi file.txt
12345
abcde

cat -v -e file.txt
12345$
abcde$

wc file.txt
2 2 12

I don't want those $ symbols at the end; they break my automation files which depend on character count. Why would word count shows 12 characters when in fact each line has 5 characters?
VIM version 7.4.629

A: @steeldriver's comment is correct: cat shows line-endings with $ (as vi might if you asked it nicely, using ":set list").  The extra character per line is the newline (an invisible character at the end of each line of text).
If you want only a count of the printable text, you could filter the file before processing it with wc, e.g., using tr with the -d option.  Here is a script which counts itself as an example:
#!/bin/sh
cat $0 |wc
cat $0 | tr -d '\r\n\t' | wc
cat $0 | tr -d '[:cntrl:]' |wc

though the last line is possibly not portable enough for your use (it is in POSIX, in the extended section).   But it will run on anything you're likely to be using, based on the clues in the rationale.


text:
Q: Error when executing using ./bin/spark-submit in PySpark I am getting the below error when executing the code from command line in centOS.
"(<class 'py4j.protocol.Py4JJavaError'>, Py4JJavaError(u'An error occurred while calling o313.save.\n', JavaObject id=o315), <traceback object at 0x7fca49970320>)"

I am getting this issue only when I am submitting it through ./bin/spark-submit test.py
If I use just :  spark-submit test.py everything works fine. But I am not able to run the code in yarn with it.
I have anaconda installed in my machine and I think it's using the anaconda spark-submit in the second method.
Can anyone please suggest what to do with it? Do I have set any env variables or update the libraries?
Edit:
As per the comments providing more details about the script and versions
This is the code:
from pyspark import SparkConf, SparkContext, SQLContext
from pyspark.sql import SparkSession,DataFrame
from pyspark.ml.feature import StringIndexer, VectorAssembler, OneHotEncoderEstimator, OneHotEncoder
import sys
from operator import add
import os
import pandas as pd
import numpy as np
from pyspark.sql.types import *
import pyspark.sql.functions as func
from IPython.display import display, HTML
from pyspark.ml import Pipeline, PipelineModel
from pyspark.ml.classification import LogisticRegression,LogisticRegressionModel

path = 'hdfs://10.0.15.42/nih-poc-public-dataset/'

pipeline_path = '/opt/nih/pipeline_model'

try:
    conf = SparkConf().setMaster("local[8]").setAppName("sparkstream").set("spark.driver.allowMultipleContexts", "true")

    sc = SparkContext(conf = conf)
    sqlContext = SQLContext(sc)

    spark = SparkSession.builder\
            .config(conf = conf)\
            .getOrCreate()

    print "SparkContext Version:", sc.version
    print "SparkContext Version:", sc.version
    print "Python version: ", sc.pythonVer
    print "Master URL to connect to: ", sc.master
    print "Path where Spark is installed on worker nodes: ", str(sc.sparkHome)
    print "Retrieve name of the Spark User running SparkContext: ", str(sc.sparkUser())
    print "Application name: ", sc.appName
    print "Application ID: ", sc.applicationId
    print "Default level of parallelism: ", sc.defaultParallelism
    print "Default number of partitions for RDDs: ", sc.defaultMinPartitions

    ########################################################################################################
    ############################################# DATA EXTRACTION ##########################################
    ########################################################################################################
    file_name = path + 'maintenance_data.csv'

    df_nih = spark.read.csv(file_name,sep = ';',header = "true",inferSchema="true")
    df_nih.show(1)

    #print(df_nih.columns)

    print(df_nih.count())
    ########################################################################################################

    ########################################################################################################
    ######################################## PIPELINE FORMATION ############################################
    ########################################################################################################
    categoricalcolumns = ['team','provider']
    numericalcolumns = ['lifetime', 'pressureInd', 'moistureInd', 'temperatureInd']

    stages = []

    for categoricalcol in categoricalcolumns:
        stringindexer = StringIndexer(inputCol = categoricalcol, outputCol = categoricalcol + '_index')
        encoder = OneHotEncoderEstimator(inputCols=[stringindexer.getOutputCol()], outputCols=[categoricalcol + "_classVec"])

        stages += [stringindexer,encoder]
        #stages += [stringindexer]

    assemblerinputs = [c + "_classVec" for c in categoricalcolumns] + numericalcolumns
    vectorassembler_stage = VectorAssembler(inputCols = assemblerinputs
                                ,outputCol='features')

    stages += [vectorassembler_stage]

    #output = assembler.transform(df_nih)

    #print(output.show(1))

    indexer = StringIndexer(inputCol = 'broken', outputCol = 'label')

    stages += [indexer]

    #pipeline = Pipeline(stages = [stages,vectorassembler_stage,indexer])

    pipeline = Pipeline(stages = stages)

    model_pipeline = pipeline.fit(df_nih)

    model_pipeline.write().overwrite().save(pipeline_path)
except:
    print(sys.exc_info())

finally:
    print('stopping spark session')
    spark.stop()
    sc.stop()

This is the output:
> /usr/hdp/3.0.0.0-1634/spark2> ./bin/spark-submit --master yarn
> /opt/nih/sample_spark.py SparkContext Version: 2.3.1.3.0.0.0-1634
> SparkContext Version: 2.3.1.3.0.0.0-1634 Python version:  2.7 Master
> URL to connect to:  yarn Path where Spark is installed on worker
> nodes:  None Retrieve name of the Spark User running SparkContext:
> spark Application name:  sparkstream Application ID:
> application_1540925663097_0023 Default level of parallelism:  2
> Default number of partitions for RDDs:  2
> +--------+------+----------------+----------------+----------------+-----+---------+ |lifetime|broken|     pressureInd|     moistureInd|  temperatureInd|
> team| provider|
> +--------+------+----------------+----------------+----------------+-----+---------+ |      56|
> 0|92.1788540640753|104.230204454489|96.5171587259733|TeamA|Provider4|
> +--------+------+----------------+----------------+----------------+-----+---------+ only showing top 1 row
>
> 999 (<class 'py4j.protocol.Py4JJavaError'>, Py4JJavaError(u'An error
> occurred while calling o309.save.\n', JavaObject id=o311), <traceback
> object at 0x7f9061c86290>) stopping spark session

If I comment the saving part(model_pipeline.write) everything works fine. Please provide your suggestions


text:
Q: Bulk add item rails 6 I have a little project management app.
In the app I have a Project, Item and Delivery Model.
class Project < ApplicationRecord
    has_many :locations, dependent: :destroy
    has_many :items, dependent: :destroy
    has_many :deliveries, dependent: :destroy
end

class Item < ApplicationRecord
  belongs_to :project
  belongs_to :location, optional: true
  has_many :delivery_items, dependent: :destroy
  has_many :deliveries, through: :delivery_items

  enum status: [:unscheduled, :scheduled, :delivered]
end

class Delivery < ApplicationRecord
  belongs_to :project
  has_many :delivery_items, dependent: :destroy
  has_many :items, through: :delivery_items

  enum status: [ :unapproved, :approved, :scheduled ]
end

I also have a delivery_item join table
class DeliveryItem < ApplicationRecord
  belongs_to :delivery
  belongs_to :item
end

I have added a new Model called location, which is a way of classifying the items into a group on the project.
class Location < ApplicationRecord
  belongs_to :project
  has_many :items
  has_many :part_numbers, through: :items

  def bulkadd(delivery)
    self.items.each do |row|
      batch << Product.new(row)
    end
  end
end

At the moment the user individually adds items to deliveries via a form on the page

Add to Delivery

<%= form_for @delivery_item, html: {class: 'form-inline'} do |form| %>

    <%= form.collection_select :delivery_id, @project.deliveries.all, :id, :date, placeholder: 'Add to Delivery', class: 'form-control' %>

    <%= form.hidden_field :item_id, value: item.id %>

    <%= form.submit "Add",class: 'btn btn-primary' %>

<% end %>

I would like to simplify the process by adding a bulk add button to each location which would add all of the associated items to the delivery selected has many items.
I know that I will need the delivery_item(delivery, item).
I just cant seem to get the final part to work in my brain

A: When you create a has_many or has_and_belongs_to_many assocation the macro creates an others_ids setter/getter. In this case item_ids= which will automatically add/remove rows from the join table.
Its really easy to use this together with the form option helpers to create a select  where the user can choose multiple records:
<%= form_for(@delivery) do |form| %>

    <%= f.label :item_ids, 'Select the items' %>
    <%= f.collection_select :item_ids, @items, :id, :name, multiple: true %>

<% end %>

Or if you prefer checkboxes:
<%= form_for(@delivery) do |form| %>

    <%= f.label :item_ids, 'Select the items' %>
    <%= f.collection_check_boxes :item_ids, @items, :id, :name %>

<% end %>

Replace :name with whatever attribute you want to use for the option text.
class DeliveriesController < ApplicationController
  before_action :set_delivery, only: [:show, :edit, :update, :destroy]
  # This avoids a database query in the view
  before_action :set_items, only: [:new, :edit]

  # POST /deliveries
  def create
    @delivery = Delivery.new(delivery_params)
    if @delivery.save
      redirect_to @delivery, notice: 'Delivery created'
    else
      set_items
      render :new
    end
  end

  # PUT|PATCH /deliveries/1
  def update
    if @delivery.update(delivery_params)
      redirect_to @delivery, notice: 'Delivery updated'
    else
      set_items
      render :edit
    end
  end

  private

  def set_delivery
    @delivery = Delivery.find(params[:id])
  end

  def set_items
    @items = Item.all
  end

  def delivery_item_params
    # Passing the hash `item_ids: []` allows an array of permitted scalar types.
    params.require(:delivery)
          .permit(:foo, :bar, :baz, item_ids: [])
  end
end


text:
Q: How can i redirect on submitting my form in reactjs and using formik the redirect is not working, how can I redirect am using functional components.
const [redirect,setredirect]=useState(false);
const onSubmit = (values,{resetForm}) => {
    console.log('Form data', values);
    setredirect(true);
    if(redirect)
    {
        return <Redirect to='/' />
    }

A: You can use history.push to redirect.
const history = useHistory()
history.push('/')

Btw, the condition to check if redirect is true won't work since setRedirect is asynchronous. You don't need the redirect piece of state at all.
const onSubmit = async (values) => {
  // Send an API request with the values
  // await makeAPICall(values)
  history.push('/')
};

A: The problem is that setting the state does not (necessarily) change it synchronously, so if you check the state right after you set it, it may still contain the old value. In react, setting the state does not immediately mutate the state, but creates a pending state transition. If you need to reliably access the new state right after setting it, just save it to a temporary variable:
let shouldRedirect = true; // I'm assuming this is not hard-coded or the if statement makes no sense.
setredirect(shouldRedirect);
if (shouldRedirect) {
  // Do something
}


text:
Q: How to use CheckIfPrime I need to use the CheckIfPrime item in my code, but having some issue, may i know how should I deal with it? Do I need to make declaration?
For number As Integer = 1 To 30
    If CheckIfPrime(number) = True Then
        sb.Append(number.ToString & " ")
    End If
Next

Please advice on how can I do that in Visual Basic.

A: The VB.net has no CheckIfPrime method, so to deal with it in your task we need to create a method to check the number if is prime or not.
   Public Function CheckIfPrime(number As Integer) As Boolean
        For i As Integer = 2 To number - 1
            If number Mod i = 0 Then
                Return False
            End If
        Next
        Return True
    End Function

Usage
   For number As Integer = 1 To 30
      If CheckIfPrime(number) = True Then
       'Console.WriteLine(number.ToString & " ")
       sb.Append(number.ToString & " ")
      End If
   Next

Source


text:
Q: C++ reading numbers from a text file into an array Hello i am student of the first year thats why i got problem with such easy task.
I am working currently on matrix calculator but in the very begging i occured some problems with reading numbers from a text file and printing them on screen
Here is my code:
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;
 int main()
{
    ifstream infile;
    infile.open("matrix.txt", ios::in);
    //check for an error
    if(infile.fail())
    {
        cerr<<"Error opening file";
        exit(0);
    }
    //char sign;
    int n = 0;
    double matrix[n];
    while(!infile.fail())
    {
        infile >> matrix[n];
        n++;
        //if(infile.eof()) {break;}
    }

infile.close();

    for(int i = 0;i<9;i++)
    {
        cout << matrix[i]<<endl;
    }
return 0;
}

In the shortcut about the whole program it is supposed to read from a text file and calculate a determinant of 2x2 matrix or 3x3 matrix. If you can give me any ideas which will be useful in the future for example how i can check if the line in text file ended i would be thankful. But mostly i want to know what i am doing wrong. Thank's from above.

A: Consider the following lines of your code.
int n = 0;
double matrix[n];
while(!infile.fail())
{
    infile >> matrix[n];
    n++;
    //if(infile.eof()) {break;}
}

You will need to read the documentation of your compiler to find whether it supports variable length arrays. They are not allowed in standard c++, so if you want your program to be portable, you will need to stop using them.
Secondly, you allocate an array of size 0, which is not allowed (again, your compiler might allow it as a non-standard feature).
Thirdly, if the size of matrix is n, then matrix[n] will overflow.
Fourthly, checking the fail bit before extracting the value with infile >> matrix[n] is a bad idea. At some point you'll want to actually figure out how many valid values you have read, you'll find that it's simpler to test whether the extraction succeeded, after the extraction.


text:
Q: Swift 4.0 Delayed Launch Screen Causes Items to disappear I am creating an app with Swift 4.0 and I am trying to delay the launch screen. The initial screen will sleep for 2 seconds, then the "a FusionPointInc application" label will disappear and the screen will stay at the red curtain background image (the second image). It will stay there and won't show the second screen (the Theater Stages Throughout History screen)
Here is my code for the initial screen:
override func viewDidLoad() {
    super.viewDidLoad()

    sleep(2)

    showNavController()
}

func showNavController() {
    performSegue(withIdentifier: "showMainView", sender: self)
}

More code for the initial screen (will transition to the second screen):
`class showMainView: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    //performSegue(withIdentifier: "showSegue", sender: self)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}
This screen will open and when prompted to segue, the screen will only show the background (the second picture).
The middle screen code is in the ViewController.swift file and it has no actual code in it (just the pre-formatted base code)
I tested when I delete the initial screen, the app will load up fine. But, I wanted the initial screen to be delayed so "a FusionPointInc application" can be seen!

A: You are calling sleep on the main thread.
Instead, you should be doing something like this:
override func viewDidLoad() {
    super.viewDidLoad()

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
       self.showNavController()
    }
}

This will call showNavController after two seconds without issues.


text:
Q: How to call images to a different view in xcode using variables I am currently working on a project in Xcode 4.4 with objective-c not in cocos2d where I have a view called GameView and a class called Characters. In the GameView have, well, the game, this is the scene in which you play the game. In the Characters, all the characters images and powers or anything unique to them are called. I want it so that I can choose a character in CharacterSelect page and then the character that I selected is the character that is in the GameView and that I am controlling. Right now I am just working with the images. In the GameView I am basically trying to set up a way to call an image of the corresponding character from the Characters class. If I could I would have an animation of the character but I'm just going to go step by step. All I want is the corresponding image for the character while he's facing right
Here is my code in my GameView.m for the function to basically create the image, and I know I need to call the image file from a variable in Characters. bluebox is like defined in the .h as a UIImageView and really it just contains all the things the character can do... such as the left and right buttons allows it to move and so on...
        -(void)createCharacter
 {
     bluebox = [[UIImageView alloc] initWithFrame:
           CGRectMake(70, 100, 150, 130)];
     bluebox = [[UIImageView alloc] init];

 }

In my Characters.m I made an NSString in my .h of Characters in it is called lookingRight1... And then for one of my characters I have this
-(void)megaMan
{
 lookingRight1 = @"MegaManRight1.png";
}

Now I suppose I'd need to call looking right. I'm actually confusing my self trying to write this, so please help, if you don't get confused also. I don't have really much code for my CharacterSelect page but what I do have just links a particular button labeled with a character name to the GameView.
If you could please help I'd be extremely thankful. I think that it would help if you could show a mock second character also so that I can see what to do to get the character I want...
Sorry If this is confusing to you.


text:
Q: Why does my item-list not work in Vue.js? I tried to create my first Vue.js app on my own and therefore relied on the documentation. But there is an error I can not solve. I tried to rebuild the app like in the documentation and made some mistake. The list doesn't display the items and it doesn't add new items to the list. I would be grateful if anyone could give me any advice.
Yours
 Vue.component('workout-item', {
    template: '\

\
        {{ title }}\
        {{ workoutGoal }}\
        {{ workoutDone }} \
        <button v-on:click="$emit(\'remove\')">Remove</button>\

\
    ',
    props: {
        title: String,
        workOutGoal: Number,
        workoutDone: Number
    }
  })

  new Vue({
    el: '#workout-list-example',
    data: {
        newWorkoutText: '',
        newWorkoutGoal: '',
        newWorkoutDone: '',
        workouts: [
            {
                id: 1,
                title: 'Sit-ups',
                workoutGoal: 10,
                workoutDone: 0,
            },
            {
                id: 2,
                title: 'Crunches',
                workoutGoal: 15,
                workoutDone: 0,
            },
            {
                id: 3,
                title: 'Lift-ups',
                workoutGoal: 16,
                workoutDone: 0,
            }
        ],
        nextWorkoutId: 4
    },
    methods: {
        addNewWorkout: function() {
            this.workouts.push({
                id: this.nextWorkoutId++,
                title: this.newWorkoutText,
                workoutGoal: this.newWorkoutGoal,
                workoutDone: this.newWorkoutDone

            })
            this.newWorkoutText=''
            this.newWorkoutGoal=''
            this.newWorkoutDone=''
        }
    }
})

    <form v-on:submit.prevent="addNewBook">
        Add a Book
        <input
        v-model="newBookText"
        id="new-book"
        placeholder="E.g. Three women"
        >

        <button>Append</button>
    </form>

    <form v-on:submit.prevent="addNewWorkout">
        Add a workout
        <input
            v-model="newWorkoutText"
            id="new-workout"
            placeholder="E.g. Push-ups"
        >
        <input
            v-model="newWorkoutGoal"
            id="new-workout"
            placeholder="E.g. 10"
        >
        <input
            v-model="newWorkoutDone"
            id="new-workout"
            placeholder="E.g. 5"
        >
        <button>Append</button>
    </form>

A: There is a prop's name mistake for workoutGoal into your props declaration code (it's case sensitive).
(I will ignore the div for the book list here)
props: {
  title: String,
  workOutGoal: Number,
  workoutDone: Number
}

Should be:
props: {
  title: String,
  workoutGoal: Number, // lowercase on 'Out'
  workoutDone: Number
}

Then to use your props, you should use "kebab-case" (hyphen separator). For e.g: myLovelyProp is bound as my-lovely-prop (https://v2.vuejs.org/v2/guide/components-props.html):

Should be:

Finally, do not forget to cast your workout goal and workout done inputs to Number. Since you get it like a string from the field, to match your prop's types:
addNewWorkout: function() {
   this.workouts.push({
   ...
   workoutGoal: Number(this.newWorkoutGoal), // Cast string to number value.
   workoutDone: Number(this.newWorkoutDone)  // Cast string to number value.
})


text:
Q: Is it possible to send batch notifications with subscriptions ids having different fields? I have this code for batch:
$ch = curl_init();
$google_gcm_url = 'https://gcm-http.googleapis.com/gcm/send';
$title = 'Title';
$msg = 'Message';

// just sample unrealistic ids
$fields['to'] = array (
    'mobileSubscriptionId1',
    'mobileSubscriptionId2',
    'mobileSubscriptionId3'
);

$fields['notification'] = array (
    'title' => $title,
    'body' => $msg,
    // 'url' => 'some_url1',
    'url' => array (
        'some_url1',
        'some_url2',
        'some_url3'
    )
);

$fields['priority'] = 'high';
$fields['content_available'] = true;

curl_setopt($ch, CURLOPT_URL, $google_gcm_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

$result = curl_exec($ch);
curl_close($ch);

Is it possible to set the subcription "mobileSubscriptionId1" so when they click it it will go to the first url field "some_url1"?
Then "mobileSubscriptionId2" to "some_url2" , then "mobileSubscriptionId3" to "some_url3" .
I've tried my code but it doesn't work.
I don't want to loop through curl because it's really slow.
Realistically I have thousands of ids.

A: This is currently not possible for GCM (and FCM). If you intend to send uniques payloads for each user, you'll have to send a separate request for each. (See my answer in the possible duplicate post).
@markdwhite's comment seems to be feasible.


text:
Q: Simple require validation inside Custom Component input I have multiple components and each having some input, select and other form elements. This all elements developed using template driven form.
But previously it was developed not in component wise, so we were able to check form status. Now as we have divided everything by component but validation we are not able to get it.
I have two questions.

*

*For getting child component form elements to parent component, I am using ControlValueAccessor, is this correct way to do it ? In my child component i have multiple form controls like input, select and other.

*Simple validations like required on input element, its not working inside child component. What should i do ?
This is Plunkr which mostly demonstrates what i wanted to achieve.
@Component({
  selector: 'my-child',
  template: `

Child

  <input [ngModel]="firstName" (ngModelChange)="firstSet($event)" required>
  <input [ngModel]="lastName" (ngModelChange)="lastSet($event)" required>
  `,
  providers: [
    {provide: NG_VALUE_ACCESSOR, useExisting: Child, multi: true}
  ]
})

export class Child implements ControlValueAccessor, OnChanges {

  private firstName: string,
  private lastName: string;

  fn: (value: any) => void;

  constructor(){

  }

  writeValue(value: any) {
    console.log("write value");
    console.log(value);
    if(value){
      this.firstName = value.firstName;
      this.lastName = value.lastName;
    }
  }

  registerOnChange(fn: (value: any) => void) {
    this.fn = fn;
  }

  registerOnTouched() {}

  firstSet(v: string){
    this.firstName = v;

    this.fn({
      firstName: this.firstName,
      lastName: this.lastName
    });
  }

  lastSet(v: string){
    this.lastName = v;

    this.fn({
      firstName: this.firstName,
      lastName: this.lastName
    });
  }
}

If you find wrong way please mention which is correct way to do it ?
Note: Please suggest solution which works on Template Driven Form. and i forgot to mention i am using Angular 2.4.8 version.

A: Not sure why you wouldn't use Reactive Forms - they are pretty much designed for validation.
You can also mix and match , you aren't locked into using Template Driven Forms just because you are using ngModel.
You can utilise Reactive Forms just for validation.
component.ts
form: FormGroup;

  constructor(fb : FormBuilder) {
    this.form = fb.group({
      'firstName' : ['', Validators.required],
      'lastName' : ['', Validators.required]
    })

  }

  hasError(n: string){
    return this.form.get(n).hasError('required') && this.form.get(n).touched;
  }

template.html

Child

  <input [ngModel]="firstName" name="firstName"  [formControl]="form.get('firstName')" required>

This field is required

  <input [ngModel]="lastName" name="lastName"  [formControl]="form.get('lastName')" required>

This field is required

Plunkr found here


text:
Q: Groovy implicit spread-dot operator So, in Groovy, list.elementProp yields the same result as list*.elementProp.
Junior members on the team seem to keep using this feature unintentionally.
I can't find any reference to this behavior in the Groovy docs. Can anyone point me to such documentation?
Edit: The flagged duplicate question pertains to how it works, not where it is documented.

A: It's here
http://docs.groovy-lang.org/latest/html/documentation/#gpath_expressions
In the GPath expressions section


text:
Q: How can I generate random numbers in python using random? I tried to code it using randint and got an attribute error for it.
import random
def generate(start,end,n):
    res=[]
    for j in range(n):
        res.append(random.randint(start,end))
    return res
start=1
end=15
n=5
print(generate(start,end,n))

The interpreter produced the following error:
AttributeError: module 'random' has no attribute 'randint'

This code doesn't raise an error in idle.

A: Check your files name! In your case "random" is key word, you can not use "random" as a file name. Take care that no files are named random.py.


text:
Q: How to modify a value in one "cell" of a pandas data frame? I have a very simple problem. I would like to change a value in a given column of a given row of a pandas data frame. I try to do it in the following way:
df['column3'].loc[this_date] = val

As a result I get the following warning:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

My interpretation of this warning is that by using columns name ('column3') and loc I do not really access (refer to) the desired cell of the data frame. Instead, I create an object which is a copy of the "cell" object and then I try to change the value associated with this "copy-object".
What I do not understand is that it seems to work. In spite on the fact that pandas writes me that I try to modify the copy, I do modify the original data frame.
My question is how to make sure that I am really doing what I would like to do and how to do it in a "correct" way so that the pandas does not complain?

A: The reason of getting the warning is that df itself is a copy of some other dataframe object. I guess that you have some original dataframe df_origin and you get df from df_origin by some operation such as slicing. So df is a copy of df_origin. Then you try to set some value to df and the warning raises to tell you that this would not change the value in the original dataframe df_origin.
One solution is to use a single variable to point to the dataframe object before and after slicing if you don't care for df_origin. Otherwise you can suppress the warning by pd.set_option('mode.chained_assignment', None)
Your way of setting value is fine, along with the following ones:
 df.ix[this_date, 'column3'] = val
 df.loc[this_date, 'column3'] = val
 df.at[this_date, 'column3'] = val


text:
Q: How to Prove this Double-Sided Trigonometric Integral Inequality How can I prove this inequality?

$$\frac{\pi}{2} \leq \int_0^{\frac{\pi}{2}} \sqrt{1+\frac{sin^2(x)}{2}} dx \leq \frac{\pi}{2}\sqrt{\frac{3}{2}}$$

I don't know how to start this problem, I tried to compute the integral but it is difficult for me.
Can someone help me to prove this? Thank you for your time.

A: Expanding on @AndreNicolas's comment, we can see that the graph of$$\sqrt{1+\frac{\sin^2(x)}{2}}$$ lies in between the boxes defined by $y=1$ and $y= \sqrt{3/2}$; thus its integral is greater than the area of the first box which is $(height)*(width) = 1\times \pi/2$ and the area of the second box $(height)*(width) = \sqrt{3/2} \times \pi/2.$
This is just a specific case of the general result: $f \le g \le h$ on $[a,b]$ implies that $$\int_a^b f(x) dx \le \int_a^b g(x) dx \le \int_a^b h(x) dx$$


text:
Q: Hibernate + JPA + Maven + Tomee + Eclipse I'm struggling to set up a very small Rest API using JAX-RS + Hibernate + H2 as DB on tomcat 8.5.
After struggling so much with dependencies, testing Git sample , nothing worked so far.
So :
Pom is like :
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>dataprovider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jersey.version>2.36</jersey.version>
        <org.json.version>20210307</org.json.version>
        <hibernate.version>6.0.0.Final</hibernate.version>
        <h2.version>[2.1.212,)</h2.version>
        <javax.persistence.version>2.2</javax.persistence.version>
        <junit.jupiter.version>5.8.1</junit.jupiter.version>
        <junit.platform.version>1.8.1</junit.platform.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
            </plugin>

        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-common</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>project</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.ext</groupId>
            <artifactId>jersey-bean-validation</artifactId>
            <version>${jersey.version}</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>${org.json.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>${javax.persistence.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.10</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>${h2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-params</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-suite</artifactId>
            <version>${junit.platform.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

Web.xml is like
<display-name>dataprovider</display-name>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>

</welcome-file-list>
<display-name>DataProvider</display-name>
<servlet>
    <servlet-name>DataProvider-servlet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.demo.provider.FutureApplication</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>DataProvider-servlet</servlet-name>
    <url-pattern>/api/v1/*</url-pattern>
</servlet-mapping>

Persistence.xml :
<persistence-unit name="dataproviderPU">

        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <jta-data-source>jdbc:h2:mem:db1</jta-data-source>
        <properties>
            <property name="hibernate.ejb.cfgfile" value="hibernate.cfg.xml"/>
        </properties>

    </persistence-unit>

hibernate.cfg.xml
<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:mem:db1</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>
        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>
        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create-drop</property>
        <!-- dbcp connection pool configuration -->
        <property name="hibernate.dbcp.initialSize">5</property>
        <property name="hibernate.dbcp.maxTotal">20</property>
        <property name="hibernate.dbcp.maxIdle">10</property>
        <property name="hibernate.dbcp.minIdle">5</property>
        <property name="hibernate.dbcp.maxWaitMillis">-1</property>
        <mapping class="com.demo.provider.entities.Lobby" />
    </session-factory>
</hibernate-configuration>

And finally , error is :
 Jun 24, 2022 4:42:41 PM jdk.internal.reflect.NativeMethodAccessorImpl invoke
    SEVERE: ContainerBase.addChild: start:
    org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/dataprovider]]
...
    Caused by: org.apache.tomee.catalina.TomEERuntimeException: org.apache.openejb.OpenEJBException: Creating application failed: C:\Shared\Apps\tomeeWS\webapps\dataprovider: org.apache.openejb.OpenEJBRuntimeException: java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider cannot be cast to class javax.persistence.spi.PersistenceProvider (org.hibernate.jpa.HibernatePersistenceProvider is in unnamed module of loader org.apache.tomee.catalina.TomEEWebappClassLoader @149ab762; javax.persistence.spi.PersistenceProvider is in unnamed module of loader java.net.URLClassLoader @2f686d1f): java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider cannot be cast to class javax.persistence.spi.PersistenceProvider (org.hibernate.jpa.HibernatePersistenceProvider is in unnamed module of loader org.apache.tomee.catalina.TomEEWebappClassLoader @149ab762; javax.persistence.spi.PersistenceProvider is in unnamed module of loader java.net.URLClassLoader @2f686d1f)

  ...
        Caused by: org.apache.openejb.OpenEJBException: Creating application failed: C:\Shared\Apps\tomeeWS\webapps\dataprovider: org.apache.openejb.OpenEJBRuntimeException: java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider cannot be cast to class javax.persistence.spi.PersistenceProvider (org.hibernate.jpa.HibernatePersistenceProvider is in unnamed module of loader org.apache.tomee.catalina.TomEEWebappClassLoader @149ab762; javax.persistence.spi.PersistenceProvider is in unnamed module of loader java.net.URLClassLoader @2f686d1f): java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider cannot be cast to class javax.persistence.spi.PersistenceProvider (org.hibernate.jpa.HibernatePersistenceProvider is in unnamed module of loader org.apache.tomee.catalina.TomEEWebappClassLoader @149ab762; javax.persistence.spi.PersistenceProvider is in unnamed module of loader java.net.URLClassLoader @2f686d1f)
...
        Caused by: org.apache.openejb.OpenEJBException: org.apache.openejb.OpenEJBRuntimeException: java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider cannot be cast to class javax.persistence.spi.PersistenceProvider (org.hibernate.jpa.HibernatePersistenceProvider is in unnamed module of loader org.apache.tomee.catalina.TomEEWebappClassLoader @149ab762; javax.persistence.spi.PersistenceProvider is in unnamed module of loader java.net.URLClassLoader @2f686d1f): java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider cannot be cast to class javax.persistence.spi.PersistenceProvider (org.hibernate.jpa.HibernatePersistenceProvider is in unnamed module of loader org.apache.tomee.catalina.TomEEWebappClassLoader @149ab762; javax.persistence.spi.PersistenceProvider is in unnamed module of loader java.net.URLClassLoader @2f686d1f)
...
Caused by: org.apache.openejb.OpenEJBRuntimeException: java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider cannot be cast to class javax.persistence.spi.PersistenceProvider (org.hibernate.jpa.HibernatePersistenceProvider is in unnamed module of loader org.apache.tomee.catalina.TomEEWebappClassLoader @149ab762; javax.persistence.spi.PersistenceProvider is in unnamed module of loader java.net.URLClassLoader @2f686d1f)
 ...
       Caused by: java.lang.ClassCastException: class org.hibernate.jpa.HibernatePersistenceProvider cannot be cast to class javax.persistence.spi.PersistenceProvider (org.hibernate.jpa.HibernatePersistenceProvider is in unnamed module of loader org.apache.tomee.catalina.TomEEWebappClassLoader @149ab762; javax.persistence.spi.PersistenceProvider is in unnamed module of loader java.net.URLClassLoader @2f686d1f)

I suppose there is mismatch between version but I'm not able to find one fully fonctionnal...
Does anyone have any ideas what I'm doing wrong ?
Thanks


text:
Q: Postfix Configuration - different servers for subdomains and domain I have a following setup:
1 postfix server: a.example.com that needs to accept all emails for any subdomain on example.com (*@*.example.com) and delivers to mailman account and also send emails to any email account (gmail, yahoo, etc) including *@example.com.
1 hosted exchange: exch11.hosted.com for example.com emails (*@example.com).
Everything works in this setup except sending emails from a.example.com to *@example.com (exch11.hosted.com).
If I have example.com in mydomains.db file, then a.example.com does not send out *@example.com emails and delivers locally. if I change it to *.example.com then it sends *@example.com emails to exch11.hosted.com but now does not accept *@subdomain.example.com emails and shows an error that Relay is not allowed (it should not be relaying and delivering to local maildir account).
Main requirement is to have a.example.com accept mail for any subdomain and deliver emails for main domain to exch11.hosted.com. Can anyone please help me or point me towards right direction?
Any help is welcome.
Thanks.
main.cf:
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
mydestination = hash:/etc/postfix/mydomains
unknown_local_recipient_reject_code = 550
alias_maps = hash:/etc/aliases
home_mailbox = Maildir/
smtpd_banner = mail.example.com

debug_peer_level = 2
debugger_command =
     PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
     xxgdb $daemon_directory/$process_name $process_id & sleep 5

sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.3.3/samples
readme_directory = /usr/share/doc/postfix-2.3.3/README_FILES
virtual_alias_maps = hash:/etc/postfix/virtual, pcre:/etc/postfix/virtual.pcre
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname
smtp_sasl_security_options = noplaintext
#smtpd_sender_restrictions = check_sender_access hash:/etc/postfix/sender-access
smtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/inbound-access,permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
mailbox_size_limit = 25600000
transport_maps = hash:/etc/postfix/transport
message_size_limit = 20240000

virtual.pcre and virtual:
/(.*)@[^.]*\.example\.com$/ mailman

transport:
# demo
.demo.example.com   smtp:192.168.100.161:25
# demo mail
demo.example.com    smtp:192.168.100.161
# Demo2
.demo2.example.com  smtp:192.168.100.221:25
# demo2 domain
demo2.example.com   smtp:192.168.100.221

mydomains:
localhost       OK
mail.local  OK
example.com     OK

A: First of all i am not sure if this will work but i hope it will help get you started:

*

*Remove example.com from mydomains as this postfix instance does not handle the mail for it directly.

*Add virtual_alias_domains = .example.com this should solve your subdomain issue

*Add relay_domains = example.com and specify an explicit transport for example.com, e.g: example.com :[exch11.hosted.com]


text:
Q: I want input to be available in all methods, how do I declare it? So what I'm trying to do is have my main method where I call other methods into it to process various bits of user input code.
Rather than writing System.in every time, I want to define input outside everything and the whole class will recognise what that means.
This is what I have:
public static final Scanner input = new Scanner(System.in);

But it doesn't seem to work as intended and my program falls apart as soon as I pull the next method into the main method. I've been researching this but I don't understand the answers in relation to what I'm attempting to do.
Can anyone help?
As requested, here's the exception I'm getting:
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at question1project.TeleSurvey.ageInput(TeleSurvey.java:83)
    at question1project.TeleSurvey.main(TeleSurvey.java:38)

And the line in my code it's throwing the exception at:
a = input.nextInt();

A: You're calling Scanner.nextInt() as the documentation says, if the next input is not an integer literal then it will throw InputMismatchException.
You should check the input if it's an integer, if you're not expecting input to be integer then you should use the appropriate method of Scanner.
For sharing the input among classes, you can assign it to a public static variable of a class.


text:
Q: Store java 5 and java 6 JARs in Maven Repo I think I need to store both Java 5 and Java 6 versions of the same jar in our internal Maven repository (Nexus). How?
I thought that I might be able to specify a classifier in the deploy plugin config ...
<build>
    <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.5</version>
            <configuration>
                <classifier>${jvmClassifier}</classifier>
            </configuration>
        </plugin>

but it is ignored!

A: You should use the version attribute, i.e. if you have both Java 5 and 6 jars of the version 2.1, then the "full" version will be 2.1-jdk15 and 2.1-jdk16. UISpec4J uses this approach - uispec4j-2.3-jdk16.jar and uispec4j-2.3-jdk15.jar

A: You can obtain different builds for different versions of the Java platfom, using different Maven profiles that specify the compiler versions for the maven compiler plugin (1.5 in one, and 1.6 in another). A hint is provided in the Sonatype book titled "Maven - The Complete Reference".
For the purpose of distinguising the JARs from each other, the other answer provides a really good hint. If you wish to achieve the same, you'll need to tweak the jar:jar task in each of the profiles to generate different jars that can then be deployed to the local repository.

A: It is ignored because classifier is NOT a parameter of deploy:deploy which is the goal bound to the deploy phase (it's a parameter of deploy:deploy-file though).
Put the classifier in the configuration of the jar/war/ear plugin. Here is a pom.xml simulating the desired behavior (you should probably use profiles):
<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>
  <properties>
    <jvmClassifier>jdk16</jvmClassifier>
  </properties>
  <groupId>com.stackoverflow.q3341837</groupId>
  <artifactId>Q3341837</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>Q3341837</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.3.1</version>
        <configuration>
          <classifier>${jvmClassifier}</classifier>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <altDeploymentRepository>mine::default::file://${basedir}/target/my-repo</altDeploymentRepository>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Here is what I get after running mvn deploy:

$ mvn clean deploy
...
$ tree target/my-repo/
target/my-repo/
└── com
    └── stackoverflow
        └── q3341837
            └── Q3341837
                ├── 1.0-SNAPSHOT
                │   ├── maven-metadata.xml
                │   ├── maven-metadata.xml.md5
                │   ├── maven-metadata.xml.sha1
                │   ├── Q3341837-1.0-20100727.222050-1.pom
                │   ├── Q3341837-1.0-20100727.222050-1.pom.md5
                │   ├── Q3341837-1.0-20100727.222050-1.pom.sha1
                │   ├── Q3341837-1.0-SNAPSHOT-jdk16.jar
                │   ├── Q3341837-1.0-SNAPSHOT-jdk16.jar.md5
                │   └── Q3341837-1.0-SNAPSHOT-jdk16.jar.sha1
                ├── maven-metadata.xml
                ├── maven-metadata.xml.md5
                └── maven-metadata.xml.sha1


text:
Q: Drawing a circle with an angle using TikZ I'm trying to re-create this picture using TikZ:

I, however, have a very limited understanding of TikZ, and, despite trying to learn how to draw this for an hour or so, have gotten nowhere on my own.

A: A PSTricks solution:
\documentclass{article}

\usepackage{pstricks}
\usepackage{xfp}

% parameters
\def\angle{50}
\def\radius{3}

\begin{document}

\begin{pspicture}%
 (-\radius,-\radius)%
 (\fpeval{\radius+0.4},\fpeval{max((\radius+0.4)*sin(\angle*pi/180),\radius)})
  \pscircle(0,0){\radius}
  \psline(\radius;\angle)(0,0)(\radius;0)
  \psarc{|-|}{\fpeval{\radius+0.3}}{0}{\angle}
  \rput(\fpeval{\radius/2},-0.2){$r$}
  \rput*(\fpeval{(\radius+0.3)*cos(\angle/2*pi/180)},
         \fpeval{(\radius+0.3)*sin(\angle/2*pi/180)}){$s$}
  \psarc{->}{\fpeval{\radius/6}}{0}{\angle}
  \rput(\fpeval{(\radius/6+0.25)*cos(\angle/2*pi/180)},
        \fpeval{(\radius/6+0.25)*sin(\angle/2*pi/180)}){$\theta$}
\end{pspicture}

\end{document}

All you have to do is choose the values of the parameters and the drawing will be adjusted accordingly.

A: Just a finger warm-up exercise with PSTricks.
\documentclass[pstricks,borde=12pt,12pt]{standalone}
\usepackage{pst-eucl}

\begin{document}
\begin{pspicture}[dimen=m](-3,-3)(3,3)
    \pstGeonode[PointName=none,PointSymbol={default,none}]{O}(2;0){A}(2;60){B}
    \pscircle{2}
    \psline(B)(O)(A)
    \pstMarkAngle[MarkAngleRadius=.9,LabelSep=.5,arrows=->]{A}{O}{B}{$\theta$}
    \pcline[linestyle=none](O)(A)\nbput{$r$}
    \psarc{|*-|*}(O){2.3}{(A)}{(B)}
    \rput*{-30}(2.3;30){$s$}
\end{pspicture}
\end{document}

A: One (somehow verbose) option:

The code:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{angles,quotes}

\def\myrad{3cm}% radius of the circle
\def\myang{60}% angle for the arc

\begin{document}

\begin{tikzpicture}
% the origin
\coordinate (O) at (0,0);
% the circle and the dot at the origin
\draw (O) node[circle,inner sep=1.5pt,fill] {} circle [radius=\myrad];
% the ``\theta'' arc
\draw
  (\myrad,0) coordinate (xcoord) --
  node[midway,below] {$r$} (O) --
  (\myang:\myrad) coordinate (slcoord)
  pic [draw,->,angle radius=1cm,"$\theta$"] {angle = xcoord--O--slcoord};
% the outer ``s'' arc
\draw[|-|]
  (\myrad+10pt,0)
  arc[start angle=0,end angle=\myang,radius=\myrad+10pt]
  node[midway,fill=white] {$s$};
\end{tikzpicture}

\end{document}

A: A MetaPost solution. A verbose one, since two macros respectively producing a circular arc and adding bar ends to a path have been included.
To be compiled with the MetaFun format of MetaPost and with the LaTeX engine:
mpost --mem=metafun --tex=latex mydrawing.mp
input latexmp; setupLaTeXMP(options = "12pt", textextlabel = enable, mode = rerun) ;

% Macro drawing a circular arc (radius = 1, centered at origin)
vardef arc(expr theta_min, theta_max) =
  save theta, mystep ;
  mystep = 1; theta = theta_min ;
  dir theta_min
  for theta = theta_min+mystep step mystep until theta_max: .. dir theta endfor
enddef ;

% Macro adding bar ends to any path
vardef drawbarends(expr pat, lmark) =
  draw pat ;
  for t = 0, infinity:
    draw (left -- right) zscaled (0.5lmark * unitvector direction t of pat)
      rotated 90 shifted point t of pat;
  endfor;
enddef;

beginfig(1);
  u := 1cm ; % unit length
  % Full circle
  pair center ; center = origin ; r := 2.75u ;
  draw fullcircle scaled 2r shifted center ;
  % Radii
  theta_min := 0 ; theta_max := 60 ;
  path radius_a, radius_b ;
  radius_a = (center -- center + dir theta_min) scaled r ; draw radius_a ;
  radius_b = (center --  center + dir theta_max) scaled r ; draw radius_b ;
  label.bot("$r$", point 0.5 of radius_a) ;
  % Arc
  myeps := 0.25u ; path p ; p = arc(theta_min, theta_max) scaled (r+myeps) shifted center ;
  drawbarends (p, 4bp) ;
  pair midpoint ; midpoint = point 0.5 along p ;
  picture arclabel ; arclabel = thelabel("$s$", midpoint) ;
  unfill (boundingbox (arclabel) enlarged 1bp) ; draw arclabel ;
  % Angle
  drawarrow anglebetween(radius_a, radius_b, "$\theta$") ;
endfig ;
end.


text:
Q: Wrapping my head around some Linear Algebra Consider the vector space $\Bbb R^d$, where $d$ is a positive integer.
Suppose I have $d+1$ unit vectors $\{v_1,v_2,...,v_{d+1}\} \in \Bbb R^d$ satisfying $\langle v_i, v_j \rangle = -1/d$ for all $i \neq j$.
I know that this condition guarantees that the vectors are "symmetric" around the origin.
(How can I prove that their sum is zero?)
Let $W \in \Bbb R^d$.  Consider the expression $\sum_{i=1}^d v_i \langle v_i, W \rangle $.
In some sense, because $\{v_1,v_2,...,v_{d+1}\}$ is not an orthonormal set,the above expression gathers too many parts of $W$.
How can I adjust this expression (not the unit vectors) so that it is equal to $W$?
I have a hunch it could be: $$W=\frac{d}{d+1} \sum_{i=1}^d  v_i \langle v_i, W \rangle $$
... but don't take my word on it.
Thank you very much for your help!

A: To show their sum is $0$, I think this should work. Notice that for $\mathbb R^2$, we get $<v_1+v_2+
v_3, v_1+v_2, v_3>=(1-1/2-1/2+1)+(1-1/2-1/2)+(1-1/2-1/2)$. For each $v_i$, we get one $1$ in the expansion (since the $v_i$ are unit vectors, we get $<v_i,v_i>=1$, and we get $d$ copies of $-1/d$, for a total sum of $d(1-d(1/d)=0)$): $$<v_1+...+v_d, v_1+...+v_d>=d(1-(d)1)/d)=0 $$. Then $v_1+v_2+....+v_3$ is orthogonal to itself, so it must be the $0$ vector.
For the second question, i.e. (if I understood you correctly), if {$v_i$} is a generating set (it will not be a basis, since it has too-many vectors to be linearly-independent.), you can always use Gram-Schmidt algorithm to turn it into an orthonormal set. Then any vector $w$ in $W$ has an expansion: $$\Sigma_{i=1,2,..,n}<w,v_i>v_i $$ . I hope I understood your question correctly.

A: I'm going to assume that we know that $\sum\limits_{i=1}^{d+1} v_i = 0$ and that $\operatorname{span}\{v_i : 1 \leq i \leq d+1\} = \Bbb{R}^d$. Now, let $X \in \Bbb{R}^d$ and let $X^i \in \Bbb{R}$ such that $X = \sum\limits_{i=1}^{d+1}X^i v_i$. Now, let's consider the sum $\sum v_i \langle v_i, X \rangle$.
$$
\sum_{i=1}^{d+1} v_i \langle v_i, X \rangle = \sum_{i=1}^{d+1} \sum_{j=1}^{d+1} X^j v_i \langle v_i, v_j \rangle = - \frac{1}{d} \sum_{i\neq j} X^j v_i + \sum_{i=1}^{d+1} X^i v_i \\
= - \frac{1}{d} \sum_{j=1}^{d+1} X^j \underbrace{\sum_{i=1}^{d+1} v_i}_{=0} + \Big[1+ \frac{1}{d} \Big] \underbrace{\sum_{i=1}^{d+1} X^i v_i}_{=X} \\= \Big[1+ \frac{1}{d} \Big] X = \frac{d+1}{d} X
$$
therefore, as your initial hunch suggested
$$
\sum_{i=1}^{d+1} v_i \langle v_i, X \rangle  = \frac{d+1}{d} X \implies X = \frac{d}{d+1} \sum_{i=1}^{d+1} v_i \langle v_i, X \rangle.
$$


text:
Q: Validate whether word can be constructed by cycling back and forth between values from two different lists Let's say I have lists of letters from two players
player_1 = ['a', 'b', 'c', 'd', 'e']
player_2 = ['c', 'f',  'x', 'd', 'r']

I'd like to ensure that some submitted word can be constructed by alternating letters between the player_1 list and the player_2 list.
For example fax is a valid word since that can be formed by alternating letters in the following way: P2, P1, P2. Red also works since that can be formed by alternating letters in the same way, even though the letter "d" appears in both player_1 and player_2's hand.
bad does not work since it would require a: P1, P1, P2 combo, which does not alternate.
I'm trying to create a function validate_word that validates that a word can be constructed in this way. Here is my initial attempt that gets a bit too convoluted:
from itertools import cycle
from itertools import chain, repeat

player_1 = ['a', 'b', 'c', 'd', 'e']
player_2 = ['c', 'f',  'x', 'd', 'r']

def validate_word(word):
    sequence_list = []
    for letters in word:
        if letters in player_1 and letters in player_2:
            sequence_list.append(3)
        elif letters in player_1:
            sequence_list.append(1)
        elif letters in player_2:
            sequence_list.append(2)
        else:
            sequence_list.append(0)
    return sequence_list

So now we have a list that contains a number indicating whether a given letter appears in P1 hand, P2 hand, both of their hand (3), or neither of their hands (0).  I was then going to make sure that those numbers cycled either from 1 -> 2 or 2 -> 1, but I'm not quite how to deal with 3s, or whether this is the most efficient way of handling this.
What's a better way of dealing with this?

A: You can combine itertools.cycle and all() to make sure the word can be constructed by alternating the two lists:
from itertools import cycle

def validate_word(p1, p2, w):
    c1 = cycle([p1, p2])
    c2 = cycle([p2, p1])
    return all(ch in next(c1) for ch in w) or all(ch in next(c2) for ch in w)

player_1 = ['a', 'b', 'c', 'd', 'e']
player_2 = ['c', 'f',  'x', 'd', 'r']

print(validate_word(player_1, player_2, 'fax'))
print(validate_word(player_1, player_2, 'red'))
print(validate_word(player_1, player_2, 'bad'))

Prints:
True
True
False


text:
Q: from Linux command line, find number of lines in which a string occurs I have a file in the location /home/someuser/sometext.txt . I want to count the number of lines in which a particular string occurs. What's the way to do that from Linux command line?

A: grep with -c switch is what you need:
grep -c "pattern" /home/someuser/sometext.txt

Alternate solution using awk:
awk '/regex/{c++}END{print c+0}' /home/someuser/sometext.txt

A: You're looking for the grep command.  Here's a basic tutorial.  It's extremely useful for string searching in files.  It also has support for regular expressions.
It looks like you'll do something like this:
grep -c "mystring" /home/someuser/sometext.txt

The -c argument is short for --count and tells grep to print out the number of lines that contain the string.


text:
Q: BUILD file error while implementing Crashylytics in Android using Bazel I have been following this tutorial to implement Crashlytics in my app. I am getting this error while building the apk,
WARNING: The major revision of the Android NDK referenced by android_ndk_repository rule 'androidndk' is 20. The major revisions supported by Bazel are [10, 11, 12, 13, 14, 15, 16, 17, 18]. Bazel will attempt to treat the NDK as if it was r18. This may cause compilation and linkage problems. Please download a supported NDK version.
ERROR: /home/sensen/GIT/UntitledFolder2/tensorflow/SenANPR/BUILD:37:1: in android_library rule //SenANPR:crashlytics_lib: The location of your BUILD file determines the Java package used for Android resource processing. A directory named "java" or "javatests" will be used as your Java source root and the path of your BUILD file relative to the Java source root will be used as the package for Android resource processing. The Java source root could not be determined for "SenANPR". Move your BUILD file under a java or javatests directory, or set the 'custom_package' attribute.
WARNING: /home/sensen/GIT/UntitledFolder2/tensorflow/tensorflow/contrib/lite/java/BUILD:43:12: in srcs attribute of android_library rule //tensorflow/contrib/lite/java:tensorflowlite: please do not import '//tensorflow/lite/delegates/nnapi/java/src/main/java/org/tensorflow/lite/nnapi:NnApiDelegate.java' directly. You should either move the file to this package or depend on an appropriate rule there
ERROR: Analysis of target '//SenANPR:senanpr' failed; build aborted: Analysis of target '//SenANPR:crashlytics_lib' failed; build aborted
INFO: Elapsed time: 0.174s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (1 packages loaded, 155 targets configured)

But I have already declared custom_package in my android_binary.

A: custom_package has to be set for all rules that are in a BUILD file that isn't under a java root, since those rules might be built independently of any other rule. So try setting custom_package for your android_library rule too.

A: just the path to your work should have a folder named java!
If you look at the official examples, they have java folder then the rest of the folders that make up the package name.
https://github.com/google/mediapipe/tree/master/mediapipe/examples/android/src/java/com/google/mediapipe/apps

for me I've this
mediapipe/myAndroidApps/java/net/rmasoft/appName1

Where the package name is net.rmasoft.appname1