text:
Q: Equally space all words I want to create a document which I can annotate by hand (that is, write above each word in pencil), but, unfortunately, the word length isn't a good indicator of how long the annotation is. I would like to have each word treated as if they were all of the same length so that the space between the end of one word and the start of the word after the next is the same. I hope I can make this clear:
Before:
Some sample text to indicate what I mean.

After:
     Some    sample    text      to       indicate       what         I          mean.

Note that shorter words, such as to and I have much larger spaces between the words to compensate for their shorter length. Thanks for any help.

A: The inter-word spacing is controlled by three parameters; \fontdimen2 (the normal inter-word space), \fontdimen3 (the amount of stretch of the inter-word space), and \fontdimen4 (the amount of shrink). So, one possibility is to change these parameters as required.
\documentclass{article}
\begin{document}

\spaceskip=8\fontdimen2\font plus 1.5\fontdimen3\font
minus 1.5\fontdimen4\font

Some sample text to indicate what I mean.

\end{document}

A: Because the words are equally spaced, they line up like an array, unless I turn on \parindent or \centering.  I also added \doublespacing from setspace, since the whole idea is to have room for annotation.
Works across paragraphs.  Don't try this in math mode.  An optional argument allows the desired word width to be set.
With this solution, \fixlen calls on the recursion routine \fixlenpar, which will filter through the data a paragraph at a time as #1 until it runs out of paragraphs.  It passes each paragraph to \fixlenword, which is also a recursion routine that filters through each successive paragraph a word at a time as #1.  With each word, it places it in a fixed-width, center-aligned \makebox.
\documentclass{article}
\newcommand\fixlen[2][10ex]{\def\fixwidth{#1}\fixlenpar#2\par\relax}
\long\def\fixlenpar#1\par#2\relax{%
  \fixlenword#1 \relax%
  \ifx\relax#2\relax\def\next{}\else\par\def\next{\fixlenpar#2\relax}\fi\next}
\def\fixlenword#1 #2\relax{%
  \makebox[\fixwidth][c]{#1}%
  \ifx\relax#2\relax\def\next{}\else\ \def\next{\fixlenword#2\relax}\fi\next}

\parindent0pt\relax
\parskip 1em\relax
\usepackage{setspace}
\doublespacing
\begin{document}
\fixlen{%
I want to create a document which I can annotate by hand (that is, write above each word in pencil), but, unfortunately, the word length isn't a good indicator of how long the annotation is. I would like to have each word treated as if they were all of the same length so that the space between the end of one word and the start of the next, next word is the same. I hope I can make this clear

Before:

Some sample text to indicate what I mean.

Note that shorter words, such as to and I have much larger spaces between the words to compensate for their shorter length. Thanks for any help.}

\end{document}


text:
Q: Why is `goog.base(this)` necessary in addition to `goog.inherits()`? In this snippet of Google Closure javascript code involving a constructor, why is goog.base(this); necessary? Doesn't Foo already inherit from Disposable with goog.inherits(foo, goog.Disposable);?
goog.provide('Foo');

/**
 * @constructor
 * @extends {goog.Disposable}
 */
Foo = function() {
  goog.base(this);
}
goog.inherits(foo, goog.Disposable);

foo.prototype.doSomething = function(){
  ...
}

foo.prototype.disposeInternal = function(){
  ...
}

A: goog.inherits(childConstructor, parentConstructor)
goog.inherits() establishes the prototype chain from the child constructor
to the parent constructor.
/**
 * Inherit the prototype methods from one constructor into another.
 * @param {Function} childCtor Child class.
 * @param {Function} parentCtor Parent class.
 */
goog.inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  /** @override */
  childCtor.prototype.constructor = childCtor;
};

In addition to prototype properties, constructors may have "own" properties
(i.e. instance-specific properties added to this). Since goog.inherits()
does not call the parent constructor, own properties are not copied to the
child constructor and any initialization code in the parent does not get
executed. For these reasons, the standard pattern is to chain constructors as in the following example.
/**
 * @param {string} name The parent's name.
 * @constructor
 */
var Parent = function(name) {
  /**
   * @type {string}
   * @private
   */
  this.name_ = name;
}

/**
 * @param {string} name The child's name.
 * @constructor
 * @extends {Parent}
 */
var Child = function(name) {
  Parent.call(this, name);
}
goog.inherits(Child, Parent);

goog.base(self, opt_methodName, var_args)
goog.base() is a helper function for calling parent methods so that you do
not need to explicitly use call() or apply().

If [goog.base()] is called from a constructor, then this calls the
  superclass contructor with arguments 1-N.
If this is called from a prototype method, then you must pass the name of
  the method as the second argument to this function. If you do not,
  you will get a runtime error. This calls the superclass' method with
  arguments 2-N.
This function only works if you use goog.inherits to express inheritance
  relationships between your classes.

In Closure code it is common to chain constructors with goog.base() rather
than calling the parent constructor explicitly.
/**
 * @param {string} name The child's name.
 * @constructor
 * @extends {Parent}
 */
var Child = function(name) {
  goog.base(this, name);
}
goog.inherits(Child, Parent);

Further Reading

*

*Inheritance Patterns in JavaScript by Michael Bolin

*An Examination of goog.base() by Michael Bolin

*Closure: The Definitive Guide by Michael Bolin

*JavaScript Patterns by Stoyan Stefanov (see Chapter 6: "Code Reuse Patterns" for a detailed analysis of the pattern used to implement goog.inherits() - Classical Pattern #5--A Temporary Constructor)

A: In JavaScript, this is set entirely by how the function is called, not where it's defined (as it is in Java, C#, and C++). So to make this within the call to goog.Disposable be the this of where you're calling it, you have to use .call or .apply. Otherwise, if you just called goog.Disposable(), within the call this would be goog.
Basically, there are two ways to set this for the function you're calling:

*

*Use obj.func() or obj["func"]() notation — e.g., make the call as part of the same overall expression where you're retrieving a property from the object. This tells the engine that within the call, you want this to refer to obj.

*Use call or apply to be more explicit about it by supplying the object to use as this as the first argument. The only difference between call and apply is how you supply other arguments: With call, you supply them as discrete args, e.g. foo.call(obj, 1, 2, 3) calls foo with this set to obj and the arguments 1, 2, and 3. With apply, you supply the arguments as an array-like second argument: foo.apply(obj, [1, 2, 3]); (note the [ and ]; e.g. var a = [1, 2, 3]; foo.call(obj, a);
More to explore:

*

*Mythical methods

*You must remember this

A: You can see
Foo = function() {
  goog.base(this); //call parent constructor
}
goog.inherits(foo, goog.Disposable);

As:
public class Foo extends Disposable(){
  public Foo(){
    super(); // call parent constructor
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot index string with string "foo" I have some json (included below), and the first key is a random number (a docker image ID), so I won't know what it is before I have to parse the json.
what I would like to do is
cat eval.json | jq \
'."3193328829c7b3ec6be0ab6bfd8988b97a35006ea578c9ce4ab7fe29cbc5ec94".result.rows[] | select (.[2]=="stop")'

This works fine, except I need to do this in the general case where I don't know the Image ID ahead of time.
I tried this, which sort of works except I get some "cannot index" errors:
cat eval.json | jq .[] | jq '.result.rows[] | select (.[2]=="stop")'
[
  "CVE-2021-3156+sudo",
  "HIGH Vulnerability found in os package type (dpkg) - sudo (fixed in: 1.8.31-1ubuntu1.2)(CVE-2021-3156 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2021-3156)",
  "stop",
  false
]
jq: error (at <stdin>:33): Cannot index array with string "result"
jq: error (at <stdin>:34): Cannot index string with string "result"
jq: error (at <stdin>:35): Cannot index array with string "result"
jq: error (at <stdin>:36): Cannot index array with string "result"

a little refinement helped with the array issues, but I still have the string error:
cat eval.json | jq '.[].result.rows[] | select (.[2]=="stop")'
[
  "CVE-2021-3156+sudo",
  "HIGH Vulnerability found in os package type (dpkg) - sudo (fixed in: 1.8.31-1ubuntu1.2)(CVE-2021-3156 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2021-3156)",
  "stop",
  false
]
jq: error (at <stdin>:38): Cannot index array with string "result"

I can delete those last four keys (I don't think I'll ever need them for what I'm trying to do), but that seems like a pretty clunky hack.
cat eval.json | jq 'del(.whitelist_names, .whitelist_data, .policy_name, .policy_data) |  .[].result.rows[] | select ((.[2]=="stop") and (.[3]==false)) | .[0], .[1]'
"CVE-2021-3156+sudo"
"HIGH Vulnerability found in os package type (dpkg) - sudo (fixed in: 1.8.31-1ubuntu1.2)(CVE-2021-3156 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2021-3156)"

Is there something better than using del to clear those keys out?  it seems like if there were some way to specify the first key like there is for the Nth element in an array, that would be a lot easier.  The other think I thought about was doing something awkward like just printing the keys out, capturing that long string in a variable, then using that to select that key directly, but that is more cumbersome than deleting the other keys.
full json below:
{
  "3193328829c7b3ec6be0ab6bfd8988b97a35006ea578c9ce4ab7fe29cbc5ec94": {
    "result": {
      "final_action": "stop",
      "header": [
        "Trigger_Id",
        "Check_Output",
        "Gate_Action",
        "Whitelisted"
      ],
      "row_count": 3,
      "rows": [
        [
          "41cb7cdf04850e33a11f80c42bf660b3",
          "Dockerfile directive 'HEALTHCHECK' not found, matching condition 'not_exists' check",
          "warn",
          false
        ],
        [
          "CVE-2018-20839+libudev1",
          "MEDIUM Vulnerability found in os package type (dpkg) - libudev1 (CVE-2018-20839 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2018-20839)",
          "warn",
          false
        ],
        [
          "CVE-2021-3156+sudo",
          "HIGH Vulnerability found in os package type (dpkg) - sudo (fixed in: 1.8.31-1ubuntu1.2)(CVE-2021-3156 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2021-3156)",
          "stop",
          false
        ]
      ]
    }
  },
  "policy_data": [],
  "policy_name": "",
  "whitelist_data": [],
  "whitelist_names": []
}

A: Adding one or more "?" would be one way to resolve the issue:

.[].result?.rows[] | select (.[2]=="stop")

If you want to specify the first key, use keys_unsorted[0], as in:
.[keys_unsorted[0]].result.rows[] | select (.[2]=="stop")


text:
Q: OS agnostic terminal Basically we have a process, spawned from command line which runs in a separate window. (Just ssh, if it matters). The command we use right now breaks on linux:
osascript -e 'tell application \"Terminal\" to do script \"foo\"'
I can use, xterm -e "foo", but that still seems too explicit.
Is there just something that says run this in new window?
Must work on Mac and Ubuntu, wider scopes appreciated. Also, minimal configuration please. I'd like to keep it a one liner.


text:
Q: Has the foregroundservice stopped on Android OREO in doze mode state? I'm a beginner to the Android development, I'm building an Alarm app.
I tried to run the app on any android version (5.0, 4.4, 6.0, 7.0) the alarm still ring on time, but I try to run on Android Oreo 8 (Huawei P20 lite, Sony Xperia XZ1) alarm can't ring. After then, I have to use JobIntentService or foregroundservice so the alarm can ring but not on time at background device.
What's wrong? When setting time for alarm and waiting at background app, alarm ring on time but at background device, alarm still ring but not on time or even alarm not ring? Anyone can find out a solution for this issue?
Thank you so much!

A: Please, check the android documentation for doze mode.
https://developer.android.com/training/monitoring-device-state/doze-standby

If you need to set alarms that fire while in Doze, use
  setAndAllowWhileIdle() or setExactAndAllowWhileIdle().


text:
Q: mqtt-Where mosquitto store all topics? I'm tracing mosquitto for a few days
I want to check some questions:

*

*Would MQTT broker store all of the pub/sub topics when they pub/sub? if yes,where?

*Which struct(or file?) when publish send a message, publisher will search the struct whether topic has been used,and then reused it?
Thank you all for answer for mqtt  beginner.

A: Short answers:
To keep it simple lets assume QOS 0

*

*No, the broker only needs to keep a list of which topics/topic patterns each client is subscribed to. There is no need to keep any information about a published message under unless it needs to queue that message for a offline client with a persistent subscription or it's a retained message.

*Your second question doesn't really make any sense, but I assume you mean which structure does the broker search when it receives a new message from a publisher. In which case I suggest you look at the very aptly named handle_publish.c


text:
Q: How to make Sliding up Panel city circular from only one side FLUTTER I'm a beginner and want to make Sliding up Panel like this. Your help will be appreciated

A: I think this will get you what you want:
import 'package:flutter/material.dart';

    void main() => runApp(const MyApp());

    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);

      static const String _title = 'Flutter Code Sample';

      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          title: _title,
          home: MyStatelessWidget(),
        );
      }
    }

    class MyStatelessWidget extends StatelessWidget {
      const MyStatelessWidget({Key? key}) : super(key: key);

      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body:
          Stack(
            children: [
              Center(
                child: Container(
                    height: 300,
                    width: 300,
                    child: Card(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                              topRight: Radius.circular(50),
                              topLeft: Radius.circular(50))),
                    )),
              ),
              Positioned(
// You can change top and left values based on the layout or device
                top: 140,
                left: 70,
                child: Container(
                  height: 100,
                  width: 100,
                  child: Card(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(100)),
                      child: Column(
                        children: [
                          SizedBox(
                            height: 20,
                          ),
                          CircleAvatar(
                              radius: 20,
                              backgroundImage: NetworkImage(
                                  'https://icon-library.com/images/avatar-icon-images/avatar-icon-images-4.jpg')),
                          Text('Patrick')
                        ],
                      )),
                ),
              ),
            ],
          ),
        );
      }
    }

A: try this:
  GestureDetector(
    onTap: () {
      showModalBottomSheet(
          context: context,
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15.0),
                topRight: Radius.circular(15.0)),
          ),
          builder: (context) {
            return Stack(
              overflow: Overflow.visible,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: List<Widget>.generate(
                    10,
                    (int index) => ListTile(
                      leading: Icon(Icons.email, color: Colors.black),
                      title: Text('$index',
                          style: TextStyle(color: Colors.black)),
                      onTap: () {},
                    ),
                  ),
                ),
                Positioned(
                  top: -50,
                  left: 20,
                  child: ClipOval(child: Container(
      width: 100,
      height: 100,
      color: Colors.red,
    ),)
                ),
              ],
            );
          });
    },


text:
Q: TeamCity Error: "cannot start build runner; NUnit runner failure"
Cannot start build runner (1)
Failed to start reason No assemblies were found.
Uncategorized problem (1)
Build failure reason NUnit runner failure

After building all of the projects and running a NUnit TestFixture in TeamCity I received the error "cannot start build runner; NUnit runner failure." All of the tests run, however at the end of the process the error was thrown. I looked up similar stack overflow questions, but I am unable to make any connections.

*

*Why am I getting this error?

*How might I go about fixing it?

Any insight is appreciated.

A: Resolved:

*

*An outdated project in the solution was removed. TeamCity was trying to run test for the project after it was removed which caused the error of not being able to find the assemblies.

*The project was originally removed because it wasn't building, therefore I am refactoring the project and re-adding it to the solution.


text:
Q: Two ways of getting time
Possible Duplicate:
System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

So far I've seen two ways of getting time in Java:
Calendar.getInstance().getTimeInMillis();

and
System.currentTimeMillis();

I know that the latter is UNIX time, i.e. time passed from 1970...
But, when to use first and when to use second time?
Thanks.

A: If you need the semantics of the second one (get the current time), then don't use the first one. The first one is only needed when you want to convert a specific moment of your choosing to the epoch number. Keep in mind that currentTimeMillis gives epoch*1000 time.


text:
Q: PHP Contact Form Submit Error In this form submitting, I am facing some errors.
1. The mail is working. But Contact form submit details not showing.
2. Its working on only gmail. Like : abc@gmail.com
3. Not working on the domain like lucky@abc.com. The mail not working.

Please give any suggestion.
<?php

       $Name = trim(strip_tags($_POST['Name']));
       $Email = trim(strip_tags($_POST['Email']));
       $Phone = trim(strip_tags($_POST['Phone']));
       $Subject = trim(strip_tags($_POST['Subject']));
       $Message = htmlentities($_POST['Message']);

       // set here
       $subject = "Contact form submitted!";
       $to = 'lachchanderdagar@gmail.com';

       $body = <<<HTML
$message
HTML;

       $headers = "From: $email\r\n";
       $headers .= "Content-type: text/html\r\n";

       // send the email
       mail($to, $subject, $body, $headers);

       // redirect afterwords, if needed
       header('Location: thanksforcontact.php');
?>


text:
Q: Mixing raw data & model based visualization How to handle the following request from a journal:
I've evaluated a data set using a linear mixed model (lmm). Among the evaluated factors, I was particularly interested in one, which I plotted as a bar graph (default state & modified state). After submitting the paper (and the plot) to a journal, I'm being asked to either

*

*superimpose all data points I used in the lmm to the bar plot or

*add for each of the two states I've plotted in the bar plot the following elements: Median values, min-values, max-values, interquartile interval etc..

Considering that I employed other factors in the lmm model to compensate for confounding patterns in the data, I'm somewhat confused by the request. IMHO, executing either on the data I put into the model might be misleading, as the visualization would now mix (confounded) raw data and (corrected) model based data.
Therefore I'm wondering, whether my reasoning is correct and how to handle the request.


text:
Q: Can't properly set vertical-align My problem: want to div content be in the middle of parent div.
CSS structure:

Basically it is sing-in window, on the right it is email/pass form, on the left - fb login button, and this button I want to be in the middle, but it works with top, works with bottom, on vertical-align:middle it again on the bottom.
CSS:
.sign_in {
    position: absolute;
    border-style: solid;
    border-width: 2px;
    border-color: #c1ffc6;
    background: #fff;
    padding: 2%;
    width: 30%;
    font-family: Arial, sans-serif;
    z-index: 9999999;
    font-size: 14px;

}
.sings_form{

    display: inline-block;
    border-right-style: solid;
    padding-right: 10%;
    border-width: 1px;
    border-color: #c1ffc6;

}
.fb_sing {

    display: inline-block;
    vertical-align: top;
    margin-left: 10%;

}

A: Fix your class names.
sing_form is in your html
sings_form is in your css
fb_sign is in your html
fb_sing is in your css


text:
Q: Need help using IVT in application Explain how $$\sin(\frac{\pi x}{2})=1-x$$
has at least one real solution.
I understand that IVT requires you to have the endpoints.
I know that $-1\leq \sin x \leq 1$
So $-1 \leq \sin(\frac{\pi x}{2}) \leq 1$
If $f(x) = \sin(\frac{\pi x}{2})-1+x$
$f(-1)=-1+1-(-1)=1>0$
$f(1)=1-1+1=1>0$
But I need one of them to be less than 0. What did I do wrong and how  do I solve this?

A: On $[0,1]$, $f(0)=-1$ while $f(1)=1$.
Can you finish now?
By the way, $f(-1)=-3$.

A: Let, f(x) = sin(πx/2) - 1+X
f(1) = 1
f(0) = -1
By Intermediate value property there must be a real root in (0,1).
By the way,
f(-1) = -3
You have done a mistake by doing ' -(-1) ' . It should be '(-1)'.
Look it carefully.


text:
Q: Make answer class a struct? Usually play around with making games but I'm taking a detour into making a little question and answer app, for educational purposes.
Anyway I have a question class which holds numerous members: the question itself, the answer to the question, an array of possible answers etc. No doubts this should be a class.
My answer class however only holds a string, an Enum and an int id number as shown below:
public class Answer
{
    public string Answer { get { return answer;} private set { answer = value; } }
    public Answer_Category = Some_Value; // The enum.
    public int ID { get { return id; } private set { return id; } }

    private string answer;
    private int id;
}

Ok so it holds two strings, also the ctor has been out.
So should I be making this a struct? I ask as it seems comparable to making a Vector a struct, being such a small data structure 'n all.
Naturally being a question and answer application the answer class/struct is going to be the subject of a lot of search calls.
IMO this should be a struct - solely because of the size of the structure, haven't played around with C# for some time though so just looking for some clarification.

A: The decision boils down to whether you want a value type or a reference type. In other words what do you want the assignment operator to mean? If you want assignment to copy the value, use a struct. If you want assignment to take another reference e, use a class.

A: There are two primary usages cases for structures: for situations where one wishes to conveniently move around aggregations of independent variables (such as the coordinates of a point), or where a small immutable object will often be used in situations where identity is not important (as would be the case with e.g. Decimal or DateTime).  Since a variable of structure type simply holds an aggregation of variables, structures which are used for that purpose should simply expose their contents as public fields.  Doing so will make clear that any invariants that might be applicable to structure members will be the responsibility of the code creating the structure.  For example, if one has a structure MinMax with int members Minimum and Maximum, using exposed public fields for those members would make clear that the structure itself makes no promise that Maximum >= Minimum.  A method which returns such a structure may promise that it will not return one where Maximum < Minimum, but methods which receive structures and want Maximum >= Minimum will have to check those fields themselves.  On the flip side, code which wishes to set those values in a structure will be able to set them in whatever order is convenient, without having to worry about the struct throwing an exception because the Minimum was set higher than Maximum.
The MSDN guidelines assume that the purpose of any struct is to behave like an object.  Since piecewise-mutable structures don't behave like objects, structures which will be used like objects shouldn't be piecewise mutable.  On the other hand, aggregations of variables can be useful in and of themselves; one should use a struct in cases where one wants an aggregation of variables, but should try to make it as obvious as possible that the struct is an aggregation of variables rather than an object.


text:
Q: Read and modify a the code of a python script from another python script Is there any package in python that can read a python script and give the ability to modify it? Something like the following:
my_script: PythonScript = read_script("my_script.py")
list_of_functions: [PythonFunction] = my_script.functions
for func in list_of_functions:
   print(func.name)
   print(func.body)
list_of_functions[0].name = "new_function_name"
my_script.functions = list_of_functions

So again what I am looking for is a package that can read a python script and give the ability to modify it, not necessary the same way I did in my example, I just have a lot of scripts and I am looking for a way to do a fix on all of them without using find and replace in an IDE nor reading them as text files for example.
Somehow traversing a python script from python code? I do not know what keywords should I use to do a proper search either.


text:
Q: How to disabled a button based on child component form validation in vue I have a child component
<v-form ref="form" v-model="valid" lazy-validation>
  <v-select v-model="test" :items="data" :rules="[v => !!v || 'Required']"></v-select>
</v-form>

If i try this.$refs.form.validate() in child component it is validating.
And in parent component, i have a simple button
<v-btn color="primary" @click="save()">save</v-btn>

On clicking on the button i can call the child component method to get the validation status of the child form. It works great.
Now i would like to disable the button, if the child form is not valid. What is the best way to do this?

A: The validity of your form is updated live by vuetify, via the v-model property of the v-form. You just need to bind this property such that it's accessible from wherever you need it. When a property like this is used in more than one component, it's shared state. I much prefer getting shared state out of Vue components, and putting it in a global object that I like to call vueStore. There are other ways to share state, but I like this way !

var vueStore = {
  valid:false
}
Vue.component('my-child',{
  template: `
<v-form ref="form"
  v-model="vueStore.valid"
>
  <v-select v-model="test" :items="items" :rules="[v => !!v || 'Required']"></v-select>
</v-form>`,
  data(){
    return {items:['','red','green','blue'],
    vueStore:vueStore,
    test:null
    }
  }
})

var vm = new Vue({
  el:'#app',
  data:{vueStore:vueStore},
  methods:{
    save(){
      alert("saving...")
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.18/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.5.5/vuetify.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.5.5/vuetify.min.css" rel="stylesheet"/>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<div id="app">
<v-app>
<my-child></my-child>
<v-btn color="primary" @click="save()" :disabled="!vueStore.valid">save</v-btn>
</v-app>
</div>


text:
Q: Javascript variable - AJAX- send to server without waitting for answer My click counter do not send variable to server.
I tried to find some example how to create, but whatever i tried, there is no attempt to send data to server.It looks like AJAX should be best option, but i do something wrong.  i tried also window.location.href  javascript, but this redirect me to other page and i want continue in current srcipt.
court1.js:

var button = document.getElementById("clickme"),
  count = 0;
button.onclick = function() {
  count += 1;
  button.innerHTML = "result: " + count;
$.ajax({
    type: 'POST',
    url: 'count.php',
    data:+count,
});
};

index.html

  <meta charset="UTF-8">
  <title></title>

court 1

    <button id="clickme">click here</button>

counter is working perfectly..  after refresh count from 0.
But i dont see any attempt to send variable to server. Debugging mode in chrome doesn't show any activity.
I need after every touch (click) send new value from variable $count to server.  Counter have to continue in work without any disturbing. We are talking about few clicks per seccond.
I would like to send new value to php script or also i am open to send new value by UDP packet to server and gather data on server through syslog-ng.
Priority is minimal load of resources on client side.
thank you for your help

A: the main problem is that there is no loaded jquery in HTML code:

this is main reason, why ajax is not activated.


text:
Q: ios restrict to input more than one "." or "," (if it is russian localization) problem is that on russian localization numeric pad has "," instead of "." and when view is loaded i have "0.0" in the text field, when I thought that user would be able to input only "." I used such code to prevent inputting more than one "."
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSArray  *arrayOfString = [newString componentsSeparatedByString:@"."];

    if ([arrayOfString count] > 2 )
    {
        return NO;
    }
}

but when occured that in rus localization pad appears with "," instead of "." I can't find out how I can prevent of inputting "," if there is "." already
and i am replacing inputted "," with "." so i will be glad if someone helps to restrict inputting "," if thereis "." in the text field already

A: You can use NSNumberFormatter to have a localized number in your field when it displays.
NSNumberFormatter * formatter =  [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:1];
[formatter setLocale:[NSLocale currentLocale]];
NSString * myString = [formatter stringFromNumber:[NSNumber numberWithFloat:123.456]];

from https://stackoverflow.com/a/11504127/719866
You can use the formatter in your check to see if the value entered by the user is valid for that locale with the -numberFromString: method.


text:
Q: Getting an empty JQuery object In the following code I set up a change handler on a select box to show and hide some follow up questions based on the value of the selection.
Further, for some values of the selection there is an extra message that is displayed.
In order to check to see if I need to hide the extra message, I keep a variable called Previous.  Upon execution of the handler I check to see if Previous is null or if the size is 0.
It would be nice to initialize Previous to an empty JQuery object so as not to have to do the extra check for null.
Doing a $() returns an object with the size of 1.
Is there a way to create an empty Jquery object?

//Init function.
$(function(){
//Hold the previously selected object for the account type selection.

var Previous = null;  //Here is where I would like to initialize.
                      //something like Previous = $();

$("SELECT[name='AccountType']").change(
    function () {
        //Hide Previous message if there was one.
        if(Previous == null || Previous.size() > 0){
            Previous.hide();
        }

        //Show the message if found and save it as previous.
        Previous = $("#"+this.value+"_Msg").show();

        //Get fisrt question
        var FirstQuestion = $(".FirstQuestion");
        if(this.value === ''){
            FirstQuestion.hide();
        }else{
            //Manually show FirstQuestion.
            FirstQuestion.show();
        }
    });
}

In the worst case I could do something like this:

    var Previous = { size : function () { return 0; } };

but that seems like overkill.

A: My advice is don't do it that way. There are a lot easier ways of doing this. Consider:
<select id="select" name="select">
  <option value="msg_1">Message 1</option>
  <option value="msg_2">Message 1</option>
  <option value="msg_3">Message 1</option>
</select>

  ...

  ...

  ...

$(function() {
  $("#select").change(function() {
    var val = $(this).val();
    $("div." + val").show();
    $("div:not(." + val + ")").hide();
  });
});

Much easier. Basically give classes to indicate what to show and hide and then there is no tracking required. An alternative is:
$(function() {
  $("#select").change(function() {
    var val = $(this).val();
    $("div").each(function() {
      if ($(this).hasClass(val)) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  });
});

A: $();

Returning an Empty Set
As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set (with a .length property of 0). In previous versions of jQuery, this would return a set containing the document node.

Source: api.jquery.com

A: This creates an empty jQuery-object:
$([])

Update:
In newer versions of jQuery (1.4+), you can use:
$()

A: try this
 var new = $([]);

I ain't a good programmer but it gives u empty object :))


text:
Q: How To Close A VCL Metro App With Touch Swiping If you create a new VCL Metro App by selecting File-New-VCL Metropolis App in the IDE, then run the app when you try to close the app with a finger drag from the top of the screen to the bottom of the screen the app appears to close, and the Start Page becomes visible but the app does not actually close.  If you swipe-in from the left edge of the start page, the metro app is still running.
I tried adding Application.Terminate in the OnFormHide event, but the app still does not close.  The only way to close the app is by swiping up from the bottom of the screen so that the app bar is visible, then touch the close button.
So my question is- How go you close a VCL Metro Application with touch swiping?
The same thing occurs if you create a FireMonkey Metro App.


text:
Q: Access remote EJB from separate Wildfly Swarm My goal:
To access @Remote EJB from separate Wildfly Swarm server
Current code:
Bean on wildfly swarm:
@Startup @Singleton
public class Bean1 {
    @Inject private LoginFacade loginFacade;

    @PostConstruct void setup() {
        System.out.println(loginFacade.getCurrentUserWithoutSession());
    }
}

Config bean on swarm:
@Startup @Singleton
public class Config {
    @Produces
    public Context context() throws NamingException {
        final Hashtable<String, Object> props = new Hashtable<>();
        props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
        return new InitialContext(props);
    }

    @Produces
    public LoginFacade loginFacadeBean(Context context) throws NamingException {
        return (LoginFacade) context.lookup("ejb:or/project//LoginFacadeBean!f.q.d.n.LoginFacade");
    }
}

Swarm config:
---
swarm:
  http:
    port: 8081
  logging: DEBUG
  remoting:
    remote-outbound-connections:
      remote-ejb-connection:
        security-realm: ejb-security-realm
        username: qazwsxmko
        outbound-socket-binding-ref: remote-ejb
        properties:
          SASL_POLICY_NOPLAINTEXT:
            value: "false"
          SASL_POLICY_NOANONYMOUS:
            value: "false"
          SSL_ENABLED:
            value: "false"
  management:
    security-realms:
      ejb-security-realm:
        secret-server-identity:
          value: "cWF6d3N4bWtvMQ=="
    http:
      port: 9991
  network:
    socket-binding-groups:
      standard-sockets:
        outbound-socket-bindings:
          remote-ejb:
            remote-host: localhost
            remote-port: 8080

Meaningful parts of standalone-full.xml from remote wildfly:
        <security-realm name="ApplicationRealm">
            <authentication>
                <local default-user="$local" allowed-users="*" skip-group-loading="true"/>
                <properties path="application-users.properties" relative-to="jboss.server.config.dir"/>
            </authentication>
            <authorization>
                <properties path="application-roles.properties" relative-to="jboss.server.config.dir"/>
            </authorization>
        </security-realm>
        <!---->
        <http-connector name="mobile-connector" connector-ref="default" security-realm="ApplicationRealm"/>

On launching application I'm getting following error:
2018-09-20 20:32:23,953 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 4) MSC000001: Failed to start service jboss.deployment.unit."demo.war".component.Bean1.START: org.jboss.msc.service.StartException in service jboss.deployment.unit."demo.war".component.Bean1.START: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance
        at org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:57)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
        at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance
        at org.jboss.as.ee.component.BasicComponent.constructComponentInstance(BasicComponent.java:163)
        at org.jboss.as.ee.component.BasicComponent.constructComponentInstance(BasicComponent.java:134)
        at org.jboss.as.ee.component.BasicComponent.createInstance(BasicComponent.java:88)
        at org.jboss.as.ejb3.component.singleton.SingletonComponent.getComponentInstance(SingletonComponent.java:124)
        at org.jboss.as.ejb3.component.singleton.SingletonComponent.start(SingletonComponent.java:138)
        at org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:54)
        ... 6 more
Caused by: javax.ejb.EJBAccessException: WFLYSEC0027: Invalid User
        at org.jboss.as.ejb3.security.SecurityContextInterceptor$1.run(SecurityContextInterceptor.java:69)
        at org.jboss.as.ejb3.security.SecurityContextInterceptor$1.run(SecurityContextInterceptor.java:49)
        at org.jboss.as.ejb3.security.SecurityContextInterceptor.processInvocation(SecurityContextInterceptor.java:97)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ejb3.deployment.processors.StartupAwaitInterceptor.processInvocation(StartupAwaitInterceptor.java:22)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ejb3.deployment.processors.EjbSuspendInterceptor.processInvocation(EjbSuspendInterceptor.java:53)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:67)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:54)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.invocation.ContextClassLoaderInterceptor.processInvocation(ContextClassLoaderInterceptor.java:64)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
        at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:636)
        at org.jboss.invocation.AccessCheckingInterceptor.processInvocation(AccessCheckingInterceptor.java:61)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.invocation.InterceptorContext.run(InterceptorContext.java:356)
        at org.jboss.invocation.PrivilegedWithCombinerInterceptor.processInvocation(PrivilegedWithCombinerInterceptor.java:80)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
        at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:198)
        at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler.invokeMethod(MethodInvocationMessageHandler.java:328)
        at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler.access$100(MethodInvocationMessageHandler.java:67)
        at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler$1.run(MethodInvocationMessageHandler.java:201)
        at org.jboss.as.ejb3.remote.protocol.versionone.MethodInvocationMessageHandler.processMessage(MethodInvocationMessageHandler.java:263)
        at org.jboss.as.ejb3.remote.protocol.versionone.VersionOneProtocolChannelReceiver.processMessage(VersionOneProtocolChannelReceiver.java:213)
        at org.jboss.as.ejb3.remote.protocol.versiontwo.VersionTwoProtocolChannelReceiver.processMessage(VersionTwoProtocolChannelReceiver.java:76)
        at org.jboss.as.ejb3.remote.protocol.versionone.VersionOneProtocolChannelReceiver.handleMessage(VersionOneProtocolChannelReceiver.java:159)
        at org.jboss.remoting3.remote.RemoteConnectionChannel$5.run(RemoteConnectionChannel.java:456)
        at org.jboss.remoting3.EndpointImpl$TrackingExecutor$1.run(EndpointImpl.java:731)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Obviously I've checked login/password many times, created new users and so on.
Just before showing error application writes in logs several messages, containing following string

Received MODULE_AVAILABLE(8) message for module "module name here"

Which makes me thing that one server is able to connect to another
My server is wildfly 10.1, version of wildfly swarm is 2.2.0


text:
Q: How get the card type from reading a range of bins I am trying to get a range of card type from a list bins that are associated with that card type, but whenever I ran the code the card-type is printed as null am not sure what I am doing wrong
This are the bins in a text
400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc

Whenever I Pass 4111111111111111 instead of getting visa i end getting null,
this is what I have done so far
package cardsystem;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

public class Solution {

    /**
     * An entity to hold bin range details. A bin range is a pair of 12 digit numbers that
     * mark the boundaries of the range which is maped to other bin range properties such
     * as a card type. The range boundaries are inclusive.
     */
    static final class BinRange {
        final String start;
        final String end;
        final String cardType;

        BinRange(String start, String end, String cardType) {
            this.start = start;
            this.end = end;
            this.cardType = cardType;
        }
    }

    //  I need a hashmap which hold index and CardType. Each index corresponding an interval (start-end).
    private static HashMap<Integer, String> cache = new HashMap<>();
    private static List<Long> startEndList = new ArrayList<>();

    interface CardTypeCache {
        /**
         * @param cardNumber 12 to 23 digit card number.
         * @return the card type for this cardNumber or null if the card number does not
         * fall into any valid bin ranges.
         */
        String get(String cardNumber);
    }

    /**
     * @param binRanges the list of card bin ranges to build a cache from.
     * @return an implementation of CardTypeCache.
     */
    public static CardTypeCache buildCache(List<BinRange> binRanges) {

        cache = new HashMap<>();

        for (int i = 0; i < binRanges.size(); i++) {
            cache.put(i, binRanges.get(i).cardType);
        }

        for (BinRange binRange : binRanges) {
            startEndList.add(Long.valueOf(binRange.start)); // Previously, Integer type used, I converted it to 'Long' type
            startEndList.add(Long.valueOf(binRange.end));
        }

        return new CardTypeCacheImpl();
    }

    static class CardTypeCacheImpl implements CardTypeCache {

        public String get(String cardNumber) {

            //Integer index = findIndexLinear(Long.valueOf(cardNumber));    // Linear Search
            Integer index = findIndexBinary(Long.valueOf(cardNumber));      // Binary Search
            return (index != -1) ? cache.get(index) : "null";
        }

        /**
         * Linear Search O(n)
         *
         * @param cardNumber, Searching an index which is between start-end .
         * @return an index. If not found, return -1.
         */
        private Integer findIndexLinear(Long cardNumber) {

            for (int i = 1; i < startEndList.size(); i += 2) {
                if (startEndList.get(i - 1) <= cardNumber && cardNumber <= startEndList.get(i)) {
                    return i / 2;
                }
            }
            return -1;
        }

        /**
         * Binary Search O(logn)
         *
         * @param cardNumber, Searching an index which is between start-end .
         * @return an index. If not found, return -1.
         */
        private Integer findIndexBinary(Long cardNumber) {

            int left = 0;
            int right = startEndList.size();

            while (left < right) {

                int mid = left + (right - left) / 2;

                if (mid % 2 == 0 && startEndList.get(mid) <= cardNumber && cardNumber <= startEndList.get(mid + 1)) { // right pair (start-end) of mid
                    return mid / 2;
                } else if (mid % 2 == 1 && startEndList.get(mid - 1) <= cardNumber && cardNumber <= startEndList.get(mid)) {  // left pair
                    return mid / 2;
                }

                if (cardNumber < startEndList.get(mid)) {
                    right = mid;
                } else {
                    left = mid + 1;
                }
            }
            return -1;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        File text = new File("D:/dev/CardSystem/src/cardsystem/input.txt");

        try (final Scanner scanner = new Scanner(text)) {
            List<Solution.BinRange> binRanges = new ArrayList<>();

            /*
            4111111111111111
            400000000000,499999999999,visa
            500000000000,599999999999,mc
            */

            String cardNumber = scanner.next();
            scanner.nextLine();

            scanner.useDelimiter("[,\n]");

            while (scanner.hasNext()) {
                String start = scanner.next();
                String end = scanner.next();
                String cardType = scanner.next();
                binRanges.add(new Solution.BinRange(start, end, cardType));
                if (scanner.hasNextLine()) {
                    scanner.nextLine();
                }
            }

            Solution.CardTypeCache cache = Solution.buildCache(binRanges);
            if (cache != null) {
                bufferedWriter.write(String.valueOf(cache.get(cardNumber)));
            }
        }

        bufferedWriter.newLine();
        bufferedWriter.close();
    }
}

What am I doing wrong, been scratching my head for hours

A: When you print the output:
bufferedWriter.write(String.valueOf(cache.get(cardNumber)));

The cardNumber is "4111111111111111", and you look for it to be in one of the ranges.
4111 1111 1111 1111
4000 0000 0000

I think your card number is outside every range specified in your file. So you can edit your file, i.e.
FROM
400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc

TO
4000000000000000,4999999999999999,visa
5000000000000000,5999999999999999,mc
4000000000000000,4999999999999999,visa
4200080000000000,4200089999999999,visadebit
4200080000000000,4350009999999999,visa
5400080000000000,5999999999999999,mc

A: FROM
400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc

TO
400000000000,499999999999,visa
500000000000,599999999999,mc
400000000000,499999999999,visa
420008000000,420008999999,visadebit
420008000000,435000999999,visa
540008000000,599999999999,mc

you can try and trim the numbers to the left and omit everything that exceeds 12 digits and then you will get  a print of the card type to the console
here is a line to add
 cardNumber = cardNumber.length() > 13 ? cardNumber.substring(0, 12) : cardNumber;

so the whole function will look like
public String get(String cardNumber) {

        cardNumber = cardNumber.length() > 13 ? cardNumber.substring(0, 12) : cardNumber;
        Integer index = findIndexLinear(Long.valueOf(cardNumber));    // Linear Search
        //Integer index = findIndexBinary(Long.valueOf(cardNumber));      // Binary Search
        return (index != -1) ? cache.get(index) : "null";
    }


text:
Q: java BigDecimal round up/down automatically i have a function that calculates data that creates a BigDecimal format variable and im trying to round up or down accordingly with the results. For instance:
16.543242123 should be 16.5
3.35 should be 3.4
6.3456 should be 6.3
and so on, if the 3rd digit is equal to 5 or above to round up the 2nd digit, if its equal to 4 and below, to remove the 3rd digit. This does not absolutely need to be BigDecimal, i can figure out converting the numbers after i manage to do the rounds up.
Thanks in advance.

A: This should do it:
  BigDecimal bg1 = new BigDecimal(16.543242123);
  bg1 = bg1.setScale(1, BigDecimal.ROUND_HALF_EVEN);
  System.out.println(bg1.toString());  //16.5

  BigDecimal bg2 = new BigDecimal(3.35);
  bg2 = bg2.setScale(1, BigDecimal.ROUND_HALF_EVEN);
  System.out.println(bg2.toString()); //3.4

  BigDecimal bg3 = new BigDecimal(6.3456);
  bg3 = bg3.setScale(1, BigDecimal.ROUND_HALF_EVEN);
  System.out.println(bg3.toString());  //6.3

A: BigDecimal bd = new BigDecimal("16.553242123");
BigDecimal format = bd.setScale(1, RoundingMode.HALF_UP);


text:
Q: IIS7 WebDAV Browsing I'm creating Virtual Directories in IIS7 so that external people can browse various documents.
It's all looking good, except the browsing is in a dull text format. How can I create more of a "Windows Explorer" look and feel when they browse to the folder.

A: If you enable webdav on these folders then the users (with windows computers) can use windows explorer to access these folders just like a folder on their harddrive.
You can map a network drive and use the url as path.
Here is some more explanation Mapping windows drive

A: I would suggest taking a look at IT Hit's Ajax File Browser: http://www.ajaxfilebrowser.com/
It is a WebDAV client written in pure JavaScript that runs in IE, Firefox, Chrome and Safari. It looks very similar to Windows Explorer and has lots of programming features: http://www.webdavsystem.com/ajaxfilebrowser/programming/


text:
Q: Ironic question: Where to go for product recommendations? There have been several questions that I thought of as '''It would be perfect to ask http://workplace.stackexchange.com where to get a good, basic 2"x3.5" color business cards now that Vistaprint makes smaller cards that look tacky on a MagnaCard backing''', except of course that this is an umbrella of forums where product recommendation questions are not deemed constructive.
So is there a recommended procedure for "I have a question that would be perfect for forum X except that it's a product recommendation question?" I know about other forums, and if I wanted a product recommendation for hardware to buy for Ubuntu or whatnot I would go to http://ubuntuforums.org and ask away.
But I'm not sure what to do with the above concern, which is classic workplace concern except for being a product recommendation request and nothing else. Do I just search for business and advertising forums to appropriately ask that question?
Thanks,

A: Stack Exchange is not the place to ask for product recommendations as these are opinion based instead of fact based, that's why those types of questions are closed for not being constructive.
This blog post on the Stack Exchange Blog explains this into further detail.


text:
Q: How to filter a single list with multiple "cases" in Kotlin I have a Sealed class as follows:-
sealed class SoundEffect {
    sealed class Acoustic : SoundEffect() {

        object Active : Acoustic()
        object Inactive : Acoustic()

        object Disable : Acoustic()
        object Enable : Acoustic()
    }

    sealed class Electronic(open val message: String) : SoundEffect() {
        data class Moog(override val message: String) : Electronic(message)
    }

    sealed class Vocal(open val dataMap: MutableMap<String, Any>) : SoundEffect() {
        data class Lieder(override val dataMap: MutableMap<String, Any> = mutableMapOf()) : Vocal(dataMap)
    }
}

and a list of these values:-
 private val sounds : List<Any> = listOf(
        SoundEffect.Acoustic.Active,
        SoundEffect.Acoustic.Disable,
        SoundEffect.Acoustic.Enable,
        SoundEffect.Acoustic.Inactive,
        SoundEffect.Electronic.Moog("Testing"),
        SoundEffect.Vocal.Lieder()
        )

To process this list I can do this
  sounds.filterIsInstance<SoundEffect.Acoustic>().forEach { acoustic -> process(acoustic) }
  sounds.filterIsInstance<SoundEffect.Electronic>().forEach { electronic -> process(electronic) }
  sounds.filterIsInstance<SoundEffect.Vocal>().forEach { vocal -> process(vocal) }

What I would like to be able to code is this:-
sounds.multipleFilter {
    is SoundEffect.Acoustic -> forEach { acoustic -> process(acoustic) }
    is SoundEffect.Electronic -> forEach { electronic -> process(electronic) }
    is SoundEffect.Vocal -> forEach { vocal -> process(vocal) }
}

is this approach possible in Kotlin?
How could I specify the multipleFilter function?

A: Exactly this syntax won't work, branches with is ... are only allowed in when. But why not just a single forEach?
sounds.forEach {
    when(it) {
        is SoundEffect.Acoustic -> process(it)
        is SoundEffect.Electronic -> process(it)
        is SoundEffect.Vocal -> process(it)
    }
}

(it will be smart-cast in each branch and end up calling the correct overload)


text:
Q: tail recursion and fibonacci I was looking at this site: http://rosettacode.org/wiki/Fibonacci_sequence#JavaScript and saw this program:
function fib(n) {
  return function(n,a,b) {
    return n>0 ? arguments.callee(n-1,b,a+b) : a;
  }(n,0,1);
}

How does this work, what are those two arguments (a and b) help. I traced it and still can't figure out how this works

A: In the function(n,a,b), n serves as a countdown counter, and a b stores two consecutive Fibonacci numbers for the purpose of computing the next, so when n reaches 0, you have a as the n+1-th Fibonacci number (since the real Fibonacci has two 1s as the beginning).
E.g., n=4:
n  a  b
4  0  1
3  1  2
2  2  3
1  3  5
0  5  8

As you can see, the value of a and b always equal to the Fibonacci numbers. Also, this is very similar to Functional Programming (as the website stated Scheme programmers).

A: a and b are parameters into a newly defined anonymous function.
I would take a look at this page which is documentation about the arguments object.  From the documentation, arguments.callee, is a reference to the function you are currently in.  This has to be done because they are working in an anonymous function, so it really has no name (that they know of).
It seems as though they are recursively calling the function that they (anonymously) define to a depth of n.  Along the way, they are calculating the fib numbers, and they return the value a once a depth of n has been met.  The initial values passed into the function are (n,0,1)

A: As explained here, arguments.callee refers to the current function you are in.  Since the function you are in is anonymous, this is the only way to call the function and achieve recursion.
The specific function computes the Fibonacci sequence, by recursively calling in the inner function.

A: a and b represent the current number of the sequence and the next number of the sequence, starting from 0 and 1. n is a count-down timer that specifies which element of the fibonacci sequence will be returned (EG: n = 10 will return 55).
This function works by accepting an argument n which means it will calculate nth number of the sequence:
function fib(n) {

The code then defines a function that will calculate the next number in the sequence:
function(n,a,b) {
  return n>0 ? arguments.callee(n-1,b,a+b) : a;
}

Basically this anonymous function counts down n by one each time it is executing, while at the same time moving a and b to the next numbers in the sequence. If n is equal to 0 then the sequence is complete and the current number a is returned.
arguments.callee refers to the currently executing function, so that code just means to call back into itself with the new arguments. In other words, to begin the next iteration of the "loop".
Finally, by saying (n,0,1); the code is actually calling into fib with the parameters n,0,1. The return statement - which I left out of the above snippet - takes the return value of the anonymous function and returns it to the caller of fib.

That said, using recursion in this manner is inefficient for languages such as JavaScript that do not have tail call optimization. For large n you would be better off writing this using a standard looping construct instead of recursion.

A: I see a few problems that can lead to confusion. Short hand and tail optimization for recursive function pattern.
The problem might be in the short hand version of the code. Re-written for clarity below.

*

*acknowledging the anonymous function by giving it a name "recur"

*conditional (ternary) operator expanded.

Tail Optimization is used to tame the stack use of recursive functions by adding an accumulator part. This is a common pattern but takes away from the readability. That's the recur function.
A special note that performance is great compared to iterating in a loop.

function fib(n) {
    function recur(n, a, b) {
        if (n > 0) {
            return recur(n - 1, b, a + b);
        } else {
            return a;
        }
    }
    return recur(n, 0, 1);
}

With respect to the parameters, n is the iteration counter, a and b are the sequence parts of fibonacci.


text:
Q: Understanding node-mariasql example code I see the following code on the node-mariasql library -
var inspect = require('util').inspect;
var Client = require('mariasql');

var c = new Client();
c.connect({
  host: '127.0.0.1',
  user: 'foo',
  password: 'bar',
  db: 'mydb'
});

c.on('connect', function() {
   console.log('Client connected');
 })
 .on('error', function(err) {
   console.log('Client error: ' + err);
 })
 .on('close', function(hadError) {
   console.log('Client closed');
 });

var pq = c.prepare('SELECT * FROM users WHERE id = :id AND name = :name');

c.query(pq({ id: 1337, name: 'Frylock' }))
 .on('result', function(res) {
   res.on('row', function(row) {
     console.log('Result row: ' + inspect(row));
   })
   .on('error', function(err) {
     console.log('Result error: ' + inspect(err));
   })
   .on('end', function(info) {
     console.log('Result finished successfully');
   });
 })
 .on('end', function() {
   console.log('Done with all results');
 });

c.end();

The output for this has been specified as -
/* output:
    Client connected
    Query #1 row: [ 'first query' ]
    Query #1 finished successfully
    Query #2 was aborted
    Query #3 row: [ 'third query' ]
    Query #3 finished successfully
    Done with all queries
    Client closed
 */

To me the c.connect looks to be an asynchronous call. So then shouldn't the bottom part of the code be placed inside the c.on('connect') callback? Otherwise what is the guarantee that the connection would have already opened by the time I do c.query or c.prepare
The bottom part of the code.
var pq = c.prepare('SELECT * FROM users WHERE id = :id AND name = :name');

c.query(pq({
    id: 1337,
    name: 'Frylock'
}))
    .on('result', function (res) {
    res.on('row', function (row) {
        console.log('Result row: ' + inspect(row));
    })
        .on('error', function (err) {
        console.log('Result error: ' + inspect(err));
    })
        .on('end', function (info) {
        console.log('Result finished successfully');
    });
})
    .on('end', function () {
    console.log('Done with all results');
});

c.end();

A: mysql protocol requires you to wait for previous command to complete before sending next one, and because of this most clients have some kind of internal queue and move to next command in the queue automatically. This code for example does not execute 3 queries in parallel:
c.query('select sleep(1)');
c.query('select sleep(2)');
c.query('select 1', console.log);

Instead, it'll output "select 1" result after 3 seconds. So the answer to "what is the guarantee that the connection would have already opened" is "client design guarantees this to you"


text:
Q: Trouble in implementing link list sorting in c# I am having trouble implementing a sort algo (merge) for singly list as defined below
My mergesort method always gives me null..I am not able to figure out what is wrong
Can you guys help me out?
Node class
public class Node
        {
           private int data;
           private  Node next;
    }

Linked List class
public class SSL
        {
            private Node head;
    }

My merge sort code
public static void MergeSort(SSL a)
        {
            SSL x = new SSL();
            SSL y = new SSL();
            if (a.Head == null || a.Head.Next == null) // base case if list has 0 or 1 element
                return;
            AlternateSplitting(a, x, y);
            MergeSort(x);
            MergeSort(y);
            a = SortedMerge(x, y);
        }

I implemented following helper methods to implement merge sort
AlternateSplitting: This method will split the list into 2 lists
public static void AlternateSplitting(SSL src, SSL odd, SSL even)
        {

            while (src.Head != null)
            {
                MoveNode(odd, src);
                if (src.Head != null)
                    MoveNode(even, src);
            }

        } // end of AlternateSplitting

This method will merge the 2 list and return a new list
public static SSL SortedMerge(SSL a, SSL b)
        {
            SSL c = new SSL();
            if (a.Head == null)
                return b;
            else
                if (b.Head == null)
                    return a;
                else
                {
                    bool flagA = false;
                    bool flagB = false;
                    Node currentA = new Node();
                    Node currentB = new Node();

                    while (!flagA && !flagB)
                    {
                        currentA = a.Head;
                        currentB = b.Head;
                        if (currentA.Data < currentB.Data)
                        {
                            MoveNodeToEnd(a, c);
                            currentA = a.Head;
                            if (currentA== null)
                                flagA = true;
                        }
                        else
                            if (currentA.Data > currentB.Data)
                            {
                                MoveNodeToEnd(b, c);
                                currentB = b.Head;
                                if (currentB== null)
                                    flagB = true;

                            }
                    } // end of while

                    if (flagA)
                    {

                        while (currentB != null)
                        {
                            MoveNodeToEnd(b, c);
                            currentB = b.Head;
                        }

                    }
                    else
                        if(flagB)
                        {

                            while (currentA != null)
                            {
                                MoveNodeToEnd(a, c);
                                currentA = a.Head;
                            }

                        }
                    return c;

                } // end of outer else

        } // end of function sorted merge

A:
I am not able to figure out what is
  wrong Can you guys help me out?

Find a bug and you fix it for a day. Teach how to find bugs and believe me, it takes a lifetime to fix the bugs. :-)
Your fundamental problem is not that the algorithm is wrong -- though, since it gives incorect results, it certainly is wrong. But that's not the fundamental problem. The fundamental problem is that you don't know how to figure out where a program goes wrong. Fix that problem first! Learn how to debug programs.
Being able to spot the defect in a program is an acquired skill like any other -- you've got to learn the basics and then practice for hundreds of hours. So learn the basics.
Start by becoming familiar with the basic functions of your debugger. Make sure that you can step through programs, set breakpoints, examine local variables, and so on.
Then write yourself some debugging tools. They can be slow -- you're only going to use them when debugging. You don't want your debugging tools in the production version of your code.
The first debugging tool I would write is a method that takes a particular Node and produces a comma-separated list of the integers that are in the list starting from that node. So you'd say DumpNode(currentB) and what would come back is, say "{10,20,50,30}".  Obviously doing the same for SSL is trivial if you can do it for nodes.
I would also write tools that do things like count nodes in a list, tell you whether a given list is already sorted, and so on.
Now you have something you can type into the watch window to more easily observe the changes to your data structures as they flow by. (There are ways to make the debugger do this rendering automatically, but we're discussing the basics here, so let's keep it simple.)
That will help you understand the flow of data through the program more easily. And that might be enough to find the problem. But maybe not. The best bugs are the ones that identify themselves to you, by waving a big red flag that says "there's a bug over here".  The tool that turns hard-to-find bugs into self-identifying bugs is the debug assertion.
When you're writing your algorithm, think "what must be true?" at various points. For example, before AlternateSplitting runs, suppose the list has 10 items. When it is done running, the two resulting lists had better have 5 items each. If they don't, if they have 10 items each or 0 items each or one has 3 and the other has 7, clearly you have a bug somewhere in there. So start writing debug-only code:
public static void AlternateSplitting(SSL src, SSL odd, SSL even)
{
#if DEBUG
  int srcCount = CountList(src);
#endif
  while (src.Head != null) { blah blah blah }
#if DEBUG
  int oddCount = CountList(odd);
  int evenCount = CountList(even);
  Debug.Assert(CountList(src) == 0);
  Debug.Assert(oddCount + evenCount == srcCount);
  Debug.Assert(oddCount == evenCount || oddCount == evenCount + 1);
#endif
}

Now AlternateSplitting will do work for you in the debug build to detect bugs in itself. If your bug is because the split is not working out correctly, you'll know immediately when you run it.
Do the same thing to the list merging algorithm -- figure out every point where "I know that X must be true at this point", and then write a Debug.Assert(X) at that point. Then run your test cases. If you have a bug, then the program will tell you and the debugger will take you right to it.
Good luck!


text:
Q: Finding the perfect database collation
Possible Duplicate:
UTF-8: General? Bin? Unicode?

I'm running some tests on finding the right collation for the right table. Is it correct to assume that if a table were to contain user submitted data (profiles info, etc.) or authentication data (hashes, etc.) a collation of utf8_bin would work well while all the rest can be in utf8_general_ci which is faster?
Or should everything just be the same collation?


text:
Q: ordering items in a list but keep getting AttributeError I am trying to organise all the posts in this list that I've created in order by descending 'created'.
This is my function:
def posts_search_by_following(request, user_username):
    start = int(request.GET.get('start') or 0)
    end = int(request.GET.get('end') or (start + 9))

    profile = get_object_or_404(User, username=user_username)
    following_users = profile.get_following()
    posts = list()[start:end]
    for person in following_users:
        posts += Post.objects.filter(creator=person).order_by('-created')

    return JsonResponse(
        {'posts': [post.serialize() for post in posts]}
    )

As it is right now, it is only ordering posts by their 'created' field per person. So when the whole list is returned everything isn't all in order. However if I try to move .order_by('created') anywhere else:
{'posts': [post.serialize() for post in posts].order_by('created')}

it will give me an Attribute error like this:
AttributeError at /posts/Moderator/following/search
'list' object has no attribute 'order_by'

How can I get the total number of posts and then order them accordingly?

A: The reason that this does not work is because your posts is a list, not a QuerySet, and a list has no .order_by(…) [Django-doc] method. You can query all the Posts of all the persons with a single query:
def posts_search_by_following(request, user_username):
    start = int(request.GET.get('start') or 0)
    end = int(request.GET.get('end') or (start + 9))

    profile = get_object_or_404(User, username=user_username)
    following_users = profile.get_following()
    posts = Post.objects.filter(
        creator__in=following_users
    ).order_by('-created')[start:end]

    return JsonResponse(
        {'posts': [post.serialize() for post in posts]}
    )


text:
Q: ACF get sub_field of repeater FROM a parent page I try to implant this
- Page A0 (images + texts)
-- Page A1
-- Page A1
---Page A2

In page A1 & A2, I need to retrieves galerie and texts from a group of field.
If I use a normal field, not in a goup, I achieve this... But I need to stay in a group field.
 <?php
    $post_ID = get_the_ID();
    $parentpost_id = wp_get_post_parent_id( $post_ID );
    $images_images = get_sub_field( "images", $parentpost_id ); //use parents-post field: "broschuren-download"
     ?>

<div class="hero__image-wrapper <?php if (count ($images_images) > 1) { echo "heroslide" ;} ?> ">
       <?php if ( $images_images ) :  ?>
           <?php foreach ( $images_images as $images_image ): ?>
               <img class="hero__image fit-cover" src="<?php echo $images_image['sizes']['large']; ?>" alt="<?php echo $images_image['alt']; ?>" />
           <?php endforeach; ?>
       <?php endif; ?>

A: The get_sub_field() function only works within a have_rows() loop that you run on the parent field. If you still want to use get_sub_field(), you would have to do something like this:
<?php
$post_ID = get_the_ID();
$parentpost_id = wp_get_post_parent_id( $post_ID );

if( have_rows('broschuren-download', $parentpost_id) ): while( have_rows('broschuren-download', $parentpost_id) ): the_row();

$images_images = get_sub_field('images');

if ( $images_images ):
?>
    <div class="hero__image-wrapper <?php if (count ($images_images) > 1) { echo 'heroslide'; } ?>">
        <?php foreach( $images_images as $images_image ): ?>
        <img class="hero__image fit-cover" src="<?php echo $images_image['sizes']['large']; ?>" alt="<?php echo $images_image['alt']; ?>" />
        <?php endforeach; ?>

<?php
endif;
endwhile; endif;
?>


text:
Q: I am having trouble with this computer science program DigitMath. I have finished it but when I ran it, it printed out 0.0 I am trying to write a program that will take an integer and add up each of the number's digits, count the number of digits in the number, and then average these two numbers.
I must use a while loop and % to access each of the individual digits.  Use / to reduce the number so that you can average all of the digits.
234 has a digit average of 3.0,
10000 has a digit average of 0.2,
111 has a digit average of 1.0
Here is my code:
import static java.lang.System.*;

        public class DigitMath
        {
           private static int countDigits( int number )
        {
            int count = 0;
            while( number > 0 )
            {
               count++;
               number = number / 10;
            }
            return count;
        }
        private static int sumDigits( int number )
        {
            double total = 0;
            while( number > 0 )
            {
               total = total + number % 10;
               number = number / 10;
            }
            return number;
        }

        public static double averageDigits( int number )
        {
            if( number > 0 )
                  return sumDigits( number ) / countDigits( number );
          return 0;
        }
    }

    // other code

    import static java.lang.System.*;

    public class Lab09e
    {
        public static void main( String args[] )
        {
            out.println(DigitMath.averageDigits(234));
       }
    }

A: It looks like you are starting with programming so a helpful tip is try to debug by printing intermediate results. Check if your sum and count work correctly, this will help you tackle the problem in smaller segments.
In your code, one very obvious mistake is that when you calculate the average you are dividing an int with an int, which will result in an int. For instance, 4/5 will be 0 and not 0.8 as you would want. Read up on this link or refer to this question to understand this better.
You can solve this by first casting the operands to double or multiplying by 1.0.
Hope this helps!

A: The issue is that you are returning number in the sumDigits method instead of total.
When you are returning number you are actually returning 0 which then causes the averageDigits to return 0/3 which results in 0.0.
To fix this problem:

*

*Return total instead of number, which is 0 at the end of the method's execution.

*Also, change the return type of the methods countDigits() and sumDigits() to double instead of an int. Because you are calculating averages you should make sure you that the return expression doing the division will return a double. Dividing two ints will return a double, however, if you divide two doubles it will return a double.
Here is the fixed code:
class DigitMath
{
    private static double countDigits( int number )
    {
        double count = 0.0;
        while( number > 0 )
        {
            count++;
            number = number / 10;
        }
        return count;
    }
    private static double sumDigits( int number )
        {
            double total = 0;
            while( number > 0 )
            {
                total = total + number % 10;
                number = number / 10;
            }
            return total;
        }

    public static double averageDigits( int number )
        {
            if( number > 0 ){
                return sumDigits( number ) / countDigits( number );
            }
          return 0.0;
        }
}

public class Lab09e
{
    public static void main( String args[] )
    {
        System.out.println(DigitMath.averageDigits(234));
    }
}

I hope that this answer helped you and if you have any further questions please feel free to leave a comment below.


text:
Q: Splitting a number in half but fixing when second half starts with 0 I have a large number that I want to split in half. For this example, let's use: 5639445604728832
When it is split in half it comes out like this:
56394456
04728832

Obviously, the second number isn't a number anymore.
I have the following code, but I am trying to make it so it will add the 0's to the end of the first number until the second number is officially a real number. Could anyone help me solve this?
function my_number_split($number)
{
    $half = (int) ( (strlen($number) / 2) ); // cast to int incase str length is odd
    $left = substr($number, 0, $half);
    $right = substr($number, $half);

    echo $left."
".$right;
}

A: Rewriting your function like this would do the trick.
function my_number_split($number)
{
    $half = ceil( (strlen($number) / 2) );
    while (0 == substr($number, $half, 1) && $half <= strlen($number) ) $half++;
    $left = substr($number, 0, $half);
    $right = substr($number, $half);

    echo $left."
".$right;
}

A: Simple loop should do it.
Something like this -
function my_number_split($number)
{
    /* Logic to traverse ahead till a 0 is not found. */
    $str_len = strlen($number);
    $half_index = $str_len/2;
    while($half_index < $str_len){
        if($number[$half_index] != "0"){
            break;
        }
        $half_index++;
    }
    //Slicing string.
    $left = substr($number, 0, $half_index);
    $right = substr($number, $half_index);
    echo $left."
".$right;
}
my_number_split("5639445604728832");

/*
OUTPUT -
563944560
4728832
*/

A: It's probably an inefficient way, but for the challenge:
if (preg_match('~\A(?<n1>.?(?:.(?=.*(.(?(2)\2)\z)))+0*)(?<n2>.+)~', $number, $m))
    echo $m['n1'] . "\n" . $m['n2'];


text:
Q: Android tvdpi layout This is driving me crazy !
I want the Nexus 7 and the other normal 7" tablets to use different layouts.
I tried multiple combinations but they always end up using the same layout.
Ex:

*

*layout-sw600dp-tvdpi

*layout-sw600dp-mdpi

With this example , both the 1024x600 tablet and the Nexus 7 end up using the tvdpi layout.
That's strange since the 1024x600 is not a tvdpi.
So how can I have separate layouts ?

A: I think that 1024x600 is hdpi. And if you replace mdpi with hdpi everything will be fine.
Android can choose layout-sw600dp-tvdpi instead of layout-sw600dp-mdpi, because tvdpi is more similar with hdpi.


text:
Q: Simulate browsing in an iFrame using JavaScript I'm looking for a test automation framework I can embed in an iFrame, to describe and simulate browsing, which will probably be translate to JQuery-simulate events.

A: What you're trying to do is difficult and uncommon, and for good reason. Firstly let's take the technical aspect.
Dealing with your chosen solution:
I've not managed to come up with any frameworks that will do what you want, but you may want to look at the accepted answer for How to communicate between iframe and the parent site? - what you're trying to do operates in the opposite direction, but the principle is the same. Essentially there is a good chance that you will not be able to achieve what you want to do unless you control both the outer and inner websites, and even then, it won't work in all browsers.
Finding a better way:
So now that the technical side has been tackled, here's the real meat of the matter - are you really sure this is what you want to be doing? A number of scenarios with different solutions:

*

*You're guiding someone through using a service you control:
Create a guided copy of the page, with the interactions built in - then embed this.

*You're guiding someone through using a third party service:
Record a video, you can even include a voiceover and closed captions to explain why the user must do certain things, and which parts are optional. This would also work well with the above scenario.

*You're streamlining an interaction with a service you control:
This gives you options - you almost certainly don't want to embed the page, but want to work with the backend, either directly or through a RESTful inteface.

*You're streamlining an interaction with a third party service:
The RESTful interface is your friend, if the service has one, if not, see if they have any other sort of API - if they don't contact them and see if you can work something out.
So what is the issue you are actually trying to solve?
Closing comments
When faced with a technical problem it's often tempting to accept the first solution you come up with, but be aware, it's probably not the best. This is not to say that you should spend endless time deliberating over what to do for each and every problem, but you should probably spend at least another couple of minutes considering the problem before choosing what to do, and if you get stuck, try something different.
It may well be that you can't think of any other solution that could possibly solve your problem, and you might be right, but if you can't get it to work, and you come looking for help, please let people know what the problem is that you're trying to solve, because as I have found, there is always someone smarter; there is always someone who, if they squint hard enough, will have seen something like your problem before; there is always a better way to do it, it's just that no-one else may have discovered it yet.


text:
Q: Some doubts about 2 different JSON formats Maybe this is a trivial question.
I am looking into a JSON file I found something like this:
{
    localization_id: 2,
    local_user_id: 33,
    is_active: true,
    registration_date: 2017-09-13 12:05:21
}

When looking into another JSON file otherwise I found something like this:
{
    "cod": "200",
    "message": 0.0036,
    "cnt": 40,
}

Why in the second one the field name and some value are into the ""? Is it irrelevant or have a meaning?


text:
Q: Методология БЭМ. Правильно ли я понимаю?

Каталог

Любителям БЭМ-методологии, правильно ли я понимаю БЭМ?
Есть общий класс c-catalog.
Все остальные вложенные классы должны быть с префиксом с-catalog?
А если как в мое примере, появился c-catalog__products, то входящие в него элементы должны быть с-catalog__product или с-catalog__products__item?
И что если в разметке появляются элементы, которые никак не влияют на логику и структуры и нужны просто для оформления, типа .wrapper.
Это допускается, или его надо тоже именовать через с-catalog?
Спасибо

A:
Есть общий класс c-catalog. Все остальные вложенные классы должны быть
  с префиксом с-catalog?

Так как c-catalog является блоком, а блок в БЭМ задаёт пространство имён, то его дочерние элементы, как правило, должны содержать префикс данного корневого блока.
Это правило именования не распространяется на универсальные блоки (см. ниже)

А если как в мое примере, появился c-catalog__products, то входящие в
  него элементы должны быть с-catalog__product или
  с-catalog__products__item?

c-catalog__products в данном случае является элементом блока c-catalog, а элементы НЕ задают пространство имён в БЭМ. К тому же все дочерние элементы c-catalog__products так же являются дочерними элементами основного блока c-catalog и должны содержать его префикс c-catalog. Т.е. ответ на вопрос - c-catalog__product.
Подробнее о том, почему не рекомендуют использовать второй вариант с-catalog__products__item можно прочитать здесь.

И что если в разметке появляются элементы, которые никак не влияют на
  логику и структуры и нужны просто для оформления, типа .wrapper.
Это допускается, или его надо тоже именовать через с-catalog?

Допускается, в данном случае wrapper является универсальным блоком.


text:
Q: cakephp - how to change pagination condition? on several places in same controller i have code like:
$publications = $this->paginate('Publication', $conditions);

...where $conditions is array of conditions, which fields to select and how (using LIKE in mysql).
every one of them have different "Order by" statement.
how can i achieve that, and define different "order by" part of sql?
UPDATE (2011-03-11): this is part how i defined pagination:
$this->paginate = array(
        'limit' => 1,
        'fields' => array('`Publication`.*, PublicationNumeration.*, Collection.*, Publisher.*, Publication.title as PublicationTitle'),
        'joins' => array( array('table' => 'publication_numerations', 'alias' => 'PublicationNumeration', 'type' => 'LEFT', 'conditions' => array( 'Publication.id = PublicationNumeration.publication_id' ) ) )
        , 'order' => array('PublicationTitle desc')
      );

            $publications = $this->paginate('Publication', $conditions);
            $this->set(compact('publications', 'urlArgs'));

part with 'limit' works, but 'order' does not works, and does not show in debug mode at all.

A: You can override the pagination function for each time that you implement it in each different action. For example:
function list_recipes() {
    $this->paginate = array(
        'limit' => 10,
        'order' => array(
            'Recipe.title' => 'asc'
        )
    );
    $data = $this->paginate('Recipe');
    $this->set(compact('data'));
}

In your case, you'd probably want to reuse your $conditions array but alter the value of 'order' for each different implementation.
Further Reference: Pagination doc

A: I used this idea to create a custom selection of items per page.
My default pagination:
var $paginate = array( 'order' => array('User.id' => 'asc') );

I added this to my controller to change the limit to 25 (also added 1 for 5 and 10 just to see how it would go and changed the limit value accordingly):
function list25() {
//fetches with different limit than default

    $this->paginate = array(
        'limit' => 25,
        'order' => array(
            'User.id' => 'asc'
        )
    );
    $data = $this->paginate('User');
    $this->set('users', $data);
}

Then, in my main view (index.ctp) I added this at the bottom of the data listing:

<?php echo "  Show:";
      echo $html->link(' 5', array('controller'=>'users', 'action' => 'list5'));
      echo $html->link(' 10', array('controller'=>'users', 'action' => 'list10'));
      echo $html->link(' 25', array('controller'=>'users', 'action' => 'list25'));
    ?>

<?php  echo $paginator->numbers(); ?>

...which shows the following text at the bottom of the display:  Show: 5 10 25
The numbers, when clicked, are linked to the controller action and thus resets the limit (and refreshes the page with the new limit set).
Perhaps there is a better way to achieve the same functionality as I had to create a view for each option:  list5.ctp, list10.ctp and list25.ctp.  Anyway, it provides the user a chance to choose how much data they want to see on a page.  Comments?
....noob cakePHP user...

A: Try this:
        echo $this->Paginator->link('5',array('limit' => '5'))
        echo $this->Paginator->link('10',array('limit' => '10'));
        echo $this->Paginator->link('10',array('limit' => '25'));


text:
Q: How do I add an embedded sprite to DOM in javascript <!DOCTYPE html>
<html>
  <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
      svg{ display: inline-block; }
    </style>
    <script src="my.js"></script>
  </head>
  <body>
    <embed src="sprites.svg" type="image/svg+xml" width="0" height="0" />
    <svg id="MAIN" xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 320 208" shape-rendering="crispEdges">
      <path d="M0 0h320v208h-320v-208z" fill="#000"/> <!-- Fill screen  -->
      <svg id="sprite1"><use xlink:href="sprites.svg#SP1" x="64" y="128"</use></svg>
      <svg id="sprite2"><use xlink:href="sprites.svg#SP2" x="64" y="128"</use></svg>
      <svg id="sprite3"><use xlink:href="sprites.svg#SP3" x="64" y="128"</use></svg>
    </svg>
    <script>
      start( 1 ); // Call Func in my.js
    </script>
  </body>
</html>

I have hundreds of sprites in "sprites.svg". How do I, in javascript add the sprites I want to the DOM via javascript. I want them added so that they are just like sprite1 to sprite3 in the example html page above, thanks Keith

A: Worked it out, not as complex as I thought.
var svgURI  = "http://www.w3.org/2000/svg";
var mainSVG = document.getElementById( "MAIN" ); // my main SVG
var svg     = document.createElementNS( svgURI, 'svg' );
svg.id      = "sprite4";
svg.innerHTML = "<use xlink:href='sprites.svg#SP4'></use>";
mainSVG.appendChild( svg );

Thanks to every one who tried to help


text:
Q: NumberFormatter() - pad with a specific number of spaces possible? I am trying to use NumberFormatter() to create a string representation of CGFloats. Ideally, I would like to create a signed string like transforming a value of
10.1 -> "  10.1" and
-10.1 -> "- 10.1", the integer part being padded with spaces.
This is the closest I have gotten, but it pads the integer portion with "0" so I get
10.1 -> " 010.1" and
-10.1 to "-010.1"
If I don't use .minimumIntegerDigits there is no padding.
I'm using a monospaced font to display the values and I'm trying to make sure they don't get jiggly as they change, and I was just hoping there would be some way to use a space in place of the 0 but otherwise exactly how .minimumIntegerDigits works.
extension CGFloat {
   func signedPaddedString() -> String {
      let formatter = NumberFormatter()
      formatter.positivePrefix = " "
      formatter.minimumIntegerDigits = 3
      formatter.paddingCharacter = " "
      formatter.minimumFractionDigits = 1
      formatter.maximumFractionDigits = 1
      return formatter.string(from: self as NSNumber)!
   }
}

A: You can achieve this by setting the positiveFormat and negativeFormat
properties, which are format patterns according to the Unicode Technical Standard #35:
extension FloatingPoint {
    func signedPaddedString() -> String {
        let formatter = NumberFormatter()
        formatter.positiveFormat = " * ##0.0"
        formatter.negativeFormat = "-* ##0.0"
        return formatter.string(for: self)!
    }
}

print((10.1).signedPaddedString())    // "  10.1"
print((-10.1).signedPaddedString())   // "- 10.1"
print((123.45).signedPaddedString())  // " 123.4"
print((-123.45).signedPaddedString()) // "-123.4"
print((0).signedPaddedString())       // "   0.0"
print((-1).signedPaddedString())      // "-  1.0"

If you want to suppress localization (e.g. in countries using decimal comma) then add
formatter.locale = Locale(identifier: "en_US_POSIX")


text:
Q: python : when a number is reversed with zero as ending. Does not display zero in output when a number is reversed with zero as ending. Zero is not printed in the output. ex: 11120 but output=2111. Please find the attached image
code:
     code i have written for reverse of the number
enter image description here

A: Most integer types in virtually every programming language do not show leading zeroes. If you want to reverse it with zeroes, convert to a string first. If you want leading zeroes you need to specify how many places you want to show.
Internally 11120 is stored as 00000000000000000010101101110000, it's just shown as 11120 for readability.

A: original_int = 21110
forward_str = str(original_int)
reverse_str = ''
for char in forward_str:
    reverse_str = char + reverse_str
print(reverse_str)

Result is 01112 (a string)


text:
Q: Grep vars from a file with ansible to use later in a task with a for loop I am relatively new to ansible.
I have a parameters.yml with something like this:
parameters:
  stuff: bullshit
  otherstuff: otherbullshit
  domain_locale: domain.locale.test
  domain_differentlocale1: domain.differentlocale1.test
  domain_differentlocale2: domain.differentlocale2.test
  domain_differentlocale3: domain.differentlocale3.test
  uninteresting_stuff: uninteresting_bullshit

This file is in another directory, but I could also symlink it to be in defaults/main.yml. Doesn't matter.
What I would like to accomplish is grep somehow within an ansible task these domain.*.test values and use it as vars in another task with ansible. This other task would be to write it directly after 127.0.0.1 localhost in the same line in the /etc/hosts.
I am not even sure which of the modules to use in ansible. include_vars has no additional grep as I see it. set_fact does not read from a different file(can I combine it with a shell command? how?). lineinfile does not have a source and dest, so it is also limited to one file.
I also thought this post would help me: Ansible read multiple variables with same name from vars_file
but it does not need the grep part, I need.

A: Here you go:
---
- hosts: localhost
  gather_facts: no
  vars:
    parameters:
      stuff: bullshit
      otherstuff: otherbullshit
      domain_locale: domain.locale.test
      domain_differentlocale1: domain.differentlocale1.test
      domain_differentlocale2: domain.differentlocale2.test
      domain_differentlocale3: domain.differentlocale3.test
      uninteresting_stuff: uninteresting_bullshit
  tasks:
    - lineinfile:
        dest: /tmp/test.txt
        regexp: ^127.0.0.1
        line: "127.0.0.1 localhost {{ parameters.values() | select('match','domain.*test') | list | join(' ') }}"


text:
Q: Difference between 'plugin' section and 'dependency' section in pom. Which one to use when? While searching for maven-check-style plugin information online I found that it can be added both as a <dependency> tag like this:
<dependency>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-checkstyle-plugin</artifactId>
    <version>2.5</version>
</dependency>

and also under <plugins> tag like this:
<reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <configuration>
                    <configLocation>config/sun_checks.xml</configLocation>
                </configuration>
            </plugin>
        </plugins>
</reporting>

I would like to know the difference between each and which one to use when. Please guide.

A: As far as I know, plugins are also artifacts, so they can be added as a dependency to a project. However adding plugin artifact as a dependency, doesnt bind its execution to any phase of maven build, therefore it cannot be executed.

A: Here you can find some answers:
https://www.quora.com/In-Maven-what-is-the-difference-between-dependency-and-plugins
"A plugin is an extension to Maven, something used to produce your artifact (maven-jar-plugin for an example, is used to, you guess it, make a jar out of your compiled classes and resources).
A dependency is a library that is needed by the application you are building, at compile and/or test and/or runtime time."Olivier Demeijer


text:
Q: slave replication stopped working This morning my slave stopped working..
Slave_IO_State: Waiting for master to send event
Slave_IO_Running: Yes
Slave_SQL_Running: No

Last_SQL_Error: Could not execute Update_rows event on table
  dynaccount.account; Can't find record in 'account', Error_code: 1032;
  handler error HA_ERR_KEY_NOT_FOUND; the event's master log
  mysql-bin.000025, end_log_pos 802331975

Restoring slave
- Master
# mysqldump -u root -pxxx --single-transaction --hex-blob --routines --triggers --events --quick --add-drop-database --extended-insert --databases my_db | gzip > /root/dump.sql.gz
# scp -o 'StrictHostKeyChecking no' /root/dump.sql.gz root@remote.com:/root

- Slave
# mysql -u root_slave -pxxx -e "stop slave; reset master"

# pv /root/dump.sql.gz | gunzip | mysql -u root_slave -pxxx
# mysql -u root_slave -pxxx -e "start slave"
# mysql -u root_slave -pxxx -e "show slave status\G"

After restoring the slave I keep getting the same error?!

A: Add --master-data to the mysqldump. That way the change of slave position to where you did the mysqldump gets executed when you load it.


text:
Q: Python error when installing module to connect couchbase I'm using CentOS 6.3, Python 2.6 and Couchbase.
I downloaded couchbase1.0.0 package for Python from and follow the guide from this https://pypi.python.org/pypi/couchbase
But, when I run the build_ext command, I got this error
/usr/bin/ld: cannot find -lcouchbase
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1

I tried to use python setup.py install command, I got the error above, too.
I changed into couchbase1.0.0 directory before running commands.
How can I solve this problem?

A: Linker is missing couchbase library, did you install couchbase package and all -devel packages for it ? by packages I mean system packages, not python packages.