text:
Q: keepRunning PhoneGap/Cordova Anyone can explain me how keepRunning works in the config.xml for Android.
I mean, I don't want to know how to write the instruction but how does it work, how does it affect the execution of the Android app ? Does it create an Service in background ?
If anyone can find the source where we can see how does it work, that will be great
Thanks.
Edit : I try to analyze the generated code, analyze the RAM, services and processus in the setting of Android. And my conclusion is..... that do nothing.
If you try to make a app which track the user with GPS, dont use Cordova. To track the user correctly, you need to make a Service with the START_STICKY option. So, it's in native code. you lost the interest of the CrossPlatform because you have to recode the service for all platforms and in my opinion, the communication between Native Service and Cordova App is not easy.
In conlusion, if you use Cordova, you have to know you can't use the power of all native, you have to make choise :
- easy dev (subjective) and crossplaform (really crossplatform ?)
and
- Native dev with its power and no compatibility problems but you have to make one app for one platform

A: I'm not a JS/Cordova developer, I'm an Android developer. Once I worked on a Cordova plugin, faced some issues and did some investigations on the subject.
General purpose of keepRunning flag is to indicate if JS timers should be stopped when the app is paused (goes to background). Answering your question: no, it doesn't create any new Service. Existing design is quite plain in this regard.
The keepRunning flag is defined in CordovaActivity.java as follows:
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;

Its main purpose is to disable JS timers when Cordova app is paused, in CordovaWebView.java:
public void handlePause(boolean keepRunning)
{
    LOG.d(TAG, "Handle the pause");
    // Send pause event to JavaScript
    this.loadUrl("javascript:try{cordova.fireDocumentEvent('pause');}catch(e){console.log('exception firing pause event from native');};");

    // Forward to plugins
    if (this.pluginManager != null) {
        this.pluginManager.onPause(keepRunning);
    }

    // If app doesn't want to run in background
    if (!keepRunning) {
        // Pause JavaScript timers (including setInterval)
        this.pauseTimers();
    }
    paused = true;

}

Note that plugins are also notified via PluginManager, so in theory they can handle app paused events, to stop (or not) their activity in background, depending on keepRunning flag.
In my case I had an issue/bug when keepRunning was true, but JS timers were stopped anyway. It happened because there is additional functionality related to that flag, in CordovaActivity.java:
/**
 * Launch an activity for which you would like a result when it finished. When this activity exits,
 * your onActivityResult() method will be called.
 *
 * @param command           The command object
 * @param intent            The intent to start
 * @param requestCode       The request code that is passed to callback to identify the activity
 */
public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
    this.activityResultCallback = command;
    this.activityResultKeepRunning = this.keepRunning;

    // If multitasking turned on, then disable it for activities that return results
    if (command != null) {
        this.keepRunning = false;
    }

    // Start activity
    super.startActivityForResult(intent, requestCode);
}

When Cordova app launches another Android activity, main Cordova activity (screen with WebView) goes to background and is therefore paused. In my case it was made via Google Maps plugin which started GM screen over Cordova app.
The code above turns off keepRunning flag, and it means that JS timers are stopped anyway when the called activity appears (in CordovaActivity.onPause method) regardless keepRunning is true or false!
It looks like a kind of trick implemented for some unclear (and not documented) purpose, I do not know its context. In my case it caused a bug, and I just removed keepRunning handling in startActivityForResult, recompiled Cordova and it worked OK.
ADDED: About using a Service for GPS - you are quite right, I agree. As an Android developer with relevant (GPS) experience I can say that a right approach (and possible the only acceptable) is to use a service for that. As far as I know Cordova doesn't provide any functionality for it, so I think it should be made via a plugin. I mean you can write native Android code for GPS functionality (implemented as a Service) and access it from JS code. I believe it is a common solution in Cordova for such cases.

A: Perfect answer, helped me a lot! I was searching for the solution to the problem for 2 days now.
In my case I'm currently developing a cordova plugin for login purposes. For the login I use an external form which I load in a webview. For two days now I was struggling with the fact that the "Password forgotten" link and every other link on the page I loaded was working, but I wasn't able to submit my form. Only when I hit the back button and through this finished the intent holding the webview, it did submit and proceed.
Turns out that the keepRunning handling was the only problem here. In the end I replaced: `
cordova.startActivityForResult(this, intent, 0);

by:
cordova.setActivityResultCallback(this);
cordova.getActivity().startActivityForResult(intent, 0);

which basically fulfills the whole job Cordova's startActivityForResult would do The only thing that's left out is the whole keepRunninghandling which messed up my plugin in the first place.
Thanks again, Mixaz!


text:
Q: How iterate through all properties of different classes in Swift? Let's say I have one parent class called Car with some properties and one method which actually does nothing.
class Car {
    var brandName : String
    var yearOfCreation : Int
    var color : String
    var numberOfDoors : Int

    func manipulateWithCar() {
    }

    init(brandName : String, yearOfCreation : Int, color : String, numberOfDoors : Int) {
        self.brandName = brandName
        self.yearOfCreation = yearOfCreation
        self.color = color
        self.numberOfDoors = numberOfDoors
    }
}

And I have two child classes called SportCar and TankerCar. They have their unique properties and also the method from parent class is overridden and now it does something.
class SportCar : Car {
    var turbo : Bool
    var nitrousOxideEngine : Bool

    override func manipulateWithCar() {
        print("Putting turbo on your car...")
        turbo = true
    }

    init(brandName: String, yearOfCreation: Int, color: String, numberOfDoors: Int, turbo : Bool, nitrousOxideEngine : Bool) {
        self.turbo = turbo
        self.nitrousOxideEngine = nitrousOxideEngine
        super.init(brandName: brandName, yearOfCreation: yearOfCreation, color: color, numberOfDoors: numberOfDoors)
    }
}

And also there is one enum for the method. This is not important but you just want to keep it as in the homework.
enum TankerForm {
    case cilindrical
    case quadratic
}

class TankerCar : Car{
    var tankerFilledSize : Int
    var tankerForm : TankerForm

    init(brandName : String, yearOfCreation : Int,
         color : String, numberOfDoors : Int, tankerVolum : Int, tankerForm : TankerForm) {
        self.tankerForm = tankerForm
        self.tankerFilledSize = tankerVolum
        super.init(brandName: brandName, yearOfCreation: yearOfCreation, color: color, numberOfDoors: numberOfDoors)
    }

    override func manipulateWithCar() {
        print("Loading 200 gallon of oil")
        tankerFilledSize = 200
    }
}

Creating some objects...
var kia = Car(brandName: "Rio", yearOfCreation: 2015, color: "Green",
numberOfDoors: 4)

var toyota = Car(brandName: "Corolla", yearOfCreation: 2015, color:
"Red", numberOfDoors: 4)

var lamborgini = SportCar(brandName: "Aventador", yearOfCreation: 2018,
color: "Black", numberOfDoors: 2, turbo: false, nitrousOxideEngine:
false)

var mazeratti = SportCar(brandName: "Ghibli", yearOfCreation: 2017,
color: "Red", numberOfDoors: 4, turbo: true, nitrousOxideEngine: false)

var kamaz = TankerCar(brandName: "Kamaz", yearOfCreation: 2007, color:
"Yellow", numberOfDoors: 2, tankerVolum: 0, tankerForm: .cilindrical)

var belaz = TankerCar(brandName: "Belaz", yearOfCreation: 2003, color:
"White", numberOfDoors: 2, tankerVolum: 0, tankerForm: .quadratic)

Creating arrays with objects...
var carrsArray : [Car] = [kia, toyota]
var sportCarsArray : [SportCar] = [lamborgini, mazeratti]
var tankerCarsArray : [TankerCar] = [kamaz, belaz]

And printing all the properties for Car class objects using for loop...
for value in carrsArray {
    print("This car is \(value.brandName)")
    print("The color is \(value.color)")
    print("The car has \(value.numberOfDoors) doors")
    print("The year of creation is \(value.yearOfCreation)")
    print(" ")
}

Printing all the properties for SportCar class objects using for loop...
for value in sportCarsArray {
    print("This car is \(value.brandName)")
    print("The color is \(value.color)")
    print("The car has \(value.numberOfDoors) doors")
    print("The year of creation is \(value.yearOfCreation)")
    if value.nitrousOxideEngine == true {
        print("This car has Nitrous Oxide Engine")
    } else {
         print("There is no Nitrous Oxide Engine on this car.")
    }
    if value.turbo == true {
        print("This car has turbo")
    } else {
        print("There is no turbo in this car.")
    }
    print(" ")
}

Printing all the properties for TankerCar class objects using for loop...
for value in tankerCarsArray {
    print("This car is \(value.brandName)")
    print("The color is \(value.color)")
    print("The car has \(value.numberOfDoors) doors")
    print("The year of creation is \(value.yearOfCreation)")
    print("The tanker is filled with \(value.tankerFilledSize) lb of oil.")

    if value.tankerForm == .cilindrical {
        print("This car has cilindrical tanker form.")
    } else {
        print("This car has quadratic tanker form.")
    }
    print(" ")
}

Now the question. Is there any way to print all the properties for different classes? I tried to create a new array of three arrays:
var allClassesArrays = [carrsArray, sportCarsArray, tankerCarsArray]

But during iteration, it was able to get all the properties of the parent class.

A: This is what reflection is for. You can add a property / method to the Car class that list all the properties of the current class, plus those of the superclass. When this property / method is dynamically applied to the subclasses, it will give what you are looking for.
We need an extension to Mirror that returns all properties of the current instance and those of its superclass recursively, taken from Martin R's answer:
extension Mirror {
    func toDictionary() -> [String: Any] {
        var dict = [String: Any]()

        // Attributes of this class
        for attr in self.children {
            if let propertyName = attr.label {
                dict[propertyName] = attr.value
            }
        }

        // Attributes of superclass
        if let superclass = self.superclassMirror {
            for (propertyName, value) in superclass.toDictionary() {
                dict[propertyName] = value
            }
        }

        return dict
    }
}

class Car: CustomDebugStringConvertible {
    // ...

    var debugDescription: String {
        let dict = Mirror(reflecting: self).toDictionary()
        return dict.map { "\($0.key) = \($0.value)" }.joined(separator: "\n")
    }
}

Usage:
var allClassesArrays = [carrsArray, sportCarsArray, tankerCarsArray]
for car in allClassesArrays.flatMap({ $0 }) {
    print(car.debugDescription, terminator: "\n\n")
}

You of course don't have to conform Car to CustomDebugStringConvertible or name the property debugDescription. I just find them convenient since the debugger will use the debugDescription when you type po car.

redpajama_set_name: RedPajamaStackExchange


text:
Q: annoying clocksource alert/warning in bash prompt periodically So I just build LFS system and it's working fine, but the annoying part is there's alert that every periode show like every 3 second.
It said
root@LFS:# clocksource: timekeeping watchdog on CPU0: acpi_pm wd-wd readback delay of 643744ns
clocksource: wd-tsc-wd read-back delay of 182144ns, clock-skew test skipped!
clocksource: timekeeping watchdog on CPU0: acpi_pm wd-wd readback delay of 643744ns
clocksource: wd-tsc-wd read-back delay of 182144ns, clock-skew test skipped!
clocksource: timekeeping watchdog on CPU0: acpi_pm wd-wd readback delay of 643744ns
clocksource: wd-tsc-wd read-back delay of 182144ns, clock-skew test skipped!
...

This is annoying my bash prompt, I even can't see my output from bash prompt

A: These are logs from the kernel which default to being displayed on the console (/dev/console) which most probably matches the tty terminal you used for login in.
This is of course usually suboptimal and most systems resort to some specific daemon in order to sort and archive logs :
I personally use metalog, syslog-ng is well known, apparently LFS gets a dedicated packet sysklogd
I suggest you first ensure it is not running already (ps -ef | grep klogd), in which case you would have to correct its configuratrion file, and if not then install it, configure it (edit /etc/syslog.conf) and ensure it is launched at init time the sysVinit way.


text:
Q: Calling onStart() on a service while being stopped I have an app in which I'm starting a service when launched:
    Intent networkingService=new Intent(MainActivity.this, SocketMngr.class);
    networkingService.putExtra("FbID",myFbId);
    if (mService==null) mService=new Messenger(messageHandler); //mService is private messenger variable of the activity
    networkingService.putExtra("MESSENGER", mService);
    networkingService.putExtra("REGIDID", regid);
    startService(networkingService);
    bindService(networkingService, mConnection, Context.BIND_AUTO_CREATE);  //mConnection is a private variable of the activity

Now, when the user exit the app, I'm setting a static flag variable in my main activity to a value the service will look at every interval seconds to know whether or not to kill himself.
In the main activity:
 @Override
public void onDestroy()
{
   this.SERVICE_KILL_YOURSELF=true; //this flag is false when app launched
}

and in the service, something like:
 while(MainActivity.SERVICE_KILL_YOURSELF==false)
 {
    ProcessData(); //can take long time thus can be processed while main activity finished
 }
 stopMySelf()

Now, I'm using the depicted scenario because when the user exit the app, the service can still recieve last data packets from a server or sending such data, and only after that, the service should kill himself.
Now, if the service is still processing last data after app destroyed, than app launched again before the service looked at MainActivity.SERVICE_KILL_YOURSELF, and then the app sets SERVICE_KILL_YOURSELF=false while launching, then onStart() will be called and the service won't be stopped, which is fine.
What I'm worried about and question about, is what happens if the service looked at  MainActivity.SERVICE_KILL_YOURSELF which is true because the app destroyed, then the service beginning to stop itself and while it's being stopped the app launched again and the service's onStart() is called.
What will happen in that situation and is there something I should be concerned about?

A: on exit  program may not call onDestroy() or even onStop() you only know that when program exits it will definitely call onPause() so be carefull when using onDestroy()
Your service may be left as is , even when the user has closed your app.


text:
Q: How to add image in a React component from local path in img tag I am using the below img tag in my React component but the image is not displaying when I am taking the image source from a local path.

A: why you are not trying this
import image from "./public/css/avataaars.svg"

or if you want to use svg as a component you can try
import {ReactComponent as SvgIcon} from "./public/css/avataaars.svg"

<SvgIcon/>

A: you can try this -:
using require ...
<img src={require(`public/css/avataaars.svg`)} alt="" />


text:
Q: Can't one load media with spaces in their file names? I appear to have successfully installed media9. My first attempt to use it (listed below) has led to an error, of course: in this case a complaint that 'car' is not a known option. Is it impossible to use spaces in the file name of the media? This would be a serious problem for me, since all my hundreds of file names have spaces in them - usually lots of spaces! (I added quotes to the file name, but that didn't help.)
\documentclass{article}
\usepackage{media9}
\begin{document}
\includemedia[
   width=0.4\linewidth,
   height=0.3\linewidth,
   addresource="D:Audio/67/67A1_Snippets/67_321 fast, car, go here fast.mov",
   activate=onclick,
   deactivate=onclick,
   flashvars={source="D:Audio/67/67A1_Snippets/67_321 fast, car, go here fast.mov"},
  ]{}{VPlayer.swf}
/end{document}

P.S. All my media files are MOVs, but I believe they are MPEG-4 inside.

A: The original question concerned a problem with spaces in filenames. This was apparently solved using egreg's suggestion:
addresource={"D:Audio/67/67A1_Snippets/67_321 fast, car, go here fast.mov"}

Later, it turned out that this was not the (only?) problem and that the commas in the filenames proved more troublesome. Willie Wong suggested that it might be possible to work around this by escaping the backslash, as well as the comma.
Finally, there was some suggestion, also, that omitting the full path and extension might be needed.


text:
Q: Verb tense with "already" Can you please check the answer of this question?

A test for the disease …………… already, but the new one will be quicker and cheaper.

a. exists
b. has existed
c. is existing
d. has been existed

I have doubt between choices a and b

A: Option D is incorrect because of the passive voice.
Options A, B, and C are grammatically sound.
Exist is a stative verb. It's not usually used in the present continuous form. A test is existing already sounds awkward unless you deliberately try to stress the continuity.
has existed would make more sense if you tried bringing attention to the past, e.g. It has existed since the early 2000s.
A looks the best to me because the sentence is about the present and the future developments.


text:
Q: In C#, when a variable passes through a function/method, will the original variable change? I am confused by how a function can change a variable passed through it. For example, if I created a variable t = 1, and pass a function by adding 2 to it, inside the function t is 3, but in Main function t is still 1:
static void Main(string[] args)
{
    int t = 1;
    addTwo(t);
    Console.WriteLine(t);
    ## t=1
    Console.ReadLine();
}
static void addTwo(int t)
{
    t+=2;
    Console.WriteLine("inside function {0}",t);
    ## t=3

the value of t inside the function is 3, but in Main the value stays 1.
However if I created an array "happiness" with value {2,3,4,5,6} and passed through a function "SunIsShining" which will increase each value by 2. Afterwards, I thought the array happiness should still be {2,3,4,5,6}. However it became {4,5,6,7,8}.
static void Main(string[] args)
{
    int[] happiness = { 2, 3, 4, 5, 6 };
    SunIsShining(happiness);
    ## happiness = { 4, 5, 6, 7, 8 }

    foreach (int y in happiness)
    {
        Console.WriteLine(y);
    }
    Console.ReadLine();
}
static void SunIsShining(int[] x)
{
    for (int i = 0; i < x.Length; i++)
        x[i] += 2;
}

Could anyone help me to understand the reason? Thank you!

A: Because

*

*int[] is a reference type that might pass the object reference to the function, so you modify the value from the same array.

*int is a value type that will clone value before passing to the function, so you modify the value is not t from Main function.
We can prove by this sample code by ReferenceEquals method that will compare the object reference whether the same as below, let's say we can see addTwo is return false, but SunIsShining return true.
static int t1;
static int[] happiness;
static void Main(string[] args)
{
    t1 = 1;
    happiness = new int[]{ 2, 3, 4, 5, 6 };

    addTwo(t1);
    SunIsShining(happiness);

    Console.ReadLine();
}
static void addTwo(int t)
{
    t+=2;
    Console.WriteLine("Is same object by value?" + object.ReferenceEquals(t1,t));
}

static void SunIsShining(int[] x)
{
    Console.WriteLine("Is same object by refer?" + object.ReferenceEquals(happiness,x));
}

c# online
More information we can see
value-types
reference-types
passing-parameters

A: Variable passing is divided into value passing and address passing.
Value passing can't change the previous value, address passing is passing the address, so you can change the previous value.
For example, the first one is passed by the name of the variable. T stores an int, so it passes a data, so it passes a 1 in the function, independent of the t in Main.  Pass is the value
Behind;  We're passing the name of the array, and the name of the array is the address of the first element in the array, so we're passing the address, so we're accessing it by address, changing the original value

A: The difference in semantics between your two examples is not explained by the different types, but rather by you doing different things to the parameter in your two examples.
In the first example, you are assigning to the parameter (t += 2 is equivalent to t = t + 2. t = something is assignment to t.) In the second example, you do not assign to x; rather, you are using the array element syntax to modify the internal contents of the array pointed to by x. If you did the same thing you did in your first example in your second example, i.e. assign directly to the parameter x, you would see that the called scope is similarly not affected by the assignment:
static void Main(string[] args) {
    int[] happiness = { 2, 3, 4, 5, 6 };
    SunIsShining(happiness);

    foreach (int y in happiness) {
        Console.WriteLine(y); // prints 2, 3, 4, 5, 6
    }
}
static void SunIsShining(int[] x) {
    x = new int[] {7, 8, 9};
}

So despite your first example passing int, a value type, and this example passing int[], a reference type, you can see that the result of assigning to the parameter in the called function is the same in both cases. And in fact this is true for all other types too -- if the method parameter is not marked ref or out, then no matter what type the parameter is, direct assignment to that parameter variable in the called function will never have any effect on a passed variable in the calling function.
Passing a variable to a method parameter that is not ref or out is exactly like assigning to a new variable. So rather than thinking about passing to methods, you can just think about what happens when you assign to a new variable. When you do this for your first example, you assign one int to another. Since int is a value type, each int variable holds its own integer, and assignment copies the integer so both variables' integers have the same value. Then when you assign to the second variable, you change that integer, but it doesn't affect the first variable's integer. This is pretty easy to understand.
int tInMain = 1;

int tInAddTwo = tInMain;
tInAddTwo += 2;
Console.WriteLine("inside function {0}", tInAddTwo); // prints 3

Console.WriteLine(tInMain); // prints 1

If you do this with my example above, you see we assign one int[] variable to another. int[] is a reference type, so the value of such a variable is a "reference" (basically, in C++ parlance, a pointer to an object). When you copy one reference to another, you get two references that have the same value, i.e. they both point to the same object. When you then assign a reference to another object to one of the variables, you just make that variable point to that other object. It does not do anything to the object that it used to point to (which the first variable still points to).
int[] happiness = { 2, 3, 4, 5, 6 };

int[] x = happiness;
x = new int[] {7, 8, 9};

foreach (int y in happiness) {
    Console.WriteLine(y); // prints 2, 3, 4, 5, 6
}

And if you do this with your second example, you see that you again assign one reference to another, so you have two reference variables pointing to the same object. But then you use one of those references to make a change to the contents of the object that is pointed to. This change is then obviously visible when you look at the object pointed to by the other reference, since it's the same object that is being pointed to.
int[] happiness = { 2, 3, 4, 5, 6 };

int[] x = happiness;
for (int i = 0; i < x.Length; i++)
    x[i] += 2;

foreach (int y in happiness)
{
    Console.WriteLine(y); // prints 4, 5, 6, 7, 8
}

Now you might ask why you can't do something like this with your first example. The reason is that the operation you are doing, i.e. "modify the object pointed to by the reference", simply doesn't exist for the type int. Most obviously, this is because int is a value type. But even for reference types, you might not be able to do this, because the object that is being pointed to might not offer you a way to modify its contents. For example, consider the following example where we box the int into an object variable of type object:
static void Main(string[] args) {
    object t = 1;
    addTwo(t);
    Console.WriteLine(t); // prints 1
}
static void addTwo(object t) { // <-- object is a reference type
    // there is nothing you can do to t here
    // that will change what is printed in Main

    // as described above, assignment to t
    // will never affect the calling scope:
    t = (int)t + 2;
}

This is similar to your first example, except that the parameter type is object, a reference type (the type of references to objects). But this object that the int is boxed into simply does not offer a way for you to modify its contents. So even though in this case, you passed a reference, and the t in addTwo and the t in Main point to a single object, it doesn't really matter since you can't make a change to that object that can be seen through the other reference.


text:
Q: How to align icon inserted with :before method? How can I vertically align icon inserted using :before method?
Here is what I have:

  Some Text

CSS:
.button a{
    background: none;
    background-color: #32BBE7;
    text-indent:1px;
    color:#FFF;
    text-decoration: none;
    display: table-cell;
    vertical-align:middle;
    text-align:center;
    height: auto;
    padding: 10px;
    border-radius: 3px;
    font-weight: 600;
    font-size: 50px;
    font-style: italic;
}

.button a:hover{
    background-color: #2597F0;
}

.button a:before {
    content:url(http://i.stack.imgur.com/tKsDb.png);
    position: relative
}

JSFiddle: https://jsfiddle.net/1z83tc1o/
How Can I align vertically icon relative to the text?

A: You can use background and set is size (width, height), Then you can use vertical-align.
CSS
.button a:before {
    position: relative;
    display: inline-block;
    width: 18px;
    height: 16px;
    vertical-align: middle;
    content:"";
    background: transparent url(http://i.stack.imgur.com/tKsDb.png) no-repeat center center;
    margin-right: 20px; // Optional

}

DEMO HERE

A: You use background and absolute position the icon to perfectly vertical align in the middle.
.button a:before {
    content: " ";
    background-image: url(http://i.stack.imgur.com/tKsDb.png);
    position: absolute;
    width: 18px;
    height: 16px;
    top: 50%;
    margin: -8px 0 0 -25px;
}

Here is the example : https://jsfiddle.net/1z83tc1o/3/


text:
Q: Inspect request body and header Using the aiohttp Client, is it possible to inspect a request (header and body) before or after sending?
I am using aiohttp.ClientSession to make and send the request - but I'd like to see the header and body that actually got sent.
Thank you

A: Please take a look on client tracing support: http://docs.aiohttp.org/en/stable/client_advanced.html#client-tracing


text:
Q: Documentar codigo de Dart Intentando documentar codigo del lenguaje Dart, haciendo comentarios de algunas de las funciones y secciones que se tiene el codigo del proyecto, inclui algo de descripcion de las varibles
como resultado es esto, estara bien? alguna sugerencia
 Future getBannerBig() async {
    ///Utilizamos un bloque [try] el cual dentro contiene código que posiblemente resulte en una excepción o error.
    ///Try catch, instruccion para manejar errores que lleguen a ocurrir.
    try {
      ///Con un QuerySnapshot nos devuelve la consulta y se toma la referencia de la ubicación en Firebase.
      ///Si no se usa el [await] no se toma la referencia.
      final all = await _db.collection('banner_grande').getDocuments();
      print(all.documents);
      List<String> handles = new List();
      for (var item in all.documents) {
        ///La variable [_urlD] espera lo que se ha tomado como referencia.
        ///
        ///Pasaremos el valor por referencia a un método, lo que implica que el valor va a cambiar dentro del método.
        ///Luego con el metodo child devuelve todos los datos del elemento seleccionado.
        ///En donde muestra los datos llamados [name] que se encuentran dentro del documento de la coleccion [banner].
        String _urlD = await FirebaseStorage.instance
            .ref()
            .child("banner/${item.data['name']}")
            .getDownloadURL();
        handles.add(_urlD);
      }

      ///
      print(handles);

      ///El tipo de retorno no cambia, de esta manera vuelve a mostrar banner en ciclo.
      return handles;
    }

    ///Basicamente lo que hace [catch] es de que si se ha presentado alguna excepción en el codigo que esta en [try]
    ///lo captura, imprime el tipo de excepcion y se devuelve como [null], un vacio y no muestra los datos de la coleccion.
    catch (e) {
      print(e);
      return [];
    }
  }

A: Me parece bastante fácil para cualquier programador que no entienda mucho de Dart, como yo.
Si tuviera que coger tu programa y empezar a programar estaría genial tener esos comentarios.

A: Doc comments vs. comentarios habituales
En primer lugar, deberías plantearte si realmente necesitas incluir doc comments (///) en tu código o no. Por norma general, se utilizan este tipo de comentarios en la definición de clases, métodos, etc. de librerías públicas. De esta forma, el IDE puede identificar y mostrar información relevante (como descripciones y ejemplos de uso) al usuario de la librería cuando, por ejemplo, pasa el ratón por encima de una función. Además, los doc comments pueden ser utilizados para generar documentación de un proyecto con dartdoc.
Si necesitas añadir comentarios a tu propio código también puedes utilizar doc comments, pero lo más habitual es utilizar comentarios normales (//).
Qué comentar y qué no
En segundo lugar, documentar cada línea de tu código no es una cosa necesariamente positiva. Por ejemplo, no es necesario comentar qué es lo que hace un bloque try/catch. Es un concepto ampliamente extendido en la mayoría de lenguajes modernos, y no aporta valor al usuario de tu código.
Además, deberías intentar que tu código sea lo más autoexplicativo posible, de forma que se minimice el número de comentarios. Esto se consigue utilizando nombres descriptivos para tus clases, funciones y variables; y evitando expresiones excesivamente complejas.
Fuente: https://dart.dev/guides/language/effective-dart/documentation


text:
Q: Azure Sphere logging For Sphere devices, we can vscode/cli to deploy, debug and see logs of the application  [1]. But later  (say I kept it running for 24 hours and comes back), if I wish to see application logs, it looks like, I don't have a way. Is there a way to see application logs on Sphere development boards without initiating the debugger?
To be clear, this is not about monitoring applications deployed in production  [2]. This is only about development logs on Azure Sphere development boards. An example is logcat in Android [3]. The intention is to analyse long running application on Azure Sphere. We cannot keep the debugger attached forever.

A: This is a late response and you've probably figured it out by now but if your Azure Sphere device is connected to a network, you can send debug logs over a UDP socket without the need for the device to be attached to the Visual Studio debugger or even a PC.
Here's an example application that modifies the Log_Debug library to send the output over UDP to a receiver application that writes the output to a "deviceLog.txt" file.


text:
Q: Facebook shows  tag in gatsby blog post description When I share a blog post link on facebook, the auto generator preview shows the P tag in the description. How can i fix it? My Seo is very messy on google, dont index all pages and social networks. I need help. I'm following as a guideline from the official Gatsby website.
blog post seo props:

<Seo title={data.post.title}
  description={data.post.excerpt} />

Seo component:

import React from 'react'
import PropTypes from 'prop-types'
import { Helmet } from 'react-helmet'
import { useLocation } from '@reach/router'
import { useStaticQuery, graphql } from 'gatsby'

const SEO = ({ title, description, image, article }) => {
  const { pathname } = useLocation()
  const { site } = useStaticQuery(query)

  const {
    defaultTitle,
    titleTemplate,
    defaultDescription,
    siteUrl,
    defaultImage,
    twitterUsername
  } = site.siteMetadata

  const seo = {
    title: title || defaultTitle,
    description: description || defaultDescription,
    image: `${siteUrl}${image || defaultImage}`,
    url: `${siteUrl}${pathname}`
  }

  return (
    <Helmet title={seo.title} titleTemplate={titleTemplate}>
      <meta name="description" content={seo.description} />
      <meta name="image" content={seo.image}
      />

      {seo.url && <meta property="og:url" content={seo.url} />}

      {(article ? true : null) && <meta property="og:type" content="article" />}

      {seo.title && <meta property="og:title" content={seo.title} />}

      {seo.description && (
        <meta property="og:description" content={seo.description} />
      )}

      {seo.image && <meta property="og:image" content={seo.image} />}

      <meta name="twitter:card" content="summary_large_image" />

      {twitterUsername && (
        <meta name="twitter:creator" content={twitterUsername} />
      )}

      {seo.title && <meta name="twitter:title" content={seo.title} />}

      {seo.description && (
        <meta name="twitter:description" content={seo.description} />
      )}

      {seo.image && <meta name="twitter:image" content={seo.image} />}

      <html lang="pt-BR" />
    </Helmet>
  )
}

export default SEO

SEO.propTypes = {
  title: PropTypes.string,
  description: PropTypes.string,
  image: PropTypes.string,
  article: PropTypes.bool
}

SEO.defaultProps = {
  title: null,
  description: null,
  image: null,
  article: false,
  lang: 'pt-BR'
}

const query = graphql`
  query SEO {
    site {
      siteMetadata {
        defaultTitle: title
        titleTemplate
        defaultDescription: description
        siteUrl: siteUrl
        defaultImage: image
        twitterUsername

      }
    }
  }
`


text:
Q: Realizar Input Radio como un Slide en su transicion Por favor su ayuda con el css, ya que estoy intentando realizar una transición tipo slide en un Input tipo Radio, pero solo logro la transición hacia el select izquiero, pero cuando intento el movimiento hacia la derecha, no realiza dicha transición slide, solo se selecciona normal.

A continuación adjunto el codigo:

  <input type="radio" name="type" id="inc" value="inc" class="form__radio" checked />
  Ingreso
  <input type="radio" id="exp" value="exp" name="type" class="form__radio" />
  Gasto

.form__group .form__radio {
  display: none;
}

.form__group.radio {
  background-color: var(--third);
  border-radius: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: .5rem;
  font-size: 1.2rem;
  margin-bottom: 2rem;
  color: var(--primary);
}

.form__group .form__radio + .form__label {
  position: relative;
  z-index: 1;
  flex: 1;
  text-align: center;
  padding: 1rem;
  margin-right: .5rem;
  cursor: pointer;
}

.form__group .form__radio + .form__label::before {
  content: "";
  width: 100%;
  height: 100%;
  mix-blend-mode: overlay;
  position: absolute;
  top: 0;
  border-radius: .8rem;
  font-weight: bolder;
  transition: left .4s ease-in;
}

.form__group .form__radio:nth-child(1) + .form__label::before {
  left: 100%;
}

.form__group .form__radio:nth-child(2) + .form__label::before {
  left: 0;
}

.form__group .form__radio:checked + .form__label::before {
  background-color: var(--secondary);
  left: 0;
}

Muchas gracias por su ayuda.

A: Para que el efecto se mantenga, solo un elemento debe moverse y mantener el background (en el ejemplo, solo el primer label). Este elemento recibe la transicion para ambos sentidos.
Ademas para que haya transision debe haber un valor por inicial definido left: 0 en .form__group .form__radio + .form__label::before {

* {
  --secondary: #aaa;
  --third: #ccc;
  --primary: #080;
}

.form__group .form__radio {
  display: none;
}

.form__group.radio {
  background-color: var(--third);
  border-radius: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: .5rem;
  font-size: 1.2rem;
  margin-bottom: 2rem;
  color: var(--primary);
}

.form__group .form__radio + .form__label {
  position: relative;
  z-index: 1;
  flex: 1;
  text-align: center;
  padding: 1rem;
  margin-right: .5rem;
  cursor: pointer;
}

.form__group .form__radio + .form__label::before {
  content: "";
  width: 100%;
  height: 100%;
  mix-blend-mode: overlay;
  position: absolute;
  top: 0;
  left: 0;
  border-radius: .8rem;
  font-weight: bolder;
  transition: left .4s ease-in;
  border: 1px solid red;
}

.form__group .form__radio:nth-child(1) + .form__label::before {
  background-color: var(--secondary);
  left: calc(100% + 0.5rem);
  border: 1px solid green;
}

.form__group .form__radio:nth-child(2) + .form__label::before {
  left: 0;
  border: 1px solid blue;
}

.form__group .form__radio:checked + .form__label::before {

  left: 0;
}

  <input type="radio" name="type" id="inc" value="inc" class="form__radio" checked />
  Ingreso
  <input type="radio" id="exp" value="exp" name="type" class="form__radio" />
  Gasto

Agregué colores de borde para mostrar cual es el elemento recibiendo la transicion (borde verde)


text: Q: Symfony2 and Payum Bundle: How do I connect payment with order placed by a customer? I have 2 entities in my database: Client and Product. Every time someone places order I store in DB new entity with Client data and some corresponding entities with Products (one-to-many), I don't have any other entity for keeping order as a whole. I added Payum Bundle with simple PayPal configuration and everything is working, but how can I connect payment info with Product? What is the best way to do this? Maybe there is something that I overlooked in Payum Documentation?


text:
Q: Why does the next line of a function still execute despite calling another function before such line? Here's a sample code where it is evident:
int foo();
void bar();

bool flag = false;

int foo()
{
    if(!flag) bar();
    cout<<"Reached Here!"<<endl;
    return 0;
}

void bar()
{
    flag = true;
    foo();
}

In this code, cout<<"Reached Here!"<<endl; is executed twice. However, simulating it step-by-step does not agree with that. From what I am expecting, it should go like this:

*

*Since !flag is true, call bar()

*From function bar(), set flag = true

*Then, call foo()

*Since !flag is now false, we just proceed to next line

*Output Reached Here to console

*End of Program

As you can see, I am expecting for cout<<"Reached Here!"<<endl; to only be executed once. So, why is it being executed twice and how can I avoid that (aside from enclosing the next lines with else)?
Edit: Changed foo() to bar() and changed main() to foo()

A: When you return from functions, the execution continues from the line after the function call. This is what return means.
Therefore, the actual trace is:

*

*(1st call of) foo() calls bar(), seeing flag = false

*bar() sets flag = true

*bar() calls (2nd) foo()

*(2nd call of) foo() skips bar(), seeing flag = true

*(2nd call of) foo() prints "Reached Here!"

*(2nd call of) foo() returns zero to bar()

*bar() returns

*(1st call of) foo() prints "Reached Here!"

*(1st call of) foo() returns zero to its caller


text:
Q: How to build a RESTful webservice using ServiceStack? ServiceStack Samples not working The samples given at servicestack are not working. I am new to servicestack.I want to build RESTful web service with service stack.PLease direct me in proper direction.

A: Not sure what the issue you're running into is but the ServiceStack.Examples projects do work. They were all developed in VS.NET and are deployed on servicestack.net Linux Server.
The Razor Rockstars example project is deployed on razor.servicestack.net.
The Social Bootstrap API (MVC + Bootstrap + Backbone) project is deployed on a windows server on AppHarbor at bootstrapapi.apphb.com.


text:
Q: .addRole and .removeRole are not functions - Discord Bot Mute Case I have scanned through all the related topics on Stack Overflow and Tried everything, but the codes just won't work :)
So I'm following a YouTube tutorial on how to mute members using a bot on Discord, and here is the error:
TypeError: person.removeRole is not a function
at Client.<anonymous> (C:\Users\hp\Documents\discordBot\Codes\index.js:39:14)
    at Client.emit (events.js:311:20)
    at MessageCreateAction.handle (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)    at WebSocketManager.handlePacket (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (C:\Users\hp\Documents\discordBot\Codes\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (C:\Users\hp\Documents\discordBot\Codes\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:311:20)
    at Receiver.receiverOnMessage (C:\Users\hp\Documents\discordBot\Codes\node_modules\ws\lib\websocket.js:801:20)

Here is my code, other parts are eliminated if it's necessary I can put them here.
case "mute":
      let person = m.mentions.members.first() || m.guild.members.fetch(args[1]); //m.guild.member(
      //console.log(person);
      if (!person) return m.reply("I don't know who this is, bro.");

      let mainrole = m.guild.roles.cache.find((role) => role.name === "Main");
      let muterole = m.guild.roles.cache.find((role) => role.name === "Mute");

      if (!muterole) return m.reply("Sorry they simply don't exsit.");

      let time = args[2];
      console.log(time);
      if (!time) return m.reply("That's not a time. How did you even do it?");

      person.removeRole(mainrole.id);
      person.addRole(muterole.id);
      // person.remove("Main");
      // person.add("Mute");

      m.channel.send(
        `@${person.user.tag} has now been mute for ${ms(ms(time))}`
      );

      setTimeout(() => {
        person.addRole(mainRole.id);
        person.removeRole(muterole.id); //switching the order and see how that looks like
        m.channel.send(`@${person.user.tag} has been unmuted, good job!`);
      }, ms(time));

Makes me wonder if the import of ms module or discord.js has some problems?
Send help please!
Thank you!

A: Since discord.js v12 you now need to use roles.add() and roles.remove() instead of .addRole() and .removeRole().


text:
Q: Combinatoric Proof of $i(n+1,k) = i(n,k) + i(n, k-1) + i(n, k-2) + i(n, k-2) + \cdot\cdot\cdot + i(n, k-n) $ Let $i(n,k)$ denote the number of permutations where $\sigma \in S_n$ with $i(\sigma) = k$, that is $k$ inversions.
I want to provide combinatoric proof for the below statement:
$i(n+1,k) = i(n,k) + i(n, k-1) + i(n, k-2) + i(n, k-2) + \cdot\cdot\cdot + i(n, k-n) $

To prove this, since the RHS denotes for the disjoint number of permutations at each terms, I want to well-dissect the LHS into $n+1$ disjoint cases.
I can easily think that $i(n,k)$ from LHS corresponds to the case of $i(n+1, k)$ where the n+1 always positioned at the last of the permutation.
However, from the second term of LHS, can't figure out to where should it be corresponded to.

Any hint/advice to approach?

A: Hint. Take a permutation $\sigma\in S_{n+1}$ with $i(\sigma) = k$ and assume that $\sigma(j)=n+1$ with $1\leq j\leq n+1$. If we "eliminate" $n+1$ and shift to the left the entries we obtain a permutation $\sigma'\in S_{n}$. What is $i(\sigma') $?
P.S. By the way the above identity follows also from the generating function
$$F(z) =\sum_{k=0}^{\binom{n}{2}} i(n,k)z^k= \prod_{j=0}^{n-1} (1+z+z^2+\cdots +z^j).$$


text:
Q: How can I compose a LINQ query with the help of a predicate builder I actually wanted to share this piece of code as I think it is of great use.
So, think that you want to programtically create a linq query.
It would be very nice to have that in a readable format, would it not?
We could create code like this:
PredicateBuilder<Document> filter = new PredicateBuilder<Document>();
filter.Add(x => x.IsDeleted == false);
filter.Add(x => x.IsArchive == false);

if (ucSearch.SearchText != "")
    filter.Add(x => x.DocumentName.Contains(ucSearch.SearchText));
repository.GetAll().Where(filter.GetLambda()).ToList();

A: The code can be achieved with the help of a helper class like the one below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Extensions
{
    public class PredicateBuilder<T> : List<Expression<Func<T, bool>>>
    {
        private class ParameterReplacer : ExpressionVisitor
        {
            private readonly ParameterExpression _parameter;
            public ParameterReplacer(ParameterExpression parameter)
            {
                _parameter = parameter;
            }
            protected override Expression VisitParameter(ParameterExpression node)
            {
                return base.VisitParameter(_parameter);
            }
        }
        public Expression<Func<T, bool>> GetLambda()
        {
            if (this.Count > 0)
            {
                var type = Expression.Parameter(typeof(T));
                if (this.Count > 1)
                {
                    BinaryExpression binaryExpression = Expression.MakeBinary(ExpressionType.And,
                        new ParameterReplacer(type).Visit(this.First().Body),
                        new ParameterReplacer(type).Visit(this.Skip(1).First().Body));
                    if (this.Count > 2)
                    {
                        foreach (var ex in this.ToList().Skip(2))
                            binaryExpression = Expression.And(binaryExpression, new ParameterReplacer(type).Visit(ex.Body));
                    }
                    return Expression.Lambda<Func<T, bool>>(binaryExpression, type);
                }
                else
                    return Expression.Lambda<Func<T, bool>>(new ParameterReplacer(type).Visit(this.First().Body), type);
            }
            return null;
        }
        public Func<T, bool> GetPredicate()
        {

            if (this.Count > 0)
            {
                var type = Expression.Parameter(typeof(T));
                if (this.Count > 1)
                {
                    BinaryExpression binaryExpression = Expression.MakeBinary(ExpressionType.And,
                        new ParameterReplacer(type).Visit(this.First().Body),
                        new ParameterReplacer(type).Visit(this.Skip(1).First().Body));
                    if (this.Count > 2)
                    {
                        foreach (var ex in this.ToList().Skip(2))
                            binaryExpression = Expression.And(binaryExpression, new ParameterReplacer(type).Visit(ex.Body));
                    }
                    return Expression.Lambda<Func<T, bool>>(binaryExpression, type).Compile();
                }
                else
                    return Expression.Lambda<Func<T, bool>>(new ParameterReplacer(type).Visit(this.First().Body), type).Compile();
            }
            return null;
        }
    }
}


text:
Q: Input field outside of div in firefox - Bootstrap Getting some odd behavior with a single input field on my login form that only happens in firefox...in chrome it's completely fine. The code is no different than any other input field in the forms on the page but this one is choosing to appear outside of the form div and will not allow you to type in it, also looks like it has a 0% length or atleast the smallest length possible. I'm using bootstrap for the field/form css.
An html snippet of the form (id: email_login is causing the issue):

<form action="process_login.php" name="login_form" method="post" id="login_form" class="form-horizontal" role="form">

    <input id="email_login" type="text" class="form-control" name="email" placeholder="Email Address" />

    <input id="password_login" type="password" class="form-control" name="password" placeholder="Password" />

      <input onclick="formhash(this.form, this.form.password);" value="Login" id="btn-login" type="button" class="btn btn-primary" />

Heres an image of what's going on

Thanks in advance...will be happy to provide further info. I didn't include the css as it's just the standard bootstrap classes with no modifications.
EDIT:
I managed to fix this issue by modifying the .input-group class in bootstrap from display:table to display:inline-table.
This did not affect any other forms on my website, but managed to fix the display issue in firefox.
So consider it solved in my case.


text:
Q: Find in which polygon a GeoJSON point lies in, in NodeJS Given a defined (lat, lon) geo-point I'm trying to find in which polygon this point lies in. I suppose iterating over all the polygons is not efficient. Is there available any function or library for NodeJS that does this?
const polygon = getPolygonFromPoint(FeatureCollection, x, y);

There are no overlapping polygons, actually I'm using this to detect in which district of a certain country a defined GPS coordinates point lies in.

A: For a simple point in polygon test you can check turf which has a booleanPointInPolygon. Turf works in node but you should check for differences between v5 and v6+ around how to use npm accordingly. Points should be long/ lat (not lat/ long) and the polygon can be easily pulled out of the feature geometry of your feature collection.
For a more complex use case where you have many points and many polygons within which to locate them you should consider using rbush.
Note that the rbush library constructs an r-tree out of the bounding boxes of the polygons and not the polygons themselves, so use of an r-tree is just a way to vastly reduce the number of polygons you need to test with booleanPointInPolygon.
Example code for rbush:
const RBush = require("rbush");
const turfBbox = require("@turf/bbox").default;

const geo = {} // your feature collection...
const maxEntriesPerNode = 50; // check the doco
const tree = new RBush(maxEntriesPerNode);
const bbox2Object = (keys, bbox) => ["minX", "minY", "maxX", "maxY"].reduce((o, k, i) => ({...o, [k]: bbox[i]}), {})

// create rtree from feature collection
geo.features.forEach(feature => {
  const leaf = bbox2Object(bboxKeys, turfBbox(feature)); // use bbox of feature
  leaf["id"] = feature.properties.SOME_ID; // add some custom properties
  tree.insert(leaf);
});

// test a random point from your data
const [x, y] = [123, 456]; // should be long, lat
const test = tree.search({minX: x, minY: y, maxX: x, maxY: y});
// test should have an array of leaves per the tree.insert above

You can then perform the booleanPointInPolygon test on this reduced set of polygons.

A: I implemented that with the library polygon-lookup
const PolygonLookup = require('polygon-lookup')
const featureCollection = {
    type: 'FeatureCollection',
    features: [{
        type: 'Feature',
        properties: { id: 'bar' },
        geometry: {
            type: 'Polygon',
            coordinates: [ [ [ 0, 1 ], [ 2, 1 ], [ 3, 4 ], [ 1, 5 ] ] ]
        }
    }]
}
var lookup = new PolygonLookup(featureCollection)
var poly = lookup.search(1, 2)
console.log(poly.properties.id) // bar


text:
Q: Validation Symfony2 with query to database I have a problem with a validation form in symfony2.
I have a form with entity. Into the file 'validation.yml' I used CALLBACK: it invoke the method 'isValidForm' content in file 'Entity.php'
ALM\CreateReleaseBundle\Entity\createReleaseEntity:
    constraints:
        - Callback:
            methods: [isFormValid]

This is my file 'Entity.php'
<?php
namespace ALM\CreateReleaseBundle\Entity;
use Symfony\Component\Validator\ExecutionContext;

class createReleaseEntity {
    protected $area;
    protected $relName;

    public function getArea() {
        return $this->area;
    }

    public function setArea($area) {
        $this->area = $area;
    }

    public function getRelName() {
        return $this->relName;
    }

    public function setRelName($relName) {
        $this->relName = $relName;
    }

    public function isFormValid(ExecutionContext $context) {
        // Validate Form
    }
}

Now in 'isFormValid' I would like to insert a forward to the function getRelease placed in another controller.
public function getReleaseAction (Request $request) {
$area = $request->get('area');
    $relName = $request->get('relName');
    $ret = $this->getRelease($area,$relName);
    $session = $this->get('request')->getSession();
    $session->set("releaseObj", $ret);
    return new Response ();
}

It is possible? How I can do it?

A: You should not access the Controller from the Model under any circumstances.
What kind of query do you want to perform?
If you want to check if the Release is unique in database by relName for instance, use the Doctrine's UniqueValidator on that field.
Hope it helps


text:
Q: Deleting row index in data frame in python? I have a data frame in python like below
ID  Featurename  TerminalName   NBBikes  NBEmptydoc   UploadDate    lat    lon

2   XXXXX           XXXXX           XXX     XXX          XXX         X      X

3   XXXXX           XXXXX            XX     XXX          XXX        X       X

and i am exporting this data frame to csv file using below command:
csvdf.to_csv('./en_final_table_2.csv', sep='\t', encoding='utf-32')

while exporting i don't want the ID column in my csv file, is there a way to do this?
Please help.

A: If 'ID' is in the index, then you can use index=False:
csvdf.to_csv('./en_final_table_2.csv', sep='\t', encoding='utf-32', index=False)


text:
Q: Footer - Different Odd and Even pages in Word 2007 I've tick the 'Different odd & even pages', clicked 'Next section' and typed 2. All my even pages changed to "2". If I retyped page 4, every even pages changes to "4". I want to keep my odd pages' footer right and even pages' footer left, with continuing page number. How??? Thanks~

A: Do not manually type the number you want.
When in footer-edit-mode, go to the design tab, and select Page Number on the left.


text:
Q: How to fix the error "argument "modelName" is missing, with no default" when using MVN package I am using the MVN package, in R, to find whether each class of the dataset iris is multivariate normal or not.
I used the below code earlier in the day and generated results from it. However, I went to revisit it and now keep getting the following error message:
Error in mvn(data = iris[Species == m[1], 1:4], mvnTest = c("mardia")) :
  argument "modelName" is missing, with no default

Can not figure out what this means and how to fix it !
Code:
#Mardia's Test
SM<-mvn(data=iris,subset="Species", mvnTest="mardia")

SM$multivariateNormality

SetosaPlot<-mvn(data=iris, subset="Species", multivariatePlot="qq")

A: You loaded the mclust package.  When you did so you should have seen a warning

The following object is masked from 'package:MVN': mvn

So now mvn() is calling mclust::mvn() (i.e. the mvn function in the mclust package) rather than MVN::mvn().

*

*In general you can make sure you get the version from the MVN package by using

MVN::mvn(data=iris, subset="Species", multivariatePlot="qq")

*

*If you want to know where R is finding mvn, try find("mvn")

*In general, to resolve these kinds of problems you should start a clean R session, so that you know you're starting with no packages loaded.

(By the way, no real data set is ever truly multivariate normal; you're not testing "whether it is MVN or not", but rather whether it is close enough to MVN that you can't reject the null hypothesis of multivariate normality ...)


text:
Q: Javascript new date() function return wrong date i need to convert a date like this new Date(2018, 12, 24, 10, 33) but it returns like this Thu Jan 24 2019 10:33:00 GMT+0530 (India Standard Time) any idea. For other months its working fine. Even i checked in w3school
There also it return wrong date please give me any solution

A: Because in javascript Date object months are numbered from 0 (January) to 11 (December). 12 in your new Date() code is not a valid month, so javascript converts it to 0, returning you a date in January.

A: There is no issue in javascript function.
In Javascript months start with 0 to 11, if you pass 0 will return January and 11 will return december.
Somehow JavaScript returning January during insertion of 12 month in digit instead of error but you achieved your result by 0 to 11 month.
Here is code for your reference.
<!DOCTYPE html>

JavaScript new Date()

5 numbers specify year, month, day, hour, and minute:


text:
Q: Apple Watch app won't re-install after being deleted on iOS 8.2, just hangs on launch screen I can install my Apple Watch app (that is in production) on my watch and it loads just fine the first time. If I uninstall it, and re-install it, it installs fine, but when I tap on the icon it just hangs. It has the loading indicator and the name of the app and it won't ever load.
Here is the error from the device log:
Jul  6 15:20:23 xxxxx-iPhone companionappd[417] <Notice>: (Error) WatchKit: <SPApplicationManager.m __56-[SPApplicationManager beginUsingPlugin:withCompletion:]_block_invoke264:392> * * * After 10.0 secs, beginUsing: hasn't called us back for plugin with beginUsingInstanceUUID <__NSConcreteUUID 0x127e18800> 53259124-xxxx-454F-xxxx-FD013Dxxxxxx
Jul  6 15:20:23 xxxxx-iPhone companionappd[417] <Notice>: (Warn ) WatchKit: <SPApplicationManager.m __83-[SPApplicationManager getOrBeginActivePlugInForApplication:setupBlock:completion:]_block_invoke_2319:478> Unable to start plugin com.xxxxx.watchkitextension 0x127e887c0 with identifier com.xxxxx.watchkitapp (Error Domain=com.apple.watchkit.errors Code=17 "PKPlugin beginUsing: never called back" UserInfo=0x127d62b90 {NSLocalizedDescription=PKPlugin beginUsing: never called back})
Jul  6 15:20:23 xxxxx-iPhone companionappd[417] <Notice>: (Error) WatchKit: <SPCompanionAppServer.m __51-[SPCompanionAppServer sendToRemoteInterface:call:]_block_invoke492:860> activePlugInForIdentifier: returned nil for application com.xxxxx.watchkitapp
I can't figure out what is going on. Is this an SDK/OS issue that is out of my hands? Has anyone seen this?
UPDATE: I just read (and confirmed) on the forums that if you restart both the watch and the phone, the watch app will load without issue. Sounds like an OS bug to me.
UPDATE 2: Got a response from a radar I filed:

I guess its good to confirm they knew about it and fixed it.

A: This definitely sounds like an OS error, as your log even says Unable to start plugin com.xxxxx.watchkitextension. That is nothing you can do anything about. I was going to say that you should probably just restart your simulator inorder for it to work properly again. Another option would have been to just reset your simulator and hardware, however that is only the worst case scenario. As the above person said, you should file a radar here. Lastly, you could try to install it on a real device and then delete it in order to check if it's an simulator bug or it will also happen on normal devices. There's a good chance it's just the simulator being unable start up the app. Hope that helps,
Julian

A: I experienced this issue myself and you shouldn't worry about it. It's a common bug in watchOS that everybody is experiencing from time to time, even normal users with third-party apps.
Since watchOS isn't really out of beta (in my opinion), you should wait for the next release, drink a cup of coffee and hope that it will be fixed soon.
I can definitely promise that you aren't alone with this bug and that you can't do anything against until Apple will fix it. If you can't wait, you can create a bug report here.

A: If you are facing the same issue on a real watch - restarting the watch and the phone helped me, this issue never came back again at least till the next time I had this issue.
OS versions used:
iPhone: 5s
iOS: 8.3
Watch OS: 1.0.1
Thanks to the below forum thread,
https://forums.developer.apple.com/thread/7845

A: I recently ran into this issue running Xcode 7.0 beta 3 iOS 9.0 beta watchOS 2.0 beta.  The simulator error log showed the following.

Jul 15 09:48:39 mymachine DTServiceHub[69227]:
  DTMemlimitAssertionFactory: failed to remove active and inactive
  memory limits for pid 1 (result = -1)
Jul 15 09:48:42 mymachine companionappd[69155]: (Error) WatchKit:
  SPCompanionAppServer.m -[SPCompanionAppServer
  _launchSockPuppetAppForCompanionAppWithIdentifier:options:completion:]:1176
  Installation of com.mydomain.myapp.watchkitapp failed

I believe this was caused by naming my WatchKit App "Watchkit App" instead of "myapp WatchKit App" when adding the new target to my existing iOS 9 beta swift application.
To fix this, I backed up my InterfaceController.swift and Interface.storyboard files (the only files in the WatchKit App I had changed).  Deleted the WatchKit App and WatchKit App Extension groups in the project.  And, deleted the WatchKit App and WatchKit App Extensions targets.
I re-added the WatchKit target with the correct name of "myapp WatckKit App".  Overwrote the new files with my backup files.  Now the application and watch application run fine.


text:
Q: Errors and warnings with cassandra and cqlsy When I run cassandra i get the output like this:
D:\STUDIA\cassandra\apache-cassandra-3.11.9\bin>cassandra
Detected powershell execution permissions.  Running with enhanced startup scripts.
*---------------------------------------------------------------------*
*---------------------------------------------------------------------*

    WARNING!  Automatic page file configuration detected.
    It is recommended that you disable swap when running Cassandra
    for performance and stability reasons.

*---------------------------------------------------------------------*
*---------------------------------------------------------------------*
Failed 64-bit check. Re-running to get version from 32-bit
*---------------------------------------------------------------------*
*---------------------------------------------------------------------*

    WARNING! Detected a power profile other than High Performance.
    Performance of this node will suffer.
    Modify conf\cassandra.env.ps1 to suppress this warning.

*---------------------------------------------------------------------*
*---------------------------------------------------------------------*
Cassandra 3.0 and later require Java 8u40 or later.

and when i type cqlsh:
D:\STUDIA\cassandra\apache-cassandra-3.11.9\bin>cqlsh
Connection error: ('Unable to connect to any servers', {'127.0.0.1': error(10061, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Nie mo\xbfna nawi\xb9za\xe6 po\xb3\xb9czenia, poniewa\xbf komputer docelowy aktywnie go odmawia")})

it says that
"Can not
make connections because the target computer is actively refusing it"

A: The error indicates that Cassandra is not running. You will need to check the Cassandra system.log to get an idea of the cause.
It may have failed to start or shutdown. It isn't possible to know why without looking at the logs. Cheers!


text:
Q: Gradle compileOnly vs implementation - code obfuscation (method parameter not visible) there is a difference in obfuscation depending on usage in android library dependencies with 'implementation' and 'compileOnly'. Please read samples below, both have same Gradle and R8 configuration.
Env configuration:

Project type: Android Library (aar)
Gradle version: 7.4.2
Gradle plugin: 7.2.1
Kotlin 1.5.31
Obfuscation: R8

R8 config (MyClass is a part of this package):
-keep public class com.module.api.** {
 public <methods>;
 public <fields>;
}

Sample #1 build.grade (valid - method parameter is visible):
dependencies{
 implementation "com.other.module"
}

Outout code in aar:
public final class MyClass public constructor() {
 public final fun someMethodWithParameter(visibleId: kotlin.String): kotlin.Unit {}
}

Sample #2 build.grade (invalid - parameter has different name)
dependencies{
 compileOnly "com.other.module"
}

Outout code in aar:
public final class MyClass {
 public MyClass() {}

 //parameter should has name 'visibleId' and class should be in Kotlin!
 public final void someMethodWithParameter(String var1) {}
}


text:
Q: How to return datetime group of categorised period into a new pandas column? I have a pandas dataframe that looks like this:
Date               Interval
31/8/20 9:22:07    Period 1
31/8/20 7:20:35    Period 9
31/8/20 7:18:24    Period 9
31/8/20 7:13:49    Period 10
31/8/20 7:07:05    Period 10
31/8/20 6:46:54    Period 11
31/8/20 0:26:16    Period 37
30/8/20 23:52:20   Period 39
30/8/20 23:50:04   Period 39

Which is generated by the following code:
# CONVERT TO DATETIME
df['Date'] = pd.to_datetime(df['Date'])

# SORT BY DATE VALUES
df = df.sort_values(by=['Date'], ascending=False)

# GROUP INTO 15 MINUTE INTERVALS
s = df.groupby(pd.Grouper(freq='15min', key='Date')).ngroup(ascending=False).add(1)
df['Interval'] = 'Period ' + s.astype(str)

I would like to add a new column into my dataframe to show the datetime interval by which the 'Period' values were generated. Such that my output should look like this:
Date               Interval     15_Min_Interval_Period_Belongs_To
31/8/20 9:22:07    Period 1     31/8/20 9:15:00
31/8/20 7:20:35    Period 9     31/8/20 7:15:00
31/8/20 7:18:24    Period 9     31/8/20 7:15:00
31/8/20 7:13:49    Period 10    31/8/20 7:00:00
31/8/20 7:07:05    Period 10    31/8/20 7:00:00
31/8/20 6:46:54    Period 11    31/8/20 6:45:00
31/8/20 0:26:16    Period 37    31/8/20 0:15:00
30/8/20 23:52:20   Period 39    30/8/20 23:45:00
30/8/20 23:50:04   Period 39    30/8/20 23:45:00

I've tried:
s2 = df.groupby(pd.Grouper(freq='15min', key='Interval')).get_group()

to no avail.
Thank you for your help.

A: Use Series.dt.floor:
df['15_Min_Interval_Period_Belongs_To'] = df['Date'].dt.floor('15Min')

print (df)
                 Date   Interval 15_Min_Interval_Period_Belongs_To
0 2020-08-31 09:22:07   Period 1               2020-08-31 09:15:00
1 2020-08-31 07:20:35   Period 9               2020-08-31 07:15:00
2 2020-08-31 07:18:24   Period 9               2020-08-31 07:15:00
3 2020-08-31 07:13:49  Period 10               2020-08-31 07:00:00
4 2020-08-31 07:07:05  Period 10               2020-08-31 07:00:00
5 2020-08-31 06:46:54  Period 11               2020-08-31 06:45:00
6 2020-08-31 00:26:16  Period 37               2020-08-31 00:15:00
7 2020-08-30 23:52:20  Period 39               2020-08-30 23:45:00
8 2020-08-30 23:50:04  Period 39               2020-08-30 23:45:00


text:
Q: What type of data protocol is inside ChannelData when webrtc completely uses turn relay? What type of data protocol is inside ChannelData when webrtc completely uses turn relay?
Does not look like SRTP;

A: The ChannelData messages will contain all the messages you would see on a non-TURN WebRTC call. The WebRTC Agent sends the same messages as usual. Only the ICE Agent is aware that it is communicating via TURN.
Inside the ChannelData messages you will have STUN (Used by ICE) DTLS and SRTP.


text:
Q: Поиск наиболее повторяющихся значений по фильтру Есть массив с 2 колонками

Как составить цикл или что применить, чтобы выявить какое значение из колонки 2 с каким другим значением из колонки 2 чаще всего встречается вместе в одинаковом значении параметра колонки 1.
Например из представленной таблицы для значения 600814: с ним вместе 3 раза встречается значение 24678, и 2 раза встречается значение 24754.
Как это оформить чтобы оно автоматически искало такие совпадения, и сортировало по убыванию кол-ва частоты встречи вместе.

A: Можно воспользоваться Counter и defaultdict, чтобы можно было создавать словарь словарей. А ещё Counter умеет сортировать ключи по убыванию частот методом most_common(). Плюс обеих структур состоит в том, что перед добавлением ключа не надо проверять его наличие в словаре, как это делается в dict-е.
Вот прототип кода с использованием этих структур:
from collections import Counter, defaultdict

first_col_dict = defaultdict(dict)

for first, second in zip(first_col, enumerate(second_col)):
    i, elem = second
    if first_col_dict[first][elem] is None:
        first_col_dict[first][elem] = Counter()

    if i - 1 >= 0:
        first_col_dict[first][elem][second_col[i - 1]] += 1
    if i + 1 < len(first_col):
        first_col_dict[first][elem][second_col[i + 1]] += 1

A: Если "скормить" в Counter кортежи, то он сам всё сделает:
from collections import Counter

arr = [(123213123, 1), (123213123, 2), (123213123, 1), (232132123, 1), (232132123, 2)]

Counter(arr)

Вывод:
Counter({(123213123, 1): 2,
         (123213123, 2): 1,
         (232132123, 1): 1,
         (232132123, 2): 1})


text:
Q: how do I know when/where to invoke the overridden method of the super class This question occured to me while programming a Android application,
but it seems to be a general programming question more.
The situation is, I am extending (subclass-ing) an class from a library, and overriding a method. how do I know if I should invoke the method of super-class? and when? (in the beginning of the overridden method or in the end?)
For example, I am overriding the method "public boolean onCreateOptionsMenu(Menu menu)" from class "Activity" in Android platform. And I saw someone write "return super.onCreateOptionsMenu(menu)" in the end of the method, in an example. But how do I know it should be done this way? and it is correct or not? what's the difference if I begin my method with "super.onCreateOptionsMenu(menu)"?
BR,
Henry

A: I don't think you can answer this question in the abstract: it depends on the behavior of the superclass method you're overriding.
Depending on circumstances, it may be appropriate to:

*

*call super first

*call super last

*handle some cases yourself (customizations), call super for the rest

*never call super

Hopefully the documentation for the particular class you're overriding will tell you if/when it's necessary to call super.

A: Unfortunately, there is no rule for this. You need to refer to the API docs and call super if the docs say you need to.
One hint as to whether you'll probably need to or not in Android's case is if the method you're overriding is one of the lifecycle methods. In this case, you can be fairly certain that you need to call super.

A: These are valid questions, but unfortunately there is no general rule to follow here.
Whether or not you need to call super method depends on the fact if the super method does something that needs to be done. In other words: are you extending or replacing the overridden method? A good API documentation of the class should give you the answer. Also, libraries often follow some conventions to make it clear how to use them.
The answer to the question where to place the super call depends on when you want to execute you're extension. Does it need to run before or after the super method? Most often you first call super and then do something extra. But if you need to prepare something for the super method, for example modifying some object state or manipulate the arguments, you place the code before the super call. Again, the API documentation should give you the answer here.

A: Android will in most of the cases cause a exception if you forget to call super.
I would trust that you don't have to call super if you don't do it and it doesn't throw.
In the google groups discussions some best practices for the lifecycle methods evolved(They are not officially backed by data but used by many programmers):

*

*If you are in a creating method like
onCreate, onResume, etc. call super
as the first statement. Thus you can be sure that everything that has to be prepared from the superclass is prepared.

*If you are in a closing method like onSaveInstanceState, onPause call super last. Now you could be sure that nothing gets removed or changed to a bad state before you got everything done.

A: You are not required to call the super.method(), you call it only when you need it where you need it.

A: When you override a method in a child class then it depends on the type of the instance on which you are calling that method.
for example:
   Class Animal{
        public eat(){
           //..
        }
   }

   Class Dog extends Animal{
        public eat(){
           //..
        }
  }

now if you say new Dog().eat()
it executes Dog's eat method.

if you say new Animal().eat()
it executes Animal's eat method.

And you may have code like this
       Animal a = new Dog();
       a.eat();

which again executes the Dog's eat method as the actual instance is of the type Dog.


text:
Q: Prove that there are an equal number of local maxima and local minima
Suppose that the temperature on the equator is a differentiable function $T(x)$ such that $T'(x)=0$ has only finitely many solutions. Prove that there are an equal number of local maxima and local minima.

$T(x)$ is $2\pi$-periodic as it is a temperature function on the equator. Hence we only need to consider the interval $[0,2\pi]$. Since $T(x)$ is differentiable, $T(x)$ is continuous. Hence, by the Extreme Value Theorem, $T(x)$ attains its maximum and minimum values on $[0,2\pi]$. Since $T(x)$ is differentiable on $[0,2\pi],$ by Fermat's Theorem, its maximum and minimum values either occur at endpoints or points where $T'(x)=0$. We now show that between any two consecutive local maxima, there is a local minima.
Suppose $x_1$ and $x_2$ are such that $T(x_1)$ and $T(x_2)$ are consecutive local maxima. Then $\exists \delta >0$ such that $x_1 < x < x_1 + \delta \Rightarrow T'(x_1) < 0$ and $\exists \delta_2 >0$ such that $x_2 -\delta < x < x_2\Rightarrow T'(x_2) >0.$ Pick $c\in (x_1, x_1 + \delta)$ and $c_2 \in (x_2-\delta, x_2)$ such that $c_2 > c$. Consider the interval $[c,c_2]$. Since $T(x)$ is continuous on this interval, by the Extreme Value Theorem, it must attain its maximum and minimum values on that interval. We show that the minimum value is not attained at the endpoints. Since $T'(c) < 0,$ we have that $\lim\limits_{h\to 0^+}\dfrac{T(c+h)-T(c)}{h} < 0\Rightarrow T(c+h) < T(c)$, and so $T(c)$ is not a minimum. Similarly, $T'(c_2) >0$, so $\lim\limits_{h\to 0^-}\dfrac{T(c_2+h)-T(c)}{h} >0\Rightarrow T(c_2+h)-T(c) < 0$, so $T(c_2)$ is not a minimum either. Therefore, the minimum is attained in $(c,c_2)$. By similar logic, we can show that there is a maximum between two consecutive local minima. Hence there must only be one local minimum between two consecutive local maxima (otherwise those maxima would not be consecutive). Hence if $T(x)$ only attains one local maximum in $[0,2\pi]$, it only attains one local minimum. As well, if we let $n$ be the number of local maxima in $[0,2\pi]$ and $m$ be the number of local minima, then $|n-m| \leq 1$ as otherwise there will be two consecutive local maxima without a local minima in between or vice versa.

Is there a shorter proof of this?
Isn't there a shorter proof of this?


text:
Q: Chrome is opening new Window instead of new tab when Ctrl+N is pressed I am using Chrome version 44.0.2403.155 m in Windows 7 when I press Ctrl+N it opens new window instead of new tab. How to open new tab in same window with keyboard?

A: Ctrl+T opens a new tab. Ctrl+N is supposed to open a new window.

A: Ctrl+T opens a new Tab. Ctrl+W closes it. These work in all browsers.
Here are more shortcuts for Chrome.


text:
Q: jsonResponse.getJSONArray not working I'm trying to fetch data from MySQL database which is on web server.
my goal is to retrieve array of location data which is already on MySQL database.
I'm getting this array of data from server,but I cant convert it from jsonResponse.getJSONArray to JSONArray object.
private void setUpMap() {
    Response.Listener<String> responseListener=new Response.Listener<String>(){

        @Override
        public void onResponse(String s) {
            try {
                JSONObject jsonResponse=new JSONObject(s);
                boolean success=jsonResponse.getBoolean("success");
                if(success){             //this is true, and also all the data is arrived
                    JSONArray jsonArray = jsonResponse.getJSONArray("data");   //after this line it doesnt work,it doesn't enter in for loop
                    JSONObject jsonObject;
                    for(int i=0;i<jsonArray.length();i++){
                    jsonObject=jsonArray.getJSONObject(i);
                    String mac=jsonObject.getString("mac");
                    String android_id=jsonObject.getString("android_id");
                    Double latitude=jsonObject.getDouble("latitude");
                    Double longitude=jsonObject.getDouble("longitude");
                    if(!isMarkerOnArray(markerCollection,latitude,longitude))
                    markerCollection.add(mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude))));
                    }

                }
                else{
                    AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
                    builder.setMessage("Downloading position failed")
                            .setNegativeButton("retry",null)
                            .create()
                            .show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    DownloadPosition downloadPosition=new DownloadPosition(responseListener);
    RequestQueue queue= Volley.newRequestQueue(MapsActivity.this);
    queue.add(downloadPosition);

}

debug
this is my php script
`<?php
$con=mysqli_connect("","","","");
$sql="SELECT * FROM positions";
$result=mysqli_query($con,$sql);
$response["data"]=array();
$data=array();
$data["success"]=false;
$i=0;
while($rs = mysqli_fetch_assoc($result)){
    $data["success"]=true;
    $data[$i] = array('id'=>$rs['id'],'mac'=>$rs['mac'], 'android_id'=>$rs['android_id'], 'latitude'=> $rs['latitude'],'longitude'=> $rs['longitude']);
    $i++;
}
echo json_encode($data);
mysqli_close($con);
?>`

so my question is how can I get JSONArray object from jsonResponse.getJSONArray() ?
edit:
this is json

A: You get the JsonObject in Response which contains the boolean and JsonObject.
So,Change in your PHP code,
$result=array();
while($rs = mysqli_fetch_assoc($result)){
      $result[$i] = array('id'=>$rs['id'],'mac'=>$rs['mac'], 'android_id'=>$rs['android_id'], 'latitude'=> $rs['latitude'],'longitude'=> $rs['longitude']);
     $i++;
}

$data['data']=$result;
echo json_encode($data);


text:
Q: Firebase android proxy setting I have made an android app https://play.google.com/store/apps/details?id=com.confesco.maggi
which works with firebase as database which works well when I use 3G net.The problem occurs when I use it under a proxy of our college it doesnot get connected to the database.Is there any way I can get around with this problem.Thanks in advance.

A: There is currently no workaround for using the Android client over a proxy, sorry. I've put this on the Firebase feature list and hopefully we can address it in the near future.
(Answer copied from a previously posted comment)

A: This article seems to suggest that it is possible. It applies the standard Java proxy directives and one specific one for Google API:
System.setProperty("https.proxyHost", "localhost");
System.setProperty("https.proxyPort", "3128");
System.setProperty("com.google.api.client.should_use_proxy", "true");


text:
Q: When align 8 bytes is not enough? I am trying to implement pimpl without heap (adapt from a SO question).
I think I should reserve char[] myself, and hardcode alignment = 8.
However, I am very new to C++ alignment.  I am afraid that 8 is not enough.
My study
After some reading, I understand that alignof is maximum size of internal field.
I have experimented :-
struct A {   //size = 16     alignof = 8 (max{4,1,8})
    int n;         //address = [0,4)
    bool flag;     //address = [4,5)
    double k;      //address = [8,16)
};
struct B{    //size = 24     alignof = 8 (max{A,1})
     A a;      //address = [0,16)
     char c;   //address = [16,24)    24=16+8(align)
};

From the experiment, I think alignment for my pimpl should be = 8 (conservative).
It should be safe as long as maximum primitive size is 8.
Reference: largest primitive type has at least 8 bytes.    (but let's assume it is actually 8 bytes)
Question
Are there any cases that I should set alignment > 8?
In other words, is 8-bytes enough for all practical cases?
I believe that the answer is "it is safe", but a SO question confused me.
Here is a part of the question :-

The "memset_16aligned" function requires a 16byte aligned pointer passed to it, or it will crash.

I have also read :-

*

*why does size of the struct need to be a multiple of the largest alignment of any struct member

*warning C4316: object allocated on the heap may not be aligned 16   <-- align 16 again!

*Does alignas affect the value of sizeof?


text:
Q: Which one to choose Type-I, Type-II, or Type-III ANOVA? I don't understand what the difference is between TypeI and TypeIII?
Since my background is not very mathematics, it's very difficult for me to understand this mathematical notation;
Type I SS: SS(A) SS(B|A) SS (AB|A, B)
Type II SS: SS(A|B) SS(B|A) SS (AB|A, B)
Type III SS: SS (A|B, AB) SS (B|A, AB) SS (A*B|A, B)?
I want to check the interaction between my two factors (genotype*FuncBIN), but my output comes as Type II ANOVA with interaction. Is this normal?
structure( list(genotype = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("WT", "Mut2", "Mut1" ), class = "factor"), FuncBIN = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("Mitochondria ", "Golgi", "ER"), class = "factor"), k = c(0.2, 0.3, 0.4, 0.5, 0.3, 0.2, 0.5, 0.6, 0.7, 0.4, 0.6, 0.9, 0.2, 0.3, 0.5, 0.4, 0.2, 0.3, 0.5, 0.6, 0.8, 0.5, 0.4, 0.6, 0.2, 0.3, 0.1)), .Names = c("genotype", "FuncBIN", "k"), class = "data.frame", row.names = c(NA, -27L) )

library(car)
library(lsmeans)
library(multcomp)
fit <- lm(k ~ genotype + FuncBIN + genotype*FuncBIN, df)
plot(fit) shapiro.test(residuals(fit))
Anova(fit)
lsmip(fit, FuncBIN ~ genotype)
lsmeans(fit, pairwise ~ genotype)[[2]]
fit.tukey <- lsmeans(fit, pairwise ~ genotype | FuncBIN)[[2]]
fit.tukey
cld(fit.tukey)

How can I run an ANOVA with interaction followed my Tukey PostHOC?

A: In a balanced design, all three of these model types will yield the same results. With unbalanced data, you will get different results for the main effects but not the interaction term, assuming you only have a two-way interaction (as in your example). The general advice is to use a Type II sums-of-squares model for unbalanced designs. This model tests the main effects without the interaction term. The difference comes down to how you weight each mean or cell of the factorial. In a Type III model, each cell of the factorial gets the same weight (even if some have smaller sample sizes). In a Type II model, each observation gets the same weight. In most situations (but not all!) the latter is more defensible.
If you are only interested in the interaction, then this decision doesn't matter. The sum-of-squares for the interaction will be the same for all three model types.
I just checked and your design is balanced. As such you can use Type III SS. Built-in R functions will work just fine here.
fit <- aov(k ~ genotype*FuncBIN, data=df)
summary(fit)
TukeyHSD(fit)


text:
Q: SPARQL 'for-loop' in query I have a simple SPARQL query:
SELECT DISTINCT ?class1 ?class2
    WHERE {
        ?class1 :child ?attribute1 .
        ?class2 :child ?attribute2 .
        ?attribute1 :objectName ?name1 .
        ?attribute2 :objectName ?name2 .
        FILTER (?name1 = ?name2)
    }

In an RDF graph where one of these 'classes' can have multiple children. What I want to do is, find duplicate classes, where duplicate means that all of the children (identified by objectName) in one class are in another class too.
What it does is, return every class where at least one child exists in another class too.
So I'm looking for some kind of iterating over all children of each class, but I couldn't find a way yet. Would be great if someone could help.
Thanks

A: Note that SPARQL is a declarative language, not an imperative one, so there's no concept of iterating over things. You could do that in a API into an RDF store, but at least in theory expressing it in SPARQL will be more efficient.
I think what you need to do is find all the combinations of classes, and subtract the ones where some objectName differs.
The following is totally untested!
SELECT DISTINCT ?class1 ?class2
WHERE {
   ?class1 :child ?attribute1 .
   ?class2 :child ?attribute2 .
   MINUS {
      ?attribute1 :objectName ?name1 .
      ?attribute2 :objectName ?name2 .
      FILTER (?name1 != ?name2 && ?attribute1 = ?attribute2 )
   }
}

There's a very small chance that's correct :) but it should give you some inspiration.

A: Here's some sample data with four classes.  The first and second classes contain children with names "name1" and "name2".  The third class contains "name1" and "name3", and the fourth contains "name3" and "name4".  The fifth class contains all the children of the fourth, as well as "name5".  So, the first and second classes are equivalent, and the fourth class is a subclass of the fifth.
@prefix : <http://example.org/> .

:class1 :child [ :objectName "name1" ] ,
               [ :objectName "name2" ] .

:class2 :child [ :objectName "name2" ] ,
               [ :objectName "name1" ] .

:class3 :child [ :objectName "name1" ] ,
               [ :objectName "name3" ] .

:class4 :child [ :objectName "name3" ] ,
               [ :objectName "name4" ] .

:class5 :child [ :objectName "name3" ] ,
               [ :objectName "name4" ] ,
               [ :objectName "name5" ] .

Your description sounds like you're actually looking for subclasses, since you mention classes all of whose children are also in another class.  As such, this SPARQL query should take care of finding subclass relationships:
prefix : <http://example.org/>

select distinct ?c1 ?c2 where {
  ?c1 :child [] .
  ?c2 :child [] .
  NOT EXISTS { ?c1 :child [ :objectName ?name ] .
               NOT EXISTS { ?c2 :child [ :objectName ?name ] } }
  FILTER( !sameTerm( ?c1, ?c2 ) )
}

The nested NOT EXIST patterns ensures that the only classes we select are such that there does NOT EXIST an element ?c1 which does NOT EXIST in ?c2.  That is, we reject any pairs of sets where there is an element in ?c1 that is not in ?c2;  we reject any ?c1,?c2 pair where ?c1 is not a subset of ?c2, so we're keeping just the ones where ?c1 is a subset of ?c2. The sameTerm filter removes the trivial ?c,?c pairs, since everything will be subset of itself. Using Jena's command line ARQ tools, we get these results:
$ arq --data data.n3 --query query.sparql
---------------------
| c1      | c2      |
=====================
| :class4 | :class5 |
| :class2 | :class1 |
| :class1 | :class2 |
---------------------

As expected, :class1 and :class2 are each subsets of the other, and :class4 is a subset of :class5.
If you want equivalent classes, it is sufficient to just a second NOT EXISTS to ensure that ?c2 is also a subset of ?c1:
prefix : <http://example.org/>

select distinct ?c1 ?c2 where {
  ?c1 :child [] .
  ?c2 :child [] .
  NOT EXISTS { ?c1 :child [ :objectName ?name ] .
               NOT EXISTS { ?c2 :child [ :objectName ?name ] } }
  NOT EXISTS { ?c2 :child [ :objectName ?name ] .
               NOT EXISTS { ?c1 :child [ :objectName ?name ] } }
  FILTER( !sameTerm( ?c1, ?c2 ) )
}

With this query, we get back just :class1 and :class2:
$ arq --data data.n3 --query query.sparql
---------------------
| c1      | c2      |
=====================
| :class2 | :class1 |
| :class1 | :class2 |
---------------------


text:
Q: Input string was not in a correct format in IJavasScriptExecutor.ExcuteScript So I want to have filter for spans that have certain text.
The jquery works find in console on chrome, but why when I use excuteScript it bring out System.FormatException: Input string was not in a correct format ?
JsExecutor.ExecuteScript(string.Format("$(\"h3:contains('{0}')\").closest(\"div.form-group-container\").find(\"span:contains('{1}')\")" +
                ".filter(function(){return $(this).text().toLowerCase()===\"{1}\";})" +
                ".closest(\"tr\").find(\"input\").click()", loonelementenType, excludedLoonelementen));

When debug I notice the .filter(function(){return $(this).text().toLowerCase()===\"{1}\";}) is the one that brought out System.FormatException


text:
Q: What are the differences between "receptacle" and "container"? Generally, both "receptacle" and "container" refer to an object that contains some other object(s). What are the differences between these two words? Do they differ in meaning, usage, or origin?
I searched "difference between receptacle and container" in Google but the only two relevant results ([1], [2]) can both be summarized as "They are basically the same thing".

A: Receptacle <-- receives something
Container <-- contains something
Sender <-- sends something
A receiver uses his receptacle to receive something. Then he puts it into his container (memory) to keep it contained and safe.
http://www.dictionary.com/browse/receptacle

1375-1425; Middle English (< Old French) < Latin receptāculum reservoir, equivalent to receptā(re) to take again, receive back (frequentative of recipere to receive ) + -culum -cle2

A: An instructive synonym for receptacle in an electrical sense is socket (discussed in depth here under difference between "socket" and "outlet").  Socket can't usually be a synonym for container.
A major part of the difference in use is to do with the purpose. You can call a litter bin a trash container or a trash receptacle. In the former case you're emphasising storage, in the latter, you're emphasising acceptance.
You may have been a little unlucky with your choice of dictionary.  Merriam-Webster has "one that receives and contains something", Cambridge has "a container used for storing or putting objects in" (emphasis mine in both cases).

A: A trash bin may be called a trash receptacle or a trash container, but a power receptacle would not be called a power container. The "receiving" done by a power receptacle, in my connotation is that it receives the plug from the device to be powered.
There is some overlap but, as others have mentioned, the root of "receptacle" is "receive" and the root of "container" is "contain".
Google Search

A: You could look to the common phrase, "place the item in the proper receptacle", and derive that receptacle is a more specified type of container; a container designated to receive a particular item. Consider where trash is sorted by different materials; glass goes into the glass receptacle, paper in the paper receptacle, etc.

A: The difference is in what the object is used for.  When I see "container" I think of something people put stuff into that the want to store for some indefinite period of time, then remove and use.  When I see "receptacle" I think of something that people put stuff into for a specific reason, that someone else is going to remove to use for whatever purpose.
Examples:
I put my leftover dinner in a plastic container so I can take it to work tomorrow.
I dropped the empty can in the aluminum receptacle.
"Receptacle" can also refer to where you plug electrical cords, but, in AE at least, it is more often called an "outlet".


text:
Q: "Listening" to AJAX calls from Capybara / Selenium - Rails I have an app which makes AJAX calls on certain events (e.g. .click). Is there a way to "listen" to real AJAX requests from feature specswith Capybara / Selenium?
I tried the Teaspoon gem, but apparently its only allowing accessing fixture URLs (as per this SO).

A: No you can't listen to events in the browser from Capybara, you can only look for changes that occur as a result of those events.  ie. If clicking a button makes an ajax request and then changes part of the page, check for the element that is added/removed from the page.


text:
Q: Counting the number of shapes in an image I am trying to count the number of shapes in an image of a board game. For some reason, the count is completely off.
I have been using code from the web (for example, https://www.pyimagesearch.com/2016/02/01/opencv-center-of-contour/)
I only need opencv for this, has anyone else had this problem, and how do I limit this to only the squares that I am interested in?
This is the same image as below but the background is now black. Now there are more center-dots than necessary all around the edge of the image.
I want the center dot to appear in every square on the board

A: I used paint to remove the edges of the numbers that were interrupting the white lines of each box. I assume that those numbers and dots were things that you added and not part of the original image.
Here is the image after my modifications

I made a mask by looking for white in the image. I dilated the results to get clearer separation and inverted so that each box was white.

I used findContours to get the contour of each white object in the mask. I filtered the contours by size to get rid of the arrows, letter bits, and the background of the image. From there I drew the centroid of each remaining contour.

import cv2
import numpy as np

# load image
img = cv2.imread("chutes_n_ladders.png");

# mask
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
mask = cv2.inRange(gray, 240, 255);

# dilate and invert
kernel = np.ones((3,3), np.uint8);
mask = cv2.dilate(mask, kernel, iterations = 1);
mask = cv2.bitwise_not(mask);

# contours
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);

# remove very large and very small contours
filtered = [];
low = 1000;
high = 100000;
for con in contours:
    area = cv2.contourArea(con);
    if low < area and area < high:
        filtered.append(con);

# draw centers of each
print("Shapes: " + str(len(filtered)));
for con in filtered:
    M = cv2.moments(con);
    cx = int(M['m10']/M['m00']);
    cy = int(M['m01']/M['m00']);
    cv2.circle(img, (cx, cy), 10, (0, 200, 100), -1);

# show
cv2.imshow("Image", img);
cv2.imshow("Mask", mask);
cv2.waitKey(0);


text:
Q: Java: ArrayList, String manipulation and Parsing I am writing an application that stores references for books, journals, sites and so on. I mean I have already done most.
What I want is a suggestion regarding what is the best way to implement above specs?
What format text file should I use to store the library? Not file type but format. I am using simple text file at the moment. But planning to implement format as in below.
<book><Art of Human Hacking><New York><2011><1>
<journal><Achieving Maximum Speed In 802.11n><London><2009><260-265>

1st tag <book> and <journal> are type identifier. I have used ArrayList. Should I use multi dimensional ArrayList and store each item like below?
[[Art of Human Hacking,New York,2011,1][Achieving Maximum Speed In 802.11n,London,2009,260-265]]

I have used StringTokenizer and I cannot differentiate spaces. How do I fix this?
I have already implemented all features including listing all, listing unique, searching, editing, removing, adding. But everything is done to content without spaces.

A: You should use an existing serializer instead of writing your own, unless the project forbids it.
For compatability and human readability, CSV would be your best bet.  Use an existing CSV parser to get your escaping correct (not that hard to write yourself, but difficult enough to warrant using an existing parser to avoid bugs).  Google turned up: http://sourceforge.net/projects/javacsv/
If human editing is not a priority, then JSON is also a good format (it is human readable, but not quite as simple as CSV, and won't display in excel for instance).
Then you have binary protocols, such as native Java serialization, or even Google protocol buffers.  These may be faster, but obviously lose the ability to view the data store and would probably complicate your debugging.