text:
Q: How to create a single function in controller? I have these codes in my 2 visualforce pages:
<apex:page standardController="mycontroller" docType="html-5.0" standardStyleSheets="false" extensions="EditDelete" action="{!editItems}" sidebar="false">

<apex:pageMessages />

the same codes is applied to delete page.
currently, I am using 2 methods in  mycontroller to return the apex message.
public PageReference editItems(){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Please click the Edit Batch button to update.'));
    return null;
}
public PageReference deleteItems(){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Please click the Edit Batch button to delete this item.'));
    return null;
}

Is it possible to merge these 2 into 1 method? How will I change the codes in visualforce pages also?

A: First, as an aside, don't specify returning a PageReference if you don't intend to redirect:
public void editBatchItems(){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Please click the Edit Batch button to update.'));
}
public void deleteBatch(){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Please click the Edit Batch button to delete this item.'));
}

In order to specify a message, you'd have to pass a parameter in, which you can do, but it might not be worth it. Here's what that might look like:
public transient Integer messageId { get; set; }
public void showMessage() {
  String[] messages = new String[] {
    'Please click the Edit Batch button to update.',
    'Please click the Edit Batch button to delete this item.'
  };
  ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, messages[messageId]));
}

There's other ways to do this, but ultimately, as you can see, you end up writing more code, not less; you'd also have to modify your buttons:
<apex:commandButton action="{!showMessage}" value="Edit">
  <apex:param name="theMessageId" value="0" assignTo="{!messageId}" />
</apex:commandButton>

Ultimately, you're not really saving much unless you had to do this for a bunch of buttons, and realistically, it'd still probably be a bad idea. For a simple one-line method, it's realistically not worth the time to try and and be "DRY" about it.


text:
Q: typeerror undefined is not a function liferay I am getting the json data from the server like 1,User,2,Courses,3,Organization correctly, this data I am storing in a variable entities, now I am adding this json data for text field for auto complete and then allow multiple values for the text box(tabs) like in the below image.
,
I am getting the exception like typeerror undefined is not a function in the alert('entities from the 466 line '+e);
Can any one help me?
AUI().ready('aui-textboxlist', function(A) {
try {
    alert('before calling selectEntities()');
    var entities = selectEntities();
    console.log(" entities "+entities);
    alert("entities from the server "+entities);

    entitiesBoxList = new A.TextboxList({
        contentBox: '#<portlet:namespace />entitiesDiv',
        dataSource: entities,
        matchKey: 'name',
        schema: {
            resultFields: ['id', 'name']
        },
        queryMatchContains:true,
        queryDelimiter : ',',
        after: {
            render: function() {
                try{
                    var instance_ = this;
                    var index = 0;
                    this.entries.insert(index, entry);
                }catch (e) {
                    alert("exception raised at 461 line"+e);
                }
            }
        }
    }).render();
} catch(e){
    alert('entities from the 466 line '+e);
}

}

A: You said it is on the line with:
alert('entities from the 466 line '+e);

Then it's either saying your alert() is not a function (unlikely)
or something in your 'e' value. Since you said it contains JSON data, maybe it's because you aren't parsing the data correctly?
Possibly better: I noticed you have a function called selectEntities() on line 3. Maybe it's referring to that line and you have a binding issue.

A: Actually the above code works fine in Liferay-6.06, I am trying to migrate it to Liferay-6.2, so the AUI version in 6.06 is not works in 6.2:
    AUI().ready('aui-textboxlist-deprecated', function (A) {

        // code that uses A.TextboxList goes here
    });

the code is for 6.2. For 6.1, we have to use aui-textboxlist instead of aui-textboxlist-deprecated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is int main(void) valid in C++? C++ standard lists allowed forms of main. It doesn't list int main(void) as an allowed form. But, it generally states that

The parameter list (void) is equivalent to the empty parameter list

Is int main(void) an allowed form?

A: From N3936 standard draft:

3.6 Start and termination
3.6.1 Main function
2 An implementation shall not predefine the main function. This
  function shall not be overloaded. It shall have a declared return type
  of type int, but otherwise its type is implementation-defined. An
  implementation shall allow both
— a function of () returning int and
— a function of (int, pointer to pointer to char) returning int
as the type of main (8.3.5).

Then:

8.3.5 Functions
4 ...
  A parameter list consisting of a single unnamed parameter of
  non-dependent type void is equivalent to an empty parameter list.
  ...

Consequently,
int main(void)

is an allowed form of main function.

A: In addition to comment of @Some programmer dude and @Edgar's answer, this is the part of N3936 draft which explains given difference between C++ and standard C:

C.1.7 Clause 8: declarators [diff.decl]
8.3.5
Change: In C++, a function declared with an empty parameter list takes
  no arguments. In C, an empty parameter list means that the number and
  type of the function arguments are unknown.
Example:
int f(); // means int f(void) in C++
            // int f( unknown ) in C


text:
Q: Is it possible to specify that a function argument must be a string literal? This fragment refuses to compile because format!() won't touch non-literal strings.
fn cond_format<T: std::fmt::Display>(cond: bool, fmt_str: &'static str, item: T) -> String {
    if cond {
        format!(fmt_str, item)
    } else {
        format!("{}", item)
    }
}

A: No.  Macros are expanded before types, names, or values even exist.  There's no possible way for that to work.  As a result, there's no reason for the language to distinguish between literals and non-literals at runtime: even if there was, nothing would be able to use that information.
You have to use a macro.  Below are two plausible ways of doing this.
macro_rules! cond_format {
    ($fmt_str:expr) => {
        |cond: bool, item| -> String {
            if cond {
                format!($fmt_str, item)
            } else {
                format!("{}", item)
            }
        }
    };

    ($cond:expr, $fmt_str:expr, $item:expr) => {
        if $cond {
            format!($fmt_str, $item)
        } else {
            format!("{}", $item)
        }
    };
}

fn main() {
    println!("{}", cond_format!("{:x}")(false, 42));
    println!("{}", cond_format!(true, "{:x}", 42));
}

A: According to Rust docs, this is not possible:

(...) you can see that the first argument is a format string. It
  is required by the compiler for this to be a string literal; it cannot
  be a variable passed in (in order to perform validity checking).


text:
Q: What's the correct way to store a list in MySQL? I'm trying to make a list of numbers structure in MySQL (phpMyAdmin), I was thinking about storing it as a varchar with commas between all the numbers, and then when I want to fetch them I just split them, but I'm not sure if this is the best way to do it.
~Sorry if I wasn't clear, my English isn't that good.

A: Depending on the length of the number, probably you can use just use TEXT data type.

A: with explode function you can separate your data with specified character and store into array
ex.
$demo = '1,2,3,4';
$data = explode(',',$demo);

this with store 1,2,3,4 separately in data array


text:
Q: c# .net core TagBuilder It doesn't show the tag part I want to print my table in the infinite category system to my cshtml screen with tagbuilder. writes some of it. some of it is not written. please help me.
c# codes:
public IActionResult Index()
        {
            var tb = new TagBuilder("ul");
            using (SqlDbContext vt = new SqlDbContext())
            {

                var Kategori = from i in vt.urunKategorileri
                               where i.urunKategorileriUstId == 0
                               select i;

                foreach (urunKategorileri anamenu in Kategori)
                {
                    tb.InnerHtml.AppendHtml("
" + anamenu.urunKategorileriKategoriAdi + ""+ Altkategori(anamenu.urunKategorileriId) + "
");
                }

            }
                return View(tb);
        }

        private TagBuilder Altkategori(int id)
        {
             TagBuilder eb = new TagBuilder("ul");
            using (SqlDbContext a = new SqlDbContext())
            {

                var say = (from i in a.urunKategorileri
                           where i.urunKategorileriUstId == id
                           select i).Count();
                if (say > 0)
                {
                    TagBuilder ab = new TagBuilder("
");
                    var altKat = from i in a.urunKategorileri
                                 where i.urunKategorileriUstId == id
                                 select i;

                    foreach (urunKategorileri altkategori in altKat)
                    {
                        ab.InnerHtml.AppendHtml("
" + altkategori.urunKategorileriKategoriAdi + ""+ Altkategori(altkategori.urunKategorileriId)+ "
");
                    }

                    return ab;
                }
            }

            return eb;
        }

cshtml codes:
@model TagBuilder

@{
    ViewData["Title"] = "Home Page";
}

@Model

screenshot:

console output:

In the console, the sub-categories should normally be listed in the section that says "Microsoft.AspNetCore.Mvc.Rendering.TagBuilder" inside the li tag. but it's not working.

A: You need to convert TagBuilder.InnerHtml to string,if you want to append it to html:
public IActionResult Index()
        {
            var tb = new TagBuilder("ul");
            using (SqlDbContext vt = new SqlDbContext())
            {

                var Kategori = from i in vt.urunKategorileri
                               where i.urunKategorileriUstId == 0
                               select i;

                foreach (urunKategorileri anamenu in Kategori)
                {
                    string html = "";
                    using (var writer = new System.IO.StringWriter())
                    {
                        Altkategori(anamenu.urunKategorileriId).InnerHtml.WriteTo(writer, HtmlEncoder.Default);
                        html = writer.ToString();
                    }
                    tb.InnerHtml.AppendHtml("
" + anamenu.urunKategorileriKategoriAdi + "" + html + "
");
                }

            }
            return View(tb);
        }


text:
Q: A monomorphism from a colimit Let $D$ be an upward directed poset, and suppose I have a diagram $F: D\to C$ in a cocomplete category such that $F(d)\to c$ is a monomorphism for all $d\in D$ for some $c\in C.$ Is it true that $\operatorname{colim}_DF\to c$ is also a monomorphism?
When $D$ is the empty category this is vacuously true. But in general, I don't how this works. An insight to answer this question would be greatly appreciated.

A: It is not true that this is vacuously true when $D=\emptyset$ !
In fact there are counterexamples. Indeed, if $D=\emptyset$, $colim_D F$ is an initial object of $C$, so you're asking : is $\emptyset \to c$ always a monomorphism ?
The answer is no: in the category of (unital) rings, $\emptyset = \mathbb Z$ and you have a morphism $\mathbb Z\to \mathbb Z/p$ which is not a monomorphism (left as an exercise)
If you allow $D$ to be nonempty, there will be more examples. For instance, let's dualize, and ask : if every $c\to F(d)$ is an epimorphism, is $c\to\lim_{D^{op}} F$ an epimorphism ?
The answer is more intuitively clear: no in general. For instance, let $D= \mathbb N$ and the functor $D^{op}\to Ab$ sends $n\mapsto \mathbb Z/p^n$, with the canonical projection maps for $n\leq m$. Then $\mathbb Z\to \mathbb Z/p^n$ is an epimorphism for all $n$, but $\mathbb{Z\to Z}_p := \lim_n \mathbb Z/p^n$ is not.
Suppose however that you have a "forgetful" functor $U: C\to Set$ which preserves nonempty directed colimits, and such that $f$ is a monomorphims if and only if $U(f)$ is. Then the claim holds in $C$ (because it does in $Set$) - so most algebraic categories work in this respect (note that in the previous example, we had $C=Ab^{op}$, and not $Ab$)


text:
Q: How to export from within an imported module's Promise? I'm trying to work around the fact that I need to import a pure ESM package into a non-module. I can't change that fact about the script.
The workaround I'm trying to use is the import() function (a "dynamic import"). That returns a Promise instead of the actual module. I can't use await since I'm not in a module, so instead I'm using .then().
The pure ESM package (unist-util-visit) is used in a function exported by my script, which is then used in another script. So the import chain goes:
importer.js imports imported.js imports unist-util-visit
So the issue is that anything I export from within the .then() function in imported.js does not show up in importer.js.
And it's not even a timing issue. I used an EventEmitter to make importer.js wait until imported.js's .then() is done executing:
imported.js:
const EventEmitter = require('events');

module.exports.emitter = new EventEmitter();
module.exports.outsideFxn = function () {
  console.log('hello');
}
import('unist-util-visit').then((unistUtilVisit) => {
  module.exports.fxn = function() {
    console.log(`unistUtilVisit: ${typeof unistUtilVisit}`);
  }
  module.exports.emitter.emit('ready');
});

importer.js:
import('./imported.js').then((imported) => {
  console.log("In importer.js's .then():");
  console.log('  fxn:', imported.fxn);
  console.log('  outsideFxn:', imported.outsideFxn);
  imported.emitter.on('ready', () => {
    console.log("After imported.js is done:")
    console.log('  fxn:', imported.fxn);
  });
});

When I execute it, this is the output:
$ node importer.js
In importer.js's .then():
  fxn: undefined
  outsideFxn: [Function (anonymous)]
After imported.js is done:
  fxn: undefined

What am I missing? Why are no exports being defined in the .then() function? How can I get my function exported?

A: Instead  of
import('unist-util-visit').then((unistUtilVisit) => {
  module.exports.fxn = function() {
    console.log(`unistUtilVisit: ${typeof unistUtilVisit}`);
  }
  module.exports.emitter.emit('ready');
});

where you attempt to modify your module's exports after it has probably been consumed by dependents, why not export a promise that yields the function when it completes?
module.exports.fxnP =
    import('unist-util-visit')
      .then((unistUtilVisit) => () => {
          console.log(`unistUtilVisit: ${typeof unistUtilVisit}`);
      });

Now you consume it:
import('./imported.js').then((imported) => {
    imported.fxnP.then((fxn) => {
        fxn();
    });
});

or, more neatly::
import('./imported.js')
    .then(({fxnP}) => fxnP)
    .then((fxn) => fxn());

A: You could use a custom require hook like jiti which can do exactly what you want synchronously.
Without hooking require:
$ node test.cjs

// test.cjs
const jiti = require('jiti')();
const unistUtilVisit = jiti("unist-util-visit");

Hooking require programmatically:
$ node test.cjs

// test.cjs
require('jiti')().register();
const unistUtilVisit = require("unist-util-visit");

Hooking require through a command line option:
$ node -r jiti/register test.cjs

// test.cjs
const unistUtilVisit = require("unist-util-visit");


text:
Q: How to type a Typescript array to accept only a specific set of values? I am writing a type declaration file for a library I do not control. One of the methods accepts an array of strings as a parameter, but these strings can only be very specific values. Currently I am typing this parameter as a string[], but I was wondering if there was a way to enhance this to include the specific values as well.
Example source (I cannot change this):
Fruits(filter) {
    for (let fruit of filter.fruits)
    {
        switch(fruit)
        {
            case 'Apple':
                ...do stuff
            case 'Pear':
                ...do stuff
            default:
                console.error('Invalid Fruit');
                return false;
        }
    }
    return true;
}

My current type declaration:
function Fruits(filter: FruitFilter): boolean;

interface FruitFilter {
    fruits: string[];
}

As I was writing this question I came up with a partial solution by defining a union type of the strings that are valid, then setting the type of the field to an array of that union rather than an array of strings. This gives me the checking I want, but I noticed that if you enter an invalid string, it marks all of the strings in the array as invalid with the error Type 'string' is not assignable to type 'Fruit'. Is there a better way of doing this so that only the offending string is marked as invalid, or is this as close as I'm going to get?
Partial solution:
function Fruits(filter: FruitFilter): boolean;

type Fruit = 'Apple' | 'Pear'

interface FruitFilter {
    fruits: Fruit[];
}

A: You might also use Enums for that:
enum Fruits {
    Apple,
    Pear,
}

interface FruitFilter {
    fruits: Array<Fruits>;
}

These will be converted to 0 and 1 in plain Javascript.
If you need to, you can also use strings instead of numbers. Then you had to define the enums like that:
enum Fruits {
    Apple = 'Apple',
    Pear = 'Pear',
}

The TypeScript doc has some more examples and how this is being used at runtime:
https://www.typescriptlang.org/docs/handbook/enums.html#enums-at-runtime

A: It works as well, if you don't want a type
export interface MyInterface {
   fruits: Array<'apple' | 'pear' | 'strawberry'>
}

A: So, your problem seems to be this:
type Fruit = "Apple" | "Pear";
interface FruitFilter {
  fruits: Fruit[];
}
declare function Fruits(filter: FruitFilter): boolean;
Fruits({ fruits: ["Apple", "Apple", "Pear"] }); // okay
Fruits({ fruits: ["Apple", "App1e", "Pear"] }); // error
// actual error: ~~~~~~~  ~~~~~~~  ~~~~~~ <-- string not assignable to Fruit
// expected error:        ~~~~~~~ <-- "App1e" not assignable to Fruit

It's not that you have an error, but that the error isn't properly constrained to the "bad" elements of the array.
My guess about why this is happening is that the compiler tends to widen string literals to string and tuple types to arrays unless you give it hints not to do that.  Therefore, when it can't verify that the fruits is of type Fruit[], it backs up and looks at what you gave it.  It widens ["Apple", "App1e", "Pear"] to string[] (forgetting both about the string literals and the fact that it is a three-element tuple), realizes that string[] is not assignable to Fruit[], and then proceeds to warn you about this by flagging each element.  I did a brief search of GitHub issues to see if this has ever been reported, but I haven't seen it.  It may be worth filing something.
Anyway, to test my guess, I decided to alter the declaration of Fruits() to hint that we want a tuple of string literals if at all possible.  Note that there is currently no convenient way to do this; the ways to do hinting right now are, uh, alchemical:
// ⚗❓
declare function Fruits2<S extends string, T extends S[] | [S]>(arr: {
  fruits: T & { [K in keyof T]: Fruit };
}): boolean;
Fruits2({ fruits: ["Apple", "Apple", "Pear"] }); // okay
Fruits2({ fruits: ["Apple", "App1e", "Pear"] }); // error
//                          ~~~~~~~ <--string is not assignable to never

Well, the placement of that error is where you want it, although the message is possibly still confusing.  That's what happens when the compiler tries to assign "Apple" to the intersection Fruit & "App1e" which doesn't exist.  The compiler reduces Fruit & "App1e" to never... correctly, but possibly a bit too soon for the error message to be useful.
Anyway, I don't recommend this "solution" since it's much more complicated and only gives you a somewhat better error experience in error situations.  But at least this is something like an answer as to why it's happening, along with a possible direction for how to address it (e.g., find or file an issue about it).  Okay, good luck!
Link to code


text:
Q: regex ignore (stop capture) strings encapsulated in square brackets I have a string containing text, in this text there are several domains included such as google.de www.google.de etc...
I want to capture these, but ignore domain encapsulated in square brackets. At the moment I have the following:
https://regex101.com/r/t8IMd1/3
It doesn't ignore the encapsulated one though I used a negative lookahead.
What I have to do if more than one domain is in one line?

I don't get it at the moment, so I try to list all requirements and hope someone can provide a explained solution:

*

*domain names can be www.domain.de || domain.de || domain.de/something

*its a multiline text string, so the domains can occur on one line beside each other or in different lines

*they are divided by one or more whitespaces

*when domains are encapsulated in [domain] or [noscript]domain[/noscript] they have to be ignored


text:
Q: Check empty fields on mongoose I have this function on my node REST API
var router = express.Router();

/*router.get('/getUsers', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});*/

router.route('/Users')
  .get(function(req,res){
      User.find(function(err,users){
        if(err)
          res.send(err);

        console.log('GET request');
        res.json(users);
      });
})
  .post(function(req,res){
      var user = new User();
      user.name = req.body.name;
      user.lastName = req.body.lastName;

      if(!user.name || !user.lastName){
        user.save(function(err){
          if(err)
            res.send(err);

          console.log('POST request');
          res.json({message:'Usuario creado'});
        });
      }else{
        res.json({message:'Campos vacíos'});
      }

  });

It works but when I a send a POST  request with empty parameters it saves a document in mongoDB without the name and lastName fields and if(!user.name || !user.lastName) doesn't work to avoid it

A: Well
if (!user.name || !user.lastName) ...
checks that at least one of both must be empty / null / undefined and only then saves it - exactly what you describe as your problem :)
So I guess you want something like
if(user.name && user.lastName)...

Or alternatively swap the code blocks in if / else branch
if(!user.name || !user.lastName){
  res.json({message:'Campos vacíos'});
}else{
  user.save(function(err){
    if(err)
      res.send(err);
    console.log('POST request');
    res.json({message:'Usuario creado'});
  });
}


text:
Q: Arduino UNO, GRBL, OpenCncPilot, max velocity/speed, max acceleration, for laser cutting I am testing GRBL for laser cutting..
In (defaults.h), i set default velocity to 40000mm/min, and default acceleration to 4000mm/sec2.
#ifdef DEFAULTS_GENERIC
// Grbl generic default settings. Should work across different machines.
#define DEFAULT_X_MAX_RATE 40000.0 // mm/min
#define DEFAULT_Y_MAX_RATE 40000.0 // mm/min
#define DEFAULT_Z_MAX_RATE 40000.0 // mm/min
#define DEFAULT_X_ACCELERATION  (4000.06060) // 106060 mm/min^2 = 10 mm/sec^2
#define DEFAULT_Y_ACCELERATION (4000.06060) // 106060 mm/min^2 = 10 mm/sec^2
#define DEFAULT_Z_ACCELERATION (4000.06060) // 106060 mm/min^2 = 10 mm/sec^2
In (config.h) i define machine configuration.
#define DEFAULTS_GENERIC
in G-Code i set feed rate to 20000mm/min (F20000).
But i get very slow move movements, anybody knows why?

A: First I would check your hardware juper setup since usually it is possible to use the so called microsteps that in fact multiplies the number of steps needed for 1 stepper motor revolution by 2,4,8,16... Second you need to check the number of steps per revolution of your stepper motor (usually is 200, but are commonly used also 4,8,16..400 variants). Then see the diameter of your pulleys to calculate the linear movement done by the machine for one revolution of your stepper motor. You are ready now to do your math to adapt the variable settings to your hardware.
Moreover, once you have done your math, maybe, you will realize that your parameters are too high for your machine and the stepper motors simply are not able to keep up with the high rate of pulses that you are sending to them. This is why, maybe, your motors are turning slowly. At last, I would check your power supply to be sure that you are providing the correct voltage and current to your motor: this may be another reason why your motors are turning slowly.


text:
Q: iOS Background Task Not Completing I understand that background tasks can be implemented to perform certain processes that need more than the allotted 3-4 seconds applicationDidEnterBackground gives you using something like such:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{

        // Clean up your background stuff

        NSLog(@"Finsihed background task.");
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Begin your background stuff...
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do something...like update Parse DB
        NSLog(@"Doing something...");
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

Unfortunately, I seem to be missing something here. While I am receiving Doing something... which is fairly obvious from the above code, I am never receiving any sort of indication that the background task expires or ever enters the expirationHandler to properly finish the task.
I am confused first off how the "do something" dispatch is even related to the background task, or is linked with the task to let the application know to allow this process to complete in the ~10 minutes the application allows for BG Tasks.
NOTE: I have ensured that I have allowed for Background Modes in my info.plist, as many posted solutions point out may be the problem for others.
If someone can help me properly allow a background task to be completed I would most appreciative.
FYI: The main purpose of this is to update my Parse database with a query to set the users new (local to the device) values to the DB. This is what I would be using in case I am not being clear enough:
// Do something...like update Parse DB
NSLog(@"Doing something...");
. . .
PFQuery *query = [PFQuery queryWithClassName:@"_User"];
// Retrieve the object by id
[query getObjectInBackgroundWithId:<SOME_OBJECT_ID> block:^(PFObject *userInfo, NSError *error) {
    // Save user info to current user info on Parse
    [userInfo saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Could not update Parse with error: %@", error);
        }
        else {
            NSLog(@"Updated Parse successfully.");
        }
   }];
}];

UPDATE:
I have tried to call [application endBackgroundTask:bgTask]; within the Parse block but it does not get called. A few times it did assuming it was quickest both of those times, but I am trying to handle situations (like all but those 2) where updating Parse successfully will take longer than the closing the application. Here is what I did:
- (void)applicationDidEnterBackground:(UIApplication *)application {
    if ([[UIDevice currentDevice] isMultitaskingSupported]) {
        NSLog(@"Good for you.");
    }

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId];
        NSLog(@"done");
    }];

    // Begin your background stuff...
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do something...like update Parse DB
        NSLog(@"Doing something...");

        PFQuery *query = [PFQuery queryWithClassName:@"_User"];
        // Retrieve the object by id
        [query getObjectInBackgroundWithId:<SOME_OBJECT_ID> block:^(PFObject *userInfo, NSError *error) {
            // Save user info to current user info on Parse
            userInfo[@"test"] = [NSNumber numberWithInteger:12345];

            [userInfo saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                if (error != nil) {
                    NSLog(@"Could not update Parse with error: %@", error);
                    [application endBackgroundTask:self.backgroundTaskId];
                    self.backgroundTaskId = UIBackgroundTaskInvalid;
                }
                else {
                    NSLog(@"Updated Parse successfully.");
                    [application endBackgroundTask:self.backgroundTaskId];
                    self.backgroundTaskId = UIBackgroundTaskInvalid;
                }
            }];
        }];
    });
}

A: You have the right structure generally, except that you are calling [application endBackgroundTask:self.backgroundTaskId]; from outside your dispatch_async block, so the background task will be ended before the Parse operations will complete.  Also, if the user your are updating is the currently logged in user, you can use PFUser.currentUser rather than having to search.
So, your applicationDidEnterBackground should be something like:
- (void)applicationDidEnterBackground:(UIApplication *)application {

    self.bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{

        // Clean up your background stuff

        NSLog(@"Expired background task.");
        [application endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }];

    // Begin your background stuff...
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSLog(@"Doing something...");

        // Do something...like update Parse DB
        PFUser *user=[PFUser currentUser];
        // Update User fields as required
        [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
            if (succeeded) {
                NSLog(@"Saved user");
            } else {
                NSLog(@"Error:%@",error.localizedDescription);
            }
            NSLog(@"Background time remaining=%f",UIApplication.sharedApplication.backgroundTimeRemaining);
            [application endBackgroundTask:self.bgTask];
            self.bgTask = UIBackgroundTaskInvalid;
        }];

    });
}


text:
Q: Testing with functions passed to a mock object I have a simple function which was recently wrapped by some additional logic. I am struggling with updating the test logic since suddently, the method body is wrapped in a mock.
Let me give you an example.
Former logic & test:
// logic
public void doSomething(Transaction t, int a) {
  myService.foo(t, a);
}

And my test:
// test
TestedService service;

@Mock
MyService myService;

@Mock
Transaction t;

@Test
public void testSomething() {
   testedService.doSomething(t, 10);
   Mockito.verify(myService).foo(t, 10);
}

What happened is that we wrapped our logic in some additional function:
public void doSomething(Transaction t, int a) {
   model.runInEnhancedTransaction(t, t2 -> { myService.foo(t2, a) });
}

My question is, how do I test this when the logic is suddently wrapped in in model method (model is a mock in my test).
I basically need to verify that t2 -> { myService.foo(t2, a) } was called when the model object is a mock.
EDIT: I made it work with implementing my custom version of model just for the test purpose but still wonder if there is some more elegant way.

A: It's kind of tough to test these kinds of lambda invocations. What I do is perform two tests: one that model.runInEnhancedTransaction() was called, and one for model.runInEnhancedTransaction() itself. eg
@Test
void doSomethingCallsModelEnhancedTransaction() {
    testedService.doSomething(t, 10);
    verify(model).runInEnhancedTransaction(eq(t), any());
}
@Test
void modelRunInEnhancedTransaction() {
    Transaction t = mock(Transaction.class);
    BiConsumer<Transaction, Integer> consumer = mock(Biconsumer.class);
    model.runInEnhancedTransaction(t, consumer);
    verify(consumer).accept(...);
}


text:
Q: Google cloud sql: Lost connection to MySQL server at 'reading initial communication packet' I've set up a default django/django-wiki project. Local tests work fine. Connecting to cloud sql from the local server (with google.appengine.ext.django.backends.rdbms) doesn't work, I believe due to some authentication issue. More importantly, I can't connect from the production server.
I've made sure not to deploy my local MySQLdb sitting in my virtual environment directory.
I have the following in app.yaml:
- name: MySQLdb
  version: "latest"

My DATABASE entry is the following:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '/cloudsql/appname:sqlinstance',
        'PORT': '',
    }
}

It seems to be working, or at least doesn't complain about missing packages or mysql import issues. My problem is the following (obtained from the production logs, but also visible via the django debug output):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/MySQLdb-1.2.4b4/MySQLdb/connections.py", line 190, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 38")

What could be causing this? Does this mean a connection was made to something but there was no reply? Other posts seem to mention this as an issue when connecting from an external source, but this connection is from app engine AFAIK.

A: Well, this was much more straight forward than expected. I had assumed the cloud sql, created with my google account would just grant access to my GAE app by default. This has to be set explicitly, from Developer Console->Storage->Cloud SQL->instance-name->Edit->AUTHORIZED APP ENGINE APPLICATIONS. Or when you create the SQL instance, open the advanced options.
I just added the name of my app in the box, hit save and everything worked.

A: according to this, whenever an instance dies (for a reason or other), it will restart and, while it restarts, it just shoots this error until it's ready to receive requests.
Your best bet is to try and implement an exponential backoff.  How often does this happen?  Every single time or just once in a while?


text:
Q: Error System.IO.FileNotFoundException al intentar cargar Archivo Excel Estoy utilizando un FileDialog para seleccionar un archivo Excel o CSC mostralo en un dgv y posterior a esto subirlo a la base de datos, pero estoy recibiendo el siguiente error:
System.IO.FileNotFoundException: 'Could not find file 'C:\Users\jdani\OneDrive\Documentos\Visual Studio 2019\Projects\SoftwareRobot\SoftwareRobot\bin\Debug\FileDialog'.'
He estado buscando posibles soluciones y mencionan en muchas de ellas poner en false la referencia del System.IO, pero esta esta ya en false entonces que mas me recomiendan hacer para solucionar el problema?
Este es el código que tengo hasta el momento:
private void btnBrowse_Click(object sender, EventArgs e)
    {
        OpenFileDialog fileDialog = new OpenFileDialog();
        fileDialog.Multiselect = false;
        fileDialog.Title = "Import file";
        fileDialog.Filter = "Excel Workbook|*.xlsx| CSV File|* .csv";
        fileDialog.DefaultExt = ".xlsx";

        if (fileDialog.ShowDialog() == DialogResult.OK)
        {
            string fileName;
            fileName = fileDialog.FileName;
            txtPath.Text = fileName;

            using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
            {

                {
                    using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
                    {
                        DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
                        {
                            ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                            { UseHeaderRow = true }
                        });
                        tableCollection = result.Tables;
                        cboSheet.Items.Clear();
                        foreach (DataTable table in tableCollection)
                            cboSheet.Items.Add(table.TableName);
                    }
                }
            }
        }
    }

    private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataTable dt = tableCollection[cboSheet.SelectedItem.ToString()];
        DGVFile.DataSource = dt;
    }

Agradezco de antemano cualquier ayuda.
Saludos
DS

A: Su error se produce porque abre el archivo con
using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))

utilizando la instancia openFileDialog, pero el cuadro de dialogo que instancia en el metodo esta referenciado por fileDialog. Debe abrirlo así
using (var stream = File.Open(fileDialog.FileName, FileMode.Open, FileAccess.Read))


text:
Q: Missing disk space on SSD despite no paging file or hibernate.sys I've been completely unable to find an answer as to why my SSD is missing ~20GB of space that doesn't include decreasing the size of the paging file, disabling hibernation or extending the volume in Disk Management. The problem is that I've done all of those things, and still there are so much space missing.
I've used up ~50GB when I right-click and select Properties on my system drive SSD, with all hidden files and folders shown, as well as the hidden protected operating system files(where the hibernate.sys and pagefile.sys would be, had I not disabled them)
I'm going crazy, all solutions on the web indicates the things I've already tried. Is it possible that the page file is still taking up space? I had it on c: before I moved it to another drive(and since then moved it back to c: and setting it to no paging file)
Any possible solution or something I haven't already tried would be much appreciated, right now I'm constantly forced to run CCleaner so my drive has at least ~100MB free.
Also, Space Sniffer sees the ~20GB of missing space as Unknown(not yet scanned) space.

A: Alright, so I found the answer after receiving a very useful link by Andrea de Palo, thank you!
After running SpaceSniffer in admin mode, after failing to see anything other than 'Unknown' when running WinDirStat in admin mode (goodbye WDS), I found what was taking up all my space (23.4GB to be exact). The C:/Windows/System32/config folder was full of .regtrans-ms and .blf files.
Apparently, according to this page and this page, these files are both connected to the NTUser.dat, and possibly System Restore as well, but why they're never cleaned up I have no idea.
Anyhow, I deleted all of them, my computer is stable and I finally got a big portion of my 80GB SSD back!

A: Have you ckecked your Temp directory? Sometimes files get piled up there, and neither Disk Cleanup or CCleaner delete them.
Write %temp% on your Start Menu searchbox (or go to c:\Users\«your username»\AppData\Local\Temp) and check how much space that folder is taking.
Also, what is the filesystem that your SSD is using? If it's FAT32 for some odd reason, and your SSD has 60GB of space, it might explain the missing space (FAT32 is limited to 32GB partitions)

A: Have you tried WinDirStat? You could use it to narrow down the culprit.
You should also check "system restore" disk settings

A: There's a chance that the file system has been corrupted. You can try chkdsk /f (the command may be slightly different on Win8) to fix such corruption. Warning: this operation may lead to data loss. Ensure you have up-to-date backups.

A: Make sure System Restore is reduced. In my case System Restore was currently configured to consume 50% of the storage space of the drive. To reconfigure, [Right Click]Computer --> Properties --> System Protection (on right) --> Configure.


text:
Q: Firefox Bootstrapped Add-On Injecting before load Is it possible to add event listeners for a document before a page has been navigated to using a Bootstrapped add-on?  I would like to see what page the user wants to navigate to as well as later after the page loads to inspect the DOM.  I need to run code in the HTML content context.
In the past I used a toolbar XUL and included javascript within it and it would load before the HTML page loaded.

A: i looked into doing stuff before DOMContentLoaded sometime ago and found out there is a document inserted observer.
order of events after running research code at bottom

*

*readystate changes to interactive (i think multiple times, not sure)

*readystate changes to complete

*DOMContentLoaded event fires

*load event fires (Sometimes load doesnt fire, if you might have to change addEventListener with capture arugment (3rd argument) as false or true)
apparently there should be readystate loading before all of this but i can never catch it i dont know why.
after running the code in scratchpad, browser environemnt of course, then load a new page and watch the error console it will throw these reports in this order:
ready state changed! ("interactive") Scratchpad/4:18
02:28:07.873 ready state changed! ("complete") Scratchpad/4:18
02:28:07.874 DOMContentLoaded event fired! Scratchpad/4:53
02:28:07.938 Load event fired! Scratchpad/4:45

here is the research code. it adds a the listeners and observer to see whats firing.
var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
var os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
var LMObserver;

function myObserver() {
  this.register();
}

myObserver.prototype = {
    observe: function (subject, topic, data) {
        //Cu.reportError(subject);
        //Cu.reportError(data);
        //i think subject is window element
        subject.onreadystatechange = function () {
            //loading
            //interactive
            //complete
            Cu.reportError('ready state changed! ("' + subject.readyState + '")');
            //var body = subject.documentElement.querySelector('body')
//you want to change title so you would do that here do something like: if (subject.readystate == 'complete') { subject.title = 'blah blah' }
            //Cu.reportError('has body element: ' + body)
        }

    },
    register: function () {
        os.addObserver(this, 'document-element-inserted', false);
    },
    unregister: function () {
        os.removeObserver(this, 'document-element-inserted', false);
    }
};

//below this is the DOMContentLoaded thing i put this here so we can see what fires in what order
var pageLoad = function(event) {
    var win = event.originalTarget.defaultView;
    if (win && win.frameElement) {
      return;
    }
    Cu.reportError('Load event fired!');
}

var pageDOMContentLoaded = function(event) {
    var win = event.originalTarget.defaultView;
    if (win && win.frameElement) {
      return;
    }
    Cu.reportError('DOMContentLoaded event fired!');
}

LMObserver = new myObserver;
gBrowser.addEventListener("load", pageLoad, true);
gBrowser.addEventListener("DOMContentLoaded", pageDOMContentLoaded, true);
//gBrowser.removeEventListener("load", pageLoad, true);
//gBrowser.removeEventListener("DOMContentLoaded", pageDOMContentLoaded, true);
//LMObserver.unregister();

Here's some more indepth research on load events added with true or false as capture argument: https://github.com/Noitidart/event-listener-experiment-DOMC-and-load/blob/master/bootstrap.js


text:
Q: Column names return lowercase in aws glue I am new to AWS Glue, and have created job through crawler which point the source target CSV-file in S3-bucket.
The CSV-file contains following columns as:
userId  jobTitleName    firstName   lastName    preferredFullName   employeeCode    region

Now during the job execution, it throws following error
Key error: userid' not exist. As notified, the issue looks the case sensitive issue. so as per the glue-document, I created mapping for the schema
mappingsSchema=[('userid', 'integer', 'userId', 'integer'),
                 ('jobtitlename', 'string', 'jobTitleName', 'string'),
                 ('firstname', 'string', 'firstName', 'string'),
                 ('lastname', 'string', 'lastName', 'string'),
                 ('preferredfullName', 'string', 'preferredFullname', 'string'),
                 ('employeecode', 'string', 'employeeCode', 'string'),
                 ('region', 'string','region', 'string')]
mapped_dynamic_frame_read=dynamic_frame_read.apply_mapping(mappings = mappingsSchema, case_sensitive = True, transformation_ctx = "tfx")
##And converting to the spark df
df = mapped_dynamic_frame_read.toDF()

Still I'mm getting the same mentioned error.
How can resolve this kind of issue?

A: Hi @Emerson The issue was with mappings in which column names were wrongly specified against the schema definition. Now it's fixed and working fine.. Thanks


text:
Q: Mirth custom web service I have made a custom web service in Java just like the one described on the Mirth wiki
There are few methods defined in the web service class, but I don't know how to configure Mirth to listen to different methods of a single web service. Are there any tutorials on this matter? How do I define different input and output data for different methods?

A: You can use the @javax.jws.WebMethod and @javax.jws.WebParam annotations in your class that extends AcceptMessage, and your return value can be any class that you've appropriately decorated as XML. Something like:
package mypackage.myservices;

import javax.jws.WebParam;
import javax.jws.WebService;

import com.mirth.connect.connectors.ws.AcceptMessage;
import com.mirth.connect.connectors.ws.WebServiceReceiver;

@WebService
public class QueryService extends AcceptMessage {

    public QueryService(WebServiceReceiver webServiceReceiver) {
        super(webServiceReceiver);
    }

    @WebMethod(action="Authenticate")
    public AuthResponse authenticate(@WebParam(name="Username") String username,
        @WebParam(name="Password") String password) {
        //authenticate your user and return an AuthResponse,
        //possibly containing a token for use in subsequent calls...

        return new AuthResponse();
    }

    @WebMethod(action="GetResponse")
    public QueryResponse getResponse(@WebParam(name="QueryObject") Query query) {
        //handle the Query object, use it to get data from a DB, or whatever

        return new QueryResponse(); // or an appropriate Response object
    }
}

Where your AuthResponse, Query and QueryResponse objects can be any appropriately decorated (with java.xml.bind.annotation...) objects you like. Your methods will then be described in the WSDL (which Mirth gives you the address of in the Connector), so your service can be consumed by third parties.


text:
Q: MyISAM vs InnoDB for BI / batch query performance (ie, _NOT_ OLTP) Sure, for a transactional database InnoDB is a slam dunk.  MyISAM doesn't support transactions or row-level locking.
But what if I want to do big nasty batch queries that touch hundreds of millions of rows?
Are there areas where MyISAM has relative advantage over InnoDB??
eg, one (minor) one that I know of ... "select count(*) from my_table;"  MyISAM knows the answer to this instantly whereas InnoDB may take a minute or more to make up its mind.
---  Dave

A: MyISAM scales better with very large datasets. InnoDB outperforms MyISAM in many situations until it can't keep the indexes in memory, then performance drop drastically.
MyISAM also supports MERGE tables, which is sort of a "poor man's" sharding. You can add/remove very large sets of data instantaneously. For example, if you have 1 table per business quarter, you can create a merge table of the last 4 quarters, or a specific year, or any range you want. Rather than exporting, deleting and importing to shift data around, you can just redeclare the underlying MERGE table contents. No code change required since the name of the table doesn't change.
MyISAM is also better suited for logging, when you are only adding to a table. Like MERGE tables, you can easily swap out (rotate "logs") a table and/or copy it.
You can copy the DB files associated with a MyISAM table to another computer and just put them in the MySQL data directory and MySQL will automatically add them to the available tables. You can't do that with InnoDB, you need to export/import.
These are all specific cases, but I've taken advantage of each one a number of times.
Of course, with replication, you could use both. A table can be InnoDB on the master and MyISAM on the slave. The structure has to be the same, not the table type. Then you can get the best of both. The BLACKHOLE table type works this way.

A: Here's a great article comparing various performance points http://www.mysqlperformanceblog.com/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/ - you'll have to evaluate this from quite a few angles, including how you intend to write your queries and what your schema looks like. It's simply not a black and white question.

A: According to this article, as of v5.6, InnoDB has been developed to the point where it is better in all scenarios.  The author is probably a bit biased, but it clearly outlines which tech is seen as the future direction of the platform.


text:
Q: Proof regarding $\operatorname{arccot}$, where am I mistaken? We know that if $\cot(-\theta)=-\cot(θ)=\cot(\pi-θ)=x$, then

*

*$ \cot(-θ) = x     \quad\implies\quad  -θ = \newcommand{\arccot}{\operatorname{arccot}}\arccot(x)  \quad\implies\quad     θ
    = -\arccot(x)$

*$-\cot(θ) = x  \quad\implies\quad \cot(θ) = -x  \quad\implies\quad θ =
        \arccot(-x)$

*$\cot(π-θ) = x \quad\implies\quad π-θ = \arccot(x)  \quad\implies\quad θ =
            π-\arccot(x)$
Now we get that $$\arccot(-x)=π-\arccot(x)=-\arccot(x)$$ because my book has  $\arccot(-x) = π-\arccot(x)$ and I added $\arccot(-x) = π-\arccot(x)=-\arccot(x)$. This leads to misleading statement $pi=0$, but my steps are not wrong (I guess). Where am I mistaken?

A: There are a few incorrect statements in your reasoning. First let's establish what has been said thoroughly in the comments. The $\cot()$ function takes any real number besides a multiple of $\pi$ as its input and can return any real number as its output. The $\newcommand{\arccot}{\operatorname{arccot}}\arccot()$ function is defined to take any real number as its input and return a number in the range $(0,\pi)$ as its output. It is necessary to restrict the range of $\arccot()$ like this because otherwise it wouldn't be a function (remember that each input needs a unique output). Because of this restriction, some sensible statements about $\arccot()$ can be made, that aren't actually true. For example, one of your statements above is

$$\cot(-\theta) = x \quad\implies\quad -\theta = \arccot(x)\;.$$

This isn't true. For example $\cot(-\frac{37}{2}\pi) = 0$, but $\arccot(0) \neq -\frac{37}{2}\pi$ because $\arccot(0)$ has to be in the range $(0,\pi)$. In fact, many values make $\cot()$ return $0$, but only one of those values can be returned by $\arccot(0)$. You also made the statement

$$\arccot(-x) = -\arccot(x)\;.$$

This isn't ever true. Because $\arccot()$ must always return a positive number we have $\arccot(\_) \neq -\arccot(\_)$ for any choice of inputs.


text:
Q: Cannot resolve Method getSupportFragmentManager() or ((FragmentActivity)activity)getSupportFragmentManager() I want to launch a fragment from my BroadcastReciver class because I want to launch a fragment on a mobile home screen just like a dialog. using that user will stop or snooze the alarm. how to achieve that?
I tried all solutions available at StackOverflow but I can't get an answer. every time I am getting an error.

Cannot resolve Method getSupportFragmentManager()

or

Cannot resolve FragmentActivity in
((FragmentActivity)activity)getSupportFragmentManager()

any suggestion or question? comment below

A: You need an Activity to host that Fragment. A Fragment cannot be possible without a hosting Activity. At first, create an Activity (eg. AlarmActivity) with transparent background (You can achieve with themes) which has a FragmentContainerView to host your fragment. When you receive broadcast in your BroadcastReceiver, start this activity:
Intent intent = new Intent(context, AlarmActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // This is required
context.startActivity(intent);


text:
Q: Spring JPA+Hibernate not able to fetch record using findAll() of JPARepository I have created configuration using below code :
@Configuration
@EnableTransactionManagement
@ComponentScan("Name of package")
@EnableJpaRepositories("Name of package")

public class Config  {
    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "Name of package";

    @Bean
    public DataSource dataSource() {
         DriverManagerDataSource dataSource = new DriverManagerDataSource();
         dataSource.setDriverClassName("Driver Name");
         dataSource.setUrl("Url");
         dataSource.setUsername("UserName");
         dataSource.setPassword("Password");
         return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN);
        entityManagerFactoryBean.setJpaProperties(hibProperties());
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        return entityManagerFactoryBean;
    }

    private Properties hibProperties() {
        Properties properties = new Properties();
                properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, "org.hibernate.dialect.DB2Dialect");
                properties.put("hibernate.default_schema","Schema Name");
                return properties;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
          JpaTransactionManager transactionManager = new JpaTransactionManager();
          transactionManager.setEntityManagerFactory(emf);
          return transactionManager;
       }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
          return new PersistenceExceptionTranslationPostProcessor();
       }
}

There is an custom repository interface that implements JPARepository.
I have autowired the custom repository in controller and tried to call findAll().But the method returns 0 although there are 3 records in DB.
I am using spring web for rest service calls.
Entity class is created with @Entity and @Table annotations.It has an embedded key which is annotated using @EmbeddedId annotation.
@Repository
public interface EntityRepository extends JpaRepository<EntityTable, Long> {
    @SuppressWarnings("unchecked") EntityTable save(EntityTable entityTable);
}

Entity table is the name of my table mapped with db table.


text:
Q: Run docker compose inside a bitbucket pipeline I need to run docker-compose with --exit-code-from . My local docker-compose binary accepts this command line and works just fine.
+ docker-compose -f file1.yml -f file2.yml up zookeeper-secure kafka-secure schema-registry-secure app integration-tests --exit-code-from integration-tests

However, I need to run this in a bitbucket pipeline. To achieve that I installed docker-compose using pip installer
pip install docker-compose

Which gives me version 1.29.2
+ docker-compose version
docker-compose version 1.29.2, build unknown
docker-py version: 5.0.3
CPython version: 3.7.12
OpenSSL version: OpenSSL 1.1.1d  10 Sep 2019

And this version probably does not honour --exit-code-from  and hence errors out
No such service: --exit-code-from

While looking into docker docs, i found compose is now available in docker cli itself (though not very clear from which version onwards), but my bitbucket pipeline does not recognise that too.
+ docker compose help
docker: 'compose' is not a docker command.
See 'docker --help'

Here is the docker version output inside my bitbucket pipeline
+ docker version
Client:
 Version:           20.10.15
 API version:       1.41
 Go version:        go1.17.9
 Git commit:        fd82621
 Built:             Thu May  5 13:10:20 2022
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true
Server: Docker Engine - Community
 Engine:
  Version:          20.10.15
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.17.9
  Git commit:       4433bf6
  Built:            Thu May  5 13:10:29 2022
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          v1.6.4
  GitCommit:        212e8b6fa2f44b9c21b2798135fc6fb7c53efc16
 runc:
  Version:          1.1.1
  GitCommit:        v1.1.1-0-g52de29d7
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

Any help will be much appreciated !

A: Since the --exit-code-from option was introduced in April 2017, v1.12.0, I think the docker-compose v1 CLI parser is being much more picky than the docker-compose v2 you probably have in your workstation.
Telling by the No such service: --exit-code-from error message, simply move the option after the up subcommand but before the service list begins:
docker-compose \
  -f file1.yml \
  -f file2.yml \
  up \
    --exit-code-from integration-tests \
    zookeeper-secure kafka-secure schema-registry-secure app integration-tests

Very much related: https://stackoverflow.com/a/59840305/11715259

Otherwise, this question is about "how to use docker-compose v2 in Bitbucket Pipelines", which is a totally different topic: https://stackoverflow.com/a/73069569/11715259


text:
Q: D3 - Problems centering labels on a SVG made in D3 I can't quite understand how to center the labels on the left of my d3 graph. I have seen that the solution is text-anchor: middle however this isn't working in my case and I'm not too sure why.
This is the D3 Javascript that is building the SVG:
function buildSvg(data) {
    var margin = {
            top: 50,
            right: 20,
            bottom: 10,
            left: 150
        },
        width = $('.figure').width() - (margin.left + margin.right),
        height = 50 * data.length;

    var y = d3.scale.ordinal()
    .rangeRoundBands([0, height], 0.3);

    var x = d3.scale.linear()
    .rangeRound([0, width]);

    var color = d3.scale.ordinal()
    .range(['#9ADF2B', '#ef473a', '#ECECEC']);

    var yAxis = d3.svg.axis()
    .scale(y)
    .orient('left');

    var svg = d3.select(element[0]).append('svg')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height)
    .attr('class', 'd3-plot')
    .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + 0 + ')');

    color.domain(['Correct', 'Incorrect', 'To complete']);

    data.forEach(function (d) {
        // Creates the percentages
        d['Correct'] = +d[1] * 100 / d.N;
        d['Incorrect'] = +d[2] * 100 / d.N;
        d['To complete'] = +d[3] * 100 / d.N;

        // Changes the starting point.
        var x0 = 0;
        var idx = 0;

        d.boxes = color.domain().map(
            function (name) {
                return {
                    name: name,
                    x0: x0,
                    x1: x0 += +d[name],
                    N: +d.N,
                    n: +d[idx += 1]
                };
            }
        );
    });

    var min_val = d3.min(data, function (d) {
        return d.boxes['0'].x0;
    });

    var max_val = d3.max(data, function (d) {
        return d.boxes['2'].x1;
    });

    x.domain([min_val, max_val]).nice();
    y.domain(data.map(function (d) {
        return d.Question;
    }));

    svg.append('g')
    .attr('class', 'y axis')
    .call(yAxis);

    var vakken = svg.selectAll('.question')
    .data(data)
    .enter().append('g')
    .attr('class', 'bar')
    .attr('transform', function (d) {
        return 'translate(10,' + y(d.Question) + ')';
    });

    var bars = vakken.selectAll('rect')
    .data(function (d) {
        return d.boxes;
    })
    .enter().append('g').attr('class', 'subbar');

    bars.append('rect')
    .attr('height', y.rangeBand())
    .attr('x', function (d) {
        return x(d.x0);
    })
    .attr('width', function (d) {
        return x(d.x1) - x(d.x0);
    })
    .style('fill', function (d) {
        return color(d.name);
    });

    bars.append('text')
    .attr('x', function (d) {
        return x(d.x0);
    })
    .attr('y', y.rangeBand() / 2)
    .attr('dy', '0.5em')
    .attr('dx', '0.5em')
    .style('font', '10px sans-serif')
    .attr('text-anchor', 'start')
    .text(function (d) {
        return d.n !== 0 && (d.x1 - d.x0) > 3 ? d.n : '';
    });

    vakken.insert('rect', ':first-child')
    .attr('height', y.rangeBand())
    .attr('x', '1')
    .attr('width', width)
    .attr('fill-opacity', '0.5')
    .style('fill', '#F5F5F5')
    // If we remove the d parameter it will break the code as it will return as undefined otherwise
    .attr('class', function (d, index) {
        return index % 2 === 0 ? 'even' : 'uneven';
    });

    // This controls the Axis line.
    svg.append('g')
    .attr('class', 'y axis axis-line')
    .append('line')
    .attr('x1', x(20))
    .attr('x2', x(20))
    .attr('y2', height);

    d3.selectAll('.axis path')
    .style('fill', 'none')
    .style('stroke', '#000')
    .style('shape-rendering', 'crispEdges');

    d3.selectAll('.axis line')
    .style('fill', 'none')
    .style('stroke', '#000')
    .style('shape-rendering', 'crispEdges');

}

Below is a jsFiddle of the SVG:
https://jsfiddle.net/bguLnktk/
This is what I would like the user labels to  look like if possible

A: Your problems is the y-axis:

You has two options.
Option A. Move your axis:

Option B. Add trail spaces on text ( )

Hope this help.


text:
Q: Migrate Joomla 3 Site to new domain I have built a Joomla site for a client on a development server.  It soon needs migrating to the client's Live site, which will mean a URL change as well as a physical server change.
I'm new to Joomla, but having worked a lot on WordPress previously I know it's a piece of cake to migrate one WP site to another, especially with the dozen or so available plugins.
However, this doesn't appear to be so easy on Joomla.  I have searched for the best practice to achieve this with Joomla 3 but cannot find what I need.
Does anyone have a suggestion for this?

A: There are in fact a two ways to achieve this and they are quite easy.
1. The first one is the manual way, that is:

*

*Copy the files of your local joomla installation and upload them to
your server

*Export your local database and import it on your server.

*Edit the configuration.php file to your new server credentials -db
name, db user, db server etc.

2. The second one is through the akeeba backup component.

*

*In this case you create a backup and then restore it on the remote
server. Detailed info
here.

After uploading your remote site you are advised to follow these
  guidelines
  to secure your installation.


text:
Q: Material ripple effect hidden by other view in layout I added a ripple effect on a ImageButton, however it is hidden by an ImageView used as a background for the parent view RelativeLayout.
Here's the layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="172dp"
                android:orientation="vertical"
                android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/drawerBackgroundImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/drawer_background"/>

    [...]

    <ImageButton
        android:id="@+id/drawerLogoutButton"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_alignBottom="@id/drawerEmailTextView"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginRight="@dimen/activity_horizontal_margin"
        style="@style/FlatButtonStyle"
        android:scaleType="centerInside"
        android:src="@drawable/ic_logout_white_24dp"/>

</RelativeLayout>

(there's a bunch of other views but they're irrelevant here)
I'm using an ImageView as the background for the RelativeLayout as I need to set a specific scaleType for the image, so I can't use the basic android:background property.
The ripple effect is hidden as it doesn't have a mask layer (I want it to extend out of the button's bounds) and thus uses the ImageButton's parent view to be displayed. The effect is perfectly visible if I remove the ImageView.
Is there a way to get the ripple effect to be shown above the problematic ImageView?

A: I am experiencing same issue. Only solution I have found so far is not 100% okay since ripple is masked by view (its not borderless).
The solution (workaround):
surround your ImageButton with other view and set ripple to the foreground instead of the background in your layout like this:
<ImageView ... />

<FrameLayout
    ...
    android:clickable="true"
    android:focusable="true"
    android:foreground="?attr/selectableItemBackgroundBorderless" >

    <ImageButton />
</FrameLayout>

I would be really glad if someone explain why the ripple is drawn behind the image. Also if you look at Google Photos app, in image detail they have transparent icons over image view with ripple. I would like to replicate this, but I am not able to make the ripple to be in foreground. Does anybody know how to put transparent imagebuttons over everything but still have the ripple?
EDIT final solution
here you can find exactly same question link
with great explanation what is happening. the solution is the same but on top of that it solves rectangular mask by adding
android:clipChildren="false"
android:clipToPadding="false"

to your layout. now your ripple should be borderless (it worked for me).
The layout xml could be something like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
...
android:clipChildren="false"
android:clipToPadding="false">

    <ImageView ... />

    <FrameLayout
        ...

        android:clickable="true"
        android:foreground="?attr/selectableItemBackgroundBorderless">
       <ImageView ... />
    </FrameLayout>

</FrameLayout>

A: I'm aware this is an old post but I did struggle with this quite a bit today hence I'm posting what I was finally able to figure out and maybe someone else might benefit from it. One key emphasis beforehand, please do always RTFM!
1) The story
I aimed to use the unbounded ripple effect on Tab Items and consequently have it spread all over the AppBarLayout area. I had applied @android:color/transparent to TabLayout as the first wrapping parent and gave AppBarLayout a background color, nevertheless the ripple was still being cut off right at the borders of TabLayout's height.
2) The moral of the story (RTFM)
So I run to the nest of Android knowledge: The Documentation, and spotted this:

?android:attr/selectableItemBackgroundBorderless for a ripple that extends beyond the view. It will be drawn upon, and bounded by, the nearest parent of the view with a non-null background.

3) The course of action
Using Layout Inspector, I realized that @android:color/transparent although transparent (duh!) it actually assigns 0 as the value of the bg attribute of a View, but zero is not null hence the ripple gets bounded at the nearest parent.
4) The conclusion
With that in hand, I went and set the android:background property of my TabLayout to @null rather than transparent, and now I have a fancy little ripple spread onto the area of the AppBarLayout.
5) Outro: **ANDROID & SO FTW!
Props to everyone in this post who shed light on the matter in word. Cheers!

A: I had exactly the same issue and solved it using this thread: https://code.google.com/p/android/issues/detail?id=155880
Issue preview:
Before solved:

After solved:

Explanation:
"Borderless buttons draw their content on the closest background. Your button might not be having background between itself and the ImageView, so it draws underneath the ImageView."
Solution:
"Use a transparent background (android:background="@android:color/transparent") on some layout containing the button (beneath the ImageView). This will dictate what the maximum bounds of the ripple effect is."
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
                ...>

    <!-- Your background ImageView -->
    <ImageView
        android:id="@+id/drawerBackgroundImageView"
        android:src="@drawable/drawer_background"
        ... />

        <!-- ... -->

    <!-- HERE, you need a container for the button with the transparent
         background. Let's say you'll use a FrameLayout -->
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent">

        <!-- Maybe more items -->

        <!-- Button with borderless ripple effect -->
        <ImageButton
            android:id="@+id/drawerLogoutButton"
            android:background="?selectableItemBackgroundBorderless"
            ... />

    </FrameLayout>

</FrameLayout>

Hope it helps.

A: After wrapping ImageButton inside FrameLayout, I was getting rectangular shape on touch. Applied background with oval shape on FrameLayout and got the circular shape on touch.

A: Had the same issue. Used the solutions described above and worked. Managed to avoid the wrapping FrameLayout by setting foreground as ?attr/actionBarItemBackground and background as @null.
 <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|end"
            android:background="@null"
            android:contentDescription="@string/app_name"
            android:foreground="?attr/actionBarItemBackground"
            android:padding="@dimen/small_margin"
            android:src="@drawable/ic_clear_text_icon" />

A: Use android:clipChildern="false"   android:clipToPadding="false" for ALL the parent layouts
here is my solution.
` <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false"
    android:clipToPadding="false" >

    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:clipChildren="false"
      android:clipToPadding="false">

      <ImageButton
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:foreground="?attr/selectableItemBackgroundBorderless"
        android:src="@drawable/ic_magnifier" />

         ....
        `


text:
Q: How do I enable a touchpad? I installed Ubuntu 11.10 several months ago, but I haven't found a proper way to enable the touchpad.
I once tried something I can't recall the name.
Does any one have any suggestions?
Update:
Here's what cat /usr/share/X11/xorg.conf.d/50-synaptics.conf shows:
# Example xorg.conf.d snippet that assigns the touchpad driver
# to all touchpads. See xorg.conf.d(5) for more information on
# InputClass.
# DO NOT EDIT THIS FILE, your distribution will likely overwrite
# it when updating. Copy (and rename) this file into
# /etc/X11/xorg.conf.d first.
# Additional options may be added in the form of
#   Option "OptionName" "value"
#
Section "InputClass"
        Identifier "touchpad catchall"
        Driver "synaptics"
        MatchIsTouchpad "on"
# This option is recommend on all Linux systems using evdev, but cannot be
# enabled by default. See the following link for details:
# http://who-t.blogspot.com/2010/11/how-to-ignore-configuration-errors.html
      MatchDevicePath "/dev/input/event*"
EndSection

A: Open the Software Center and search for synaptics, should have a couple of packages that after install should enable your touchpad.
I had the same problem on a Dell Inspiron 1545!


text:
Q: I was reading a book about a boy who was able to travel through time, and i am trying to remember its name A couple years ago, I read a book about a boy that was able to imagine a clock in his head, and make the hands of the clock spin, forward and backwards, allowing him to travel through time. I believe that the clock that he was imagining was a grandfather clock, and he had help from a another person who had the same power. Also, there was something about him coming home and finding his house burned down.

A: The book "There will be Time"  by Poul Anderson seems to meet your criteria.  The boy's name is Jack.  I don't know about the clock in the head, but he does meet other people with the same ability from a variety of time periods.
https://en.wikipedia.org/wiki/There_Will_Be_Time


text:
Q: Programmatically modify related products in magento I'm trying to programmatically manipulate the product relations in a Magento store.
From what I've read, setRelatedLinkData should be the way to go.
As I simple test, I'm just trying to replace a products related products with nothing (i.e. an empty array), however it's not working - the product in question is still showing the related product in the backend.
The test code I'm working with is:
$product = Mage::getModel('catalog/product')->load($product->getId());
$linkData = array();
print_r($linkData);

$product->setRelatedLinkData($linkData);
echo "Save\n";

$r = $product->save();

As mentioned above however the product still has a related product when I reload it in the backend.
NOTE: I don't only want to remove related products, eventually I want to be able to add new ones as well, so a DELTE FROM... SQL query isn't what I am looking for. However if I can't get it to work to remove products, then it's certainly not going to work to add them, so one step at a time :-)

A: The quickest way I can think of is to use the Link Resource:
app/code/core/Mage/Catalog/Model/Resource/Product/Link.php  saveProductLinks
// sample code

$product = Mage::getModel('catalog/product')->load(147);
$linkData = array();

Mage::getResourceModel('catalog/product_link')->saveProductLinks(
    $product, $linkData, Mage_Catalog_Model_Product_Link::LINK_TYPE_RELATED
);

and if you want to assign products use the same code but provide this as $linkData:
$linkData = array(
    '145' => array('position' => 1),
    '146' => array('position' => 2)
);


text:
Q: JQuery Datepicker: show on input group addon button click I have the following div:

                <input type="hidden" id="datepicker">
                <input type="text" id="input_date" class="form-control" value="" readonly='readonly'>

And the following JQuery call:
    var today = new Date();
    $("#input_date").datepicker({
        changeYear: false,
        numberOfMonths: 1,
        altFormat: "yy-mm-dd",
        altField: "#datepicker",
        minDate: today,
        onSelect : function () {
            var inputdate = $.datepicker.parseDate('yy-mm-dd', $("#datepicker").val());
        }
    }).datepicker("setDate",today);

This makes the datepicker appear correctly when I press the text field. However, I also want it to show up when I click the input_btn_calendar button inside the accompanying span.
I've tried this:
    $("#input_btn_calendar").click(function() {
        $("input_date").datepicker('show')
    });

But unfortunately, that does nothing. What am I missing?

A: You have an invalid selector of $('input_date').
Try this instead,
$("#input_btn_calendar").click(function() {
    $("#input_date").datepicker('show')
});


text:
Q: Update statement to convert Email to MD5 is not calculating the correct results I have trying to cycle through my database and MD5 hash my email addresses. This is the code I tired using:
update Recipients set MD5Email = CONVERT(VARCHAR(MAX), HASHBYTES( 'md5', NonMd5.EmailAddress ), 2)
from
 Recipients INNER JOIN Recipients as NonMd5
on
 Recipients.Id = NonMd5.Id

I also tried this and it had the same result:
update Recipients set MD5Email = CONVERT(VARCHAR(MAX), HASHBYTES( 'md5', Recipients.EmailAddress ), 2)
    from
     Recipients

If I replace the NonMd5.EmailAddress with an a hardcoded string, it calculates it correctly. I have no idea what is wrong.
This is my Table:
CREATE TABLE [dbo].[Recipients] (
[Id] uniqueidentifier NOT NULL DEFAULT (newid()) ,
[EmailAddress] nvarchar(MAX) COLLATE Latin1_General_CI_AS NULL ,
[IsProcessed] bit NOT NULL ,
[MD5Email] nvarchar(80) COLLATE Latin1_General_CI_AS NULL ,
CONSTRAINT [PK__Recipien__3214EC0703317E3D] PRIMARY KEY ([Id])
)
ON [PRIMARY]
TEXTIMAGE_ON [PRIMARY]
GO

Update:
If I set an email adress to test@test.com  this is my result:  4767DCA4A82B295C59D18097EE7B4070
Running it as a direct value in the code above, this is my result:
b642b4217b34b1e8d3bd915fc65c4452

A: How about just:
UPDATE dbo.Recipients
  SET MD5Email = CONVERT(NVARCHAR(80), HASHBYTES('MD5', EmailAddress), 2);

That said you really should consider SHA or other algorithms over MD5, and you really shouldn't be storing the hash output as a string - use varbinary.
Here are the results I get:
SQLFiddle
Now there is a very important distinction that I think you're missing. You're currently storing an e-mail address as NVARCHAR(MAX) - I have no idea why you're using Unicode (most servers in the world still don't support double-byte characters), and I have no idea why you're using MAX. However compare these:
SELECT CONVERT(NVARCHAR(80), HASHBYTES('MD5', 'test@test.com'), 2);

SELECT CONVERT(NVARCHAR(80), HASHBYTES('MD5', N'test@test.com'), 2);
----------- this N is very important ---------^

Given the current SMTP standard, your column should probably be 320 characters (255 characters for domain name, 64 for local part, plus the @ symbol) instead of MAX (nobody has an e-mail address with > 4000 characters, never mind 1 billion characters). And you would only need NVARCHAR if you truly need to support Unicode e-mail addresses - which, like I said, are unrecognized by most mail servers today. If you change the data type, you will see that it matches your test. If you stay with NVARCHAR, you need to compare apples to apples, so when you run your test, make sure you prefix your hard-coded value with an N.


text:
Q: Debug mock services generated by soapUI preconditions:
1. response(generated as mock service) in soupUI
2. web-client, that knows about running mock service by address:
http://localhost:8091/cps/axis2/services/

Mock services are running OK.
When perform request from web-client,I expect to get response as specified in soapUI.
Instead of this I got general error:
org.apache.axiom.soap.SOAPProcessingException: First Element must contain the local name, Envelope , but found html

That means there are problems with response,thus html with 500 code returned.
The question is ,how can I debug what is the cause of problem?
I suspect namespaces and abstract types.

A: It's probably a bad endpoint on the client. i.e. it's not using the right URI.  Or, the mockservice may be configured but not running. In this situation, SoapUI responds with an HTML page that says something like:
"There are currently 0 running soapUI MockServices" or some such.
Take a look at your WSDL that SoapUI produces. Consume that in SoapUI and you should be able to send yourself a request, see it in the mockservice log, and get a response. Once you get that working, THEN try a client. And it should work. If it doesn't, check its endpiont vs the one that the SoapUI request (built from the SoapUI mock) used. Adjust for localhost vs IP address.

A: I might not be able to answer your question in general but in this case it looks like instead of returning fully specified response from soapUI mock (i.e. with soap:Envelope included) you only specify message body. The official documentation has samples that specify responses.
P.S. I hope I got your question correctly


text:
Q: Creating a table with FIXED length column widths I'm trying to recreate a table from a RPG character sheet:

I don't care about the colouring particularly, black and white works perfectly fine, the sizing is the main issue. I am going to be making multiple copies of this table, and I want all of them to be uniform. So even if every data value was blank is would then just produce a blank table of the same measurements as a filled in version.
I'm wanting each box to have (roughly) the following widths (relative to the total table width):

*

*Name:70%, Class: 30%

*Range: 21%, RoF: 37%, Damage: 40%

*Pen: 21%, Clip 18%, Reload: 18%, Weight: 14%, Availability: 19%

*Special: 100%

Sketch with measurements in place of the data for the table (not drawn to scale):

These widths are to keep the table looking close to the original as possible in terms of layout. Being still relatively new to LaTeX and very new to doing more than a basic data table. The only way I could think of doing this would be something along the lines of making 100 columns, and using \multicolumn{% above} . However even with that lengthy method, since LaTeX likes to make everything as small as possible the far right columns wouldn't have their full width and it would create different sized tables depending on the data.
I've looked around as quite a number of questions about fixed length table columns but all seem to be fixing it to be smaller than the text within (causing multine) rather than wanting to keep the size the same and allow empty space to fill the gap.
For some context, the goal is to have a macro that I can input the data for each box, and then the macro creates a copy of the table, filled in with the entered data. The macro I have sorted, the issue is just the formatting/layout of the table.
Here is the macro code I have:
\documentclass[11pt]{article}

\usepackage{fancyhdr}

\oddsidemargin 0.2cm
\topmargin -1.0cm
\textheight 24.0cm
\textwidth 15.25cm
\parindent=0pt
\parskip 1ex
\pagestyle{fancy}

\newcommand{\printweptable}{
\begin{tabular}{p{\linewidth}}
 Name: \name \hfill Cls: \class \\
 Rng: \range    \hfill RoF: \rof \hfill Rmg: \dmg\\
 Pen: \pen \hfill Clip: \clip \hfill Rld: \rld \hfill Wt: \wt \hfill Avl: \avl\\
 Special: \special
\end{tabular}
}

%Weapon info
\newcommand{\setwepstats}[9]{%
\def\name{#1}%
\def\class{#2}%
\def\range{#3}%
\def\rof{#4}%
\def\dmg{#5}%
\def\pen{#6}%
\def\clip{#7}%
\def\rld{#8}%
\def\wt{#9}
\wepstatsrelay
}%

\def\wepstatsrelay#1#2{
\def\avl{#1}%
\def\special{#2}}%

\begin{document}

\setwepstats{Name}{Class}{Range}{RoF}{Damage}{Pen}{Clip}{Reload}{Wt}{Availability}{Special}

\printweptable

\setwepstats{}{}{}{}{}{}{}{}{}{}{}

\printweptable

\end{document}

I think I shall use the code provided by Werner, and scrap the macro I had (his seems cleaner to use and reuse.
I have now merged the codes provided by both Werner and cfr and have this working code:
\documentclass{article}

\usepackage{xkeyval}

\makeatletter
\define@cmdkey{rpg}[char@]{name}[]{}
\define@cmdkey{rpg}[char@]{class}[]{}
\define@cmdkey{rpg}[char@]{range}[]{}
\define@cmdkey{rpg}[char@]{rof}[]{}
\define@cmdkey{rpg}[char@]{damage}[]{}
\define@cmdkey{rpg}[char@]{pen}[]{}
\define@cmdkey{rpg}[char@]{clip}[]{}
\define@cmdkey{rpg}[char@]{reload}[]{}
\define@cmdkey{rpg}[char@]{weight}[]{}
\define@cmdkey{rpg}[char@]{availability}[]{}
\define@cmdkey{rpg}[char@]{special}[]{}
\define@cmdkey{rpg}[char@]{mods}[]{}
\define@cmdkey{rpg}[char@]{qualities}[]{}
\define@cmdkey{rpg}[char@]{width}[\linewidth]{}

\newcommand{\statlabel}{\textsc}

\usepackage{calc,xparse}
\newlength\mycardwidth
\setlength\mycardwidth{.75\textwidth}
\NewDocumentCommand \boxme { O{} }{%
  \fbox{%
    \parbox{\linewidth-2\fboxrule-2.5\fboxsep}{\strut #1}%
  }%
}
\NewDocumentCommand \pageme { O{} O{} }{%
  \begin{minipage}{#1\mycardwidth}
    \centering\boxme[#2]
  \end{minipage}%
}
\NewDocumentCommand \cardme { O{.75\textwidth} +m }{%
  \setlength\mycardwidth{#1-2\fboxrule-2\fboxsep}%
  \fbox{%
    \begin{minipage}{\mycardwidth}
      \centering
      #2%
    \end{minipage}%
  }%
}

\newcommand{\setcharacterstats}[1]{%
  \begingroup
  \setkeys{rpg}{name,class,range,rof,damage,pen,clip,reload,weight,availability,special,mods,qualities,width,#1}%
  \noindent
  \centering
  \cardme[\textwidth]{%
    \pageme[.69][\statlabel{Name}: \char@name]%
    \pageme[.31][\statlabel{Cls}: \char@class]

    \pageme[.22][\statlabel{Rng}: \hfill \char@range \hfill m]%
    \pageme[.38][\statlabel{RoF}: \char@rof]%
    \pageme[.4][\statlabel{Dmg}: \char@damage]

    \pageme[.22][\statlabel{Pen}: \char@pen]%
    \pageme[.19][\statlabel{Clip}: \char@clip]%
    \pageme[.19][\statlabel{Rld}: \char@reload]%
    \pageme[.18][\statlabel{Wt}: \hfill \char@weight \hfill kg]%
    \pageme[.22][\statlabel{Avl}: \char@availability]

    \pageme[][\statlabel{Special}: \char@special]%

    \pageme[][\statlabel{Mods}: \char@mods]%

    \pageme[][\statlabel{Qualities}: \char@qualities]%
  }
}
\makeatletter

%-----------------------------------
\begin{document}

\setcharacterstats{
  name = Long Las,
  class = Basic,
  range = 150,
  rof = S/-/-,
  damage = 1d10+3,
  pen = 1,
  clip = 40,
  reload = Full,
  weight = 4.5,
  availability = Scarce,
  special = Accurate Felling (4) Reliable
  }

\end{document}

With that code however, is there a way to center the variable data within the remaining space of the cell? E.g. If I had Carbine as the name, it would make the distance from the : and the C be equal to the distance from the e and the right side of the cell. (Not put it in the center of the entire cell).
I tried to edit the variable within the macro to replace \char@name with \center{\char@name} however this threw the variable onto an entirely new line (within the cell) and centered it based on the cell sides alone. If there's no simple way to do this, I'll stick with it being left aligned.

A: This seems to beg for a key-value interface:

\documentclass{article}

\usepackage{xkeyval}

\makeatletter
\define@cmdkey{rpg}[char@]{name}[]{}
\define@cmdkey{rpg}[char@]{class}[]{}
\define@cmdkey{rpg}[char@]{range}[]{}
\define@cmdkey{rpg}[char@]{rof}[]{}
\define@cmdkey{rpg}[char@]{damage}[]{}
\define@cmdkey{rpg}[char@]{pen}[]{}
\define@cmdkey{rpg}[char@]{clip}[]{}
\define@cmdkey{rpg}[char@]{reload}[]{}
\define@cmdkey{rpg}[char@]{weight}[]{}
\define@cmdkey{rpg}[char@]{availability}[]{}
\define@cmdkey{rpg}[char@]{special}[]{}
\define@cmdkey{rpg}[char@]{width}[\linewidth]{}

\newcommand{\setcharacterstats}[1]{%
  \begingroup
  \setkeys{rpg}{name,class,range,rof,damage,pen,clip,reload,weight,availability,special,width,#1}%
  \noindent
  \begin{tabular}{ @{} c @{} }
    \begin{tabular}{ | p{\dimexpr.69\char@width-2\tabcolsep} | p{\dimexpr.31\char@width-2\tabcolsep} | }
      \hline
      \statlabel{Name}: \char@name & \statlabel{Cls}: \char@class
    \end{tabular} \\
    \begin{tabular}{ | p{\dimexpr.23\char@width-2\tabcolsep} | p{\dimexpr.37\char@width-2\tabcolsep} | p{\dimexpr.4\char@width-2\tabcolsep} | }
      \hline
      \statlabel{Rng}: \char@range & \statlabel{RoF}: \char@rof & \statlabel{Dmg}: \char@damage
    \end{tabular} \\
    \begin{tabular}{ | p{\dimexpr.23\char@width-2\tabcolsep} | p{\dimexpr.20\char@width-2\tabcolsep} | p{\dimexpr.20\char@width-2\tabcolsep} |
                       p{\dimexpr.16\char@width-2\tabcolsep} | p{\dimexpr.21\char@width-2\tabcolsep} | }
      \hline
      \statlabel{Pen}: \char@pen & \statlabel{Clip}: \char@clip & \statlabel{Rld}: \char@reload & \statlabel{Wt}: \char@weight & \statlabel{Avl}: \char@availability
    \end{tabular} \\
    \begin{tabular}{ | p{\dimexpr\char@width-2\tabcolsep} | }
      \hline
      \statlabel{Special}: \char@special \\
      \hline
    \end{tabular}
  \end{tabular}\par
  \endgroup
}
\makeatletter

\newcommand{\statlabel}{\textsc}

\begin{document}

\setcharacterstats{
  name = The HuLK,
  class = Huge,
  range = Arm,
  rof = 5m,
  damage = 400,
  pen = 12,
  clip = 12.2,
  reload = 2s,
  weight = 7t,
  availability = 7,
  special = Green and very angry
  }

\end{document}

All the keys should be self-explanatory, including the possibility that you can adjust the width for each table. The default it \linewidth, and all the columns are specified in percentages of this.

A: Key-Value Version
Here's a version of my earlier answer which provides a key-value interface. I've used the LaTeX 3 code for handling the keys because I find this the most intuitive to use, although the syntax looks a bit alien at first. (That is, I've never understood how to use xkeyval etc. properly, so I can't do it in the difficult, non-alien-looking way.)
Also, since my original code used xparse, I didn't need to add any packages to use this approach. geometry is added just to get a wider page for the example.
\cardme[<list of key-value pairs>]

\cardme now takes one optional argument which is a list of key-value pairs.
Available keys are:
avl=,
  card width=,
  clip=,
  cls=,
  dmg=,
  name=,
  pen=,
  rld=,
  rng=,
  rof=,
  special=,
  wt=,
Apart from card width, these take text which is the value of the key in this case. In each case, the default is to typeset nothing as the value. The default for card width, which expects a dimension, is .75\textwidth, as in the original code.
Two additional macros are provided.
\cardnames{<list of key-value pairs>}

can be used to customise the labels used for each key-value pair. The keys are as before, except that there is no card width. The difference is that this macro doesn't typeset anything. It just changes the text which will be used when creating the label in each box if, and when, \cardme is later used.
Similarly
\cardunits{<list of key-value pairs>}

can be used to assign a unit to each type of value. By default these are empty except for rng and wt which are set to km and kg respectively.
For example, suppose we create the following cards:
\noindent
\cardme

This will be an empty card with default width and labels.
\noindent
\cardme[%
  card width=\textwidth,
  name=This One,
  cls=Aristocracy,
  rng=450,
  rof=RoF,
  dmg=Extensive,
  pen=Pen,
  clip=Y,
  rld=N,
  wt=1,
  avl=Y,
  special=Extraordinary powers,
]

This card uses the default labels but, this time, the card is completed with a value in each box and the width is increased to allow for this.
\cardnames{
  name=Enw,
  cls=Dth,
  rng=Pll,
  dmg=Dfd,
  clip=Cnf,
  rld=AilLl,
  wt=Pwys,
  avl=ArGl,
  special=Arbennig,
}

This doesn't typeset anything. Rather, it changes some of the labels, while leaving others untouched. Hence, when we typeset another empty card with
\noindent\cardme[card width=.85\textwidth]

we will get an empty card with a mixture of default and custom labels and width of .85\textwidth.

Complete code:
\documentclass{article}
\usepackage{calc,xparse,geometry}
\ExplSyntaxOn
\dim_new:N \l_Archimedes_card_width_dim
\dim_set:Nn \l_Archimedes_card_width_dim { .75\textwidth }
\keys_define:nn { Archimedes / card }
{
  avl .tl_set:N = \l_Archimedes_avl_tl,
  card~width .dim_set:N = \l_Archimedes_card_width_dim,
  clip .tl_set:N = \l_Archimedes_clip_tl,
  cls .tl_set:N = \l_Archimedes_cls_tl,
  dmg .tl_set:N = \l_Archimedes_dmg_tl,
  name .tl_set:N = \l_Archimedes_name_tl,
  pen .tl_set:N = \l_Archimedes_pen_tl,
  rld .tl_set:N = \l_Archimedes_rld_tl,
  rng .tl_set:N = \l_Archimedes_rng_tl,
  rof .tl_set:N = \l_Archimedes_rof_tl,
  special .tl_set:N = \l_Archimedes_special_tl,
  wt .tl_set:N = \l_Archimedes_wt_tl,
  avl .initial:n = ,
  clip .initial:n = ,
  cls .initial:n = ,
  dmg .initial:n = ,
  name .initial:n = ,
  pen .initial:n = ,
  rld .initial:n = ,
  rng .initial:n = ,
  rof .initial:n = ,
  special .initial:n = ,
  wt .initial:n = ,
}
\keys_define:nn { Archimedes / card / names }
{
  avl .tl_set:N = \l_Archimedes_avlname_tl,
  clip .tl_set:N = \l_Archimedes_clipname_tl,
  cls .tl_set:N = \l_Archimedes_clsname_tl,
  dmg .tl_set:N = \l_Archimedes_dmgname_tl,
  name .tl_set:N = \l_Archimedes_namename_tl,
  pen .tl_set:N = \l_Archimedes_penname_tl,
  rld .tl_set:N = \l_Archimedes_rldname_tl,
  rng .tl_set:N = \l_Archimedes_rngname_tl,
  rof .tl_set:N = \l_Archimedes_rofname_tl,
  special .tl_set:N = \l_Archimedes_specialname_tl,
  wt .tl_set:N = \l_Archimedes_wtname_tl,
  avl .initial:n = Avl,
  clip .initial:n = Clip,
  cls .initial:n = Cls,
  dmg .initial:n = Dmg,
  name .initial:n = Name,
  pen .initial:n = Pen,
  rld .initial:n = Rld,
  rng .initial:n = Rng,
  rof .initial:n = RoF,
  special .initial:n = Special,
  wt .initial:n = Wt,
}
\keys_define:nn { Archimedes / card / units }
{
  avl .tl_set:N = \l_Archimedes_avlunit_tl,
  clip .tl_set:N = \l_Archimedes_clipunit_tl,
  cls .tl_set:N = \l_Archimedes_clsunit_tl,
  dmg .tl_set:N = \l_Archimedes_dmgunit_tl,
  name .tl_set:N = \l_Archimedes_nameunit_tl,
  pen .tl_set:N = \l_Archimedes_penunit_tl,
  rld .tl_set:N = \l_Archimedes_rldunit_tl,
  rng .tl_set:N = \l_Archimedes_rngunit_tl,
  rof .tl_set:N = \l_Archimedes_rofunit_tl,
  special .tl_set:N = \l_Archimedes_specialunit_tl,
  wt .tl_set:N = \l_Archimedes_wtunit_tl,
  avl .initial:n = ,
  clip .initial:n = ,
  cls .initial:n = ,
  dmg .initial:n = ,
  name .initial:n = ,
  pen .initial:n = ,
  rld .initial:n = ,
  rng .initial:n = km,
  rof .initial:n = ,
  special .initial:n = ,
  wt .initial:n = kg,
}
\cs_new_protected:Nn \Archimedes_pageme:nn
{
  \begin{minipage}{#1\l_Archimedes_card_width_dim}
    \centering
    \fbox{
      \parbox{\linewidth-2\fboxrule-2.5\fboxsep}
      {
        \strut
        \textsc{ \use:c { l_Archimedes_#2name_tl } } : ~ \skip_horizontal:n {\fill} \use:c { l_Archimedes_#2_tl } \skip_horizontal:n {\fill}  \hbox:n { \use:c { l_Archimedes_#2unit_tl } }
      }
    }
  \end{minipage}
}
\NewDocumentCommand \cardnames { m }{
  \keys_set:nn { Archimedes / card / names } { #1 }
}
\NewDocumentCommand \cardunits { m }{
  \keys_set:nn { Archimedes / card / units } { #1 }
}
\NewDocumentCommand \cardme { O {} }{%
  \group_begin:
  \keys_set:nn { Archimedes / card } { #1 }
  \dim_sub:Nn \l_Archimedes_card_width_dim { 2\fboxrule + 2\fboxsep }
  \fbox{
    \begin{minipage}{\l_Archimedes_card_width_dim}
      \centering
      \Archimedes_pageme:nn {.69 } { name }
      \Archimedes_pageme:nn {.31 } { cls }\par
      \Archimedes_pageme:nn { .22 } { rng }
      \Archimedes_pageme:nn { .38 } { rof }
      \Archimedes_pageme:nn { .4 } { dmg }\par
      \Archimedes_pageme:nn { .22 } { pen }
      \Archimedes_pageme:nn { .19 } { clip }
      \Archimedes_pageme:nn { .19 } { rld }
      \Archimedes_pageme:nn { .18 } { wt }
      \Archimedes_pageme:nn { .22 } { avl }\par
      \Archimedes_pageme:nn {  } { special }
    \end{minipage}
  }
  \group_end:
}
\ExplSyntaxOff
\begin{document}
\noindent
\cardme

\noindent
\cardme[%
  card width=\textwidth,
  name=This One,
  cls=Aristocracy,
  rng=450,
  rof=RoF,
  dmg=Extensive,
  pen=Pen,
  clip=Y,
  rld=N,
  wt=1,
  avl=Y,
  special=Extraordinary powers,
]

\cardnames{
  name=Enw,
  cls=Dth,
  rng=Pll,
  dmg=Dfd,
  clip=Cnf,
  rld=AilLl,
  wt=Pwys,
  avl=ArGl,
  special=Arbennig,
}

\noindent\cardme[card width=.85\textwidth]
\end{document}

Original Answer
This uses \fbox and minipage to create the boxes-in-a-box look. I adjusted some of the percentages so they added to 100 on each line.
\cardme[<width>]{<content>}

sets up the main box. The optional parameter specifies the width. The required argument specifies the content. The default width is three-quarters of the width of the text block.
\pageme[<width>][<content>]

constructs an inner box. The two optional arguments are, first, the width and, second, the content. The default is to create an empty box the entire (inner) width of the card.
Then
\cardme[.8\textwidth]{%
  \pageme[.69][Name]%
  \pageme[.31][Class]

  \pageme[.22][Range]%
  \pageme[.38][RoF]%
  \pageme[.4][Damage]

  \pageme[.22][Pen]%
  \pageme[.19][Clip]%
  \pageme[.19][Reload]%
  \pageme[.18][Weight]%
  \pageme[.22][Availability]

  \pageme[][Special]%
}

specifies the following card:

Complete code:
\documentclass{article}
\usepackage{calc,xparse}
\newlength\mycardwidth
\setlength\mycardwidth{.75\textwidth}
\NewDocumentCommand \boxme { O{} }{%
  \fbox{%
    \parbox{\linewidth-2\fboxrule-2.5\fboxsep}{\strut #1}%
  }%
}
\NewDocumentCommand \pageme { O{} O{} }{%
  \begin{minipage}{#1\mycardwidth}
    \centering\boxme[#2]
  \end{minipage}%
}
\NewDocumentCommand \cardme { O{.75\textwidth} +m }{%
  \setlength\mycardwidth{#1-2\fboxrule-2\fboxsep}%
  \fbox{%
    \begin{minipage}{\mycardwidth}
      \centering
      #2%
    \end{minipage}%
  }%
}
\begin{document}
\cardme[.8\textwidth]{%
  \pageme[.69][Name]%
  \pageme[.31][Class]

  \pageme[.22][Range]%
  \pageme[.38][RoF]%
  \pageme[.4][Damage]

  \pageme[.22][Pen]%
  \pageme[.19][Clip]%
  \pageme[.19][Reload]%
  \pageme[.18][Weight]%
  \pageme[.22][Availability]

  \pageme[][Special]%
}
\end{document}