text:
Q: Autoresize parent container with drag and drop I have three containers which are automatically resized when inner div is resized. Now I want to add drag feature to my code and keep the container auto-resize option like it is in my example. How to do this?
I have found several examples but none of those is working with multiple containers.
$(function(){
    $('.inner').resizable({
    });

  /* This is not working
      $('.inner').draggable({
    });

    */

});

Jsfiddle

A: Bind events in the same selector.
$('.inner').resizable({}).draggable({});

See in your edited fiddle.
EDIT:
Use the containment: parent option on both divs to constraint movement like in  this one.
EDIT 2:
This should solve your problem. A callback function to control outer div height is called on resize.
EDIT 3:
This last fiddle should match all you request. I took your fiddle in comment and edited it.

A: When you call draggable function, draggable objects position property will set to absolute, So you need to write new function for resizing and dragging.
You can detect dragging statement with mousemove and mouseup event.
mousemove event for when object is on dragging, mouseup event for after drag work.
resize event is provided by default.
Check this fiddle


text:
Q: Python import syslog on windows I have a python script that is normally run on a unix machine, I am trying to run it on windows. The one snag I have run into is the module syslog. Is there a way that anyone knows that I can get around this on a windows machine, is there an equivalent package for windows? Running python 2.7.

A: You can create syslog.py and put it somewhere in a python path.
You also can customize it to actually write messages down or send them over network.
My version below. (It misses few functions and constants, so you may need to add some more):

import sys

LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, \
LOG_NOTICE, LOG_INFO, LOG_DEBUG = range(8)

LOG_KERN, LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, \
LOG_SYSLOG, LOG_LPR, LOG_NEWS, LOG_UUCP = range(0,65,8)

LOG_CRON = 120
LOG_LOCAL0 = 128
LOG_LOCAL1 = 136
LOG_LOCAL2 = 144
LOG_LOCAL3 = 152
LOG_LOCAL4 = 160
LOG_LOCAL5 = 168
LOG_LOCAL6 = 176
LOG_LOCAL7 = 184

LOG_PID = 1
LOG_CONS = 2
LOG_NDELAY = 8
LOG_NOWAIT = 16

def syslog(message):
pass

def syslog(priority, message):
pass

def openlog(ident=sys.argv[0], logoptions=0, facility=LOG_USER):
pass

def closelog():
pass

def setlogmask(maskpri):
pass

A: The "logging" module should be ideal for what you're looking for, though it may require some rewriting of the code. It also has the advantage that logging is platform independent, so it works on both Windows and *nix, which is always handy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I'm at a loss on how to loop this? Well, before this project I knew NOTHING about jQuery. I still know basically nothing, but still.
Anyways, the end goal is to create a slider gallery. This gallery should run infinitely, with no skipping or tears. Thanks to the numerous questions I've already asked you guys, (Thanks for the help by the way.) I've got it to this point...
http://jsfiddle.net/75MDR/
But I have NO idea how to get that animation to repeat itself. I've done a little bit of research, and thought perhaps I could use the .before property to take the last image and slap it behind the other one. Perhaps something like...
$(document).ready(function() {
$("#image").animate({"margin-left":"+=400px"}, 3000, "linear");
function gallery () {
    $("#image").animate({"margin-left":"+=400px"}, 3000, "linear");
            $("image3").before( $("image") );
}
setInterval(gallery, 3000);
});

But, I have two problems with that. The firs being that that code does absolutely nothing The second is that I'm not sure how I would time it. Perhaps is there a way to check if it has left the frame?
Thanks in advanced!

A: There are several issues with your approach that you are going to need to address. Namely, you will need to address the use of better selectors; the issue of having your code properly wrapped to call;  and you will need to manage where your image is.
Use better selectors
jQuery selection is based pretty much on css selectors.
id selection
In css if you want to style an element with id="hello" then you would use #id{ color: blue; }. In jQuery if you want to target an element with id="hello" then you would use $("#hello"). See the correlation? Keep in mind, you should only use unique ids.
class selection
If you want to target more than one element, uses classes. In css if you wanted to select all the elements with class="world" then you would use .world{ background-color:yellow; }. In jQuery if you wanted to target all the elements with class="world" then you would use $('.world'). Again note the correlation.
complex selection
There are more complex selectors that you can choose. For your exact situation, I would suggest using img[class^=image] and getting rid of the ids altogether. That selector says "select all image elements which have a class that starts with image". If you wanted to use this selector for css, you would use img[class^=image]{ position: relative; }. If you wanted to use this selector for jQuery, you would use $('img[class^=image]').animate({});. Sorry to be repetitive, but again.. the correlation :P
Wrap your code
naming conventions
What is it that you want to do? Can you state it in a few words, if so, make a function with that name.
function slideGallery(){}

define your goals
Then go through your function and define the process you wish to handle. If you really want to accomplish the goals defined in your question, then there are some non trivial aspects you will need to take into consideration.
function slideGallery()
{
 //will animation cause an image to leave the screen? (hint: think collision detection)
 //if so, clone image leaving screen and place it at the start (hint: $(element).clone())
 //animate all images
 //remove image which left screen (hint: $(element).remove())
}

Where is your image?
Keeping track of your image is definitely non trivial.
viewport
First you have to be aware not specifically what the size of the document is, but what the size of the viewport is. If you take into consideration scrollbars this can become a little hard. However, since you can push the image off the screen at will that isn't an issue. All you really need is to ask jQuery what the window width is.
var windowWidth = $(window).width();

image location
Next you need to keep track of where your image is as it animates. This can be done with jQuery's offset.
//target current image animating
var currentImage = however you decide to access the image
var currentImageOffset = $(currentImage).offset().left;
if( currentImageOffset + animationWidth > windowWidth ) //collision will occur

image placement
Now you need to do is keep track of where the first image started off so that when you clone all of your images, you can place that one there. This means gathering the first images data before everything begins to animate.
var baseImagePosition = $('.image').offset().left;

Putting all of these things together should give you a scrolling gallery.


text:
Q: how to communicate with system pop-up using selenium? im using selenium for automation, and in some part of the process im automation I get a system-pop up like this:

And I want to click on "ok", how can I do this?
thanks
ANSWER:
How to handle Javascript Alert/pop up window in selenium webdriver

A: Autoit provides windows GUI interaction.

A: Try AppleScript on macOS. It can handle the system pop-up.
tell application "System Events" to tell process "NotificationCenter"
    click last item of windows
end tell

The example is how to click the system pop-up.
Maybe you can modify it for using on your case.


text:
Q: How to display polygon with apple's KML viewer sample code I'm creating an app which shows multiple overlays on a map, and you can enable or disable each 'layer'. I'm using Apple's KMLParser class as demoed in WWDC 2010 session 127.
Up till now, I've been displaying paths. When I first tried to do this, I exported direct form google earth and it didn't like it (Apple's parser likes the KML in a very specific format). So what I did was to copy the coordinates from google earth's code, to the apple one included in the KMLViewer project (keeping all the surrounding tags the same).
My question to anyone who knows - how do you do this with polygons?
Here is the google earth code for my polygon:
<Polygon>
    <tessellate>1</tessellate>
    <outerBoundaryIs>
        <LinearRing>
            <coordinates>
                <!-- My Coords here -->
            </coordinates>
        </LinearRing>
    </outerBoundaryIs>
</Polygon>

KMLParser won't display anything for that.

Just for reference, here are the differences between a google earth path and the apple-supported path:
GOOGLE EARTH:
<Placemark>
    <name>A path</name>
    <styleUrl>#msn_ylw-pushpin</styleUrl>
        <LineString>
        <tessellate>1</tessellate>
        <coordinates>
            <!-- My Coords Here -->
        </coordinates>
    </LineString>
</Placemark>

APPLE SUPPORTED:
<Placemark>
      <name>A path</name>
      <GeometryCollection>
            <LineString>
                  <coordinates> <!-- My Coords Here --> </coordinates>
            </LineString>
      </GeometryCollection>
      <styleUrl>#roadStyle</styleUrl>
</Placemark>

If anyone could tell me how to get KMLViewer to work with polygons that would be great!
Thanks in advance

A: After hours of experimenting and scouring the google docs I've figured it out:
Just for reference here is how it's done:
<Placemark>
    <name>MyPoly</name>
    <styleUrl>#mypolystyle</styleUrl>
    <Polygon>
        <outerBoundaryIs>
            <linearRing>
                <coordinates>
                    <!-- My Coords Here -->
                </coordinates>
            </linearRing>
        </outerBoundaryIs>
    </Polygon>
</Placemark>


text:
Q: Empirical probability with boost histogram I have a boost::histogram with 100 bins over the range [-3.5,3.5]. I fill it with a data vector qp. Since I work with periodic BC all the values of q in qp are in [-3.5,3.5].
auto h = boost::histogram::make_histogram(boost::histogram::axis::regular<>(100, -3.5, 3.5));
for (auto&& value : qp)
    h(value.first);

For security I count all points in the bin with
int samplesize = 0;
for (auto&& it : indexed(h))
    samplesize += *it;

I prepare the data for the plot
for (auto&& it : indexed(h)) {
    const auto bin = it.bin(0_c);
    double xaxis = bin.lower();
    double density = *it / samplesize;
    const std::pair<double, double> paar = std::make_pair(xaxis,density);
    printToStream(file, paar);
}

The result confuses me. It should be a normalized probability distribution, but it is definitely not (the values on the y-axis are way to low)

Is there a boost method with which I automatically get a (normalized) relative frequency?

A: You need to divide by the width of the bin. So you need to modify the density:
double density = *it / bin.width() / samplesize;

Here's the complete code in boost-histogram's Python bindings, since it was quicker to mock up:
import boost_histogram as bh
import numpy as np
import matplotlib.pyplot as plt

h = bh.Histogram(bh.axis.Regular(100, -3.5, 3.5))

data = np.concatenate([
    np.random.normal(-.75,.3, 1_000_000),
    np.random.normal(.75,.3, 750_000),
    np.random.normal(-1.5,.2, 200_000),
])

h.fill(data)

# Compute the areas of each bin (any number of axes)
areas = np.prod(h.axes.widths, axis=0)

# Compute the density (any number of axes)
density = h.view() / h.sum() / areas

plt.plot(h.axes.centers[0], density)

PS: You can use a circular axes if your data is circular


text:
Q: Link error implementing CRC 32 on a Qt project I am trying to implement checksum (CRC32) for my project.
I am getting the following Link error when I try to build the project:
mainwindow.obj:-1: error: LNK2019: unresolved external symbol "public: __cdecl Crc32::Crc32(void)" (??0Crc32@@QEAA@XZ) referenced in function "private: void __cdecl MainWindow::on_pushButton_configfile_clicked(void)" (?on_pushButton_configfile_clicked@MainWindow@@AEAAXXZ)

I added the class file to do crc32, which is implemented as follows.
CRC32.h :
#ifndef CRC32_H
#define CRC32_H

#include <QtCore>
#include <QString>
#include <QMap>

class Crc32
{
private:
    quint32 crc_table[256];
    QMap<int, quint32> instances;

public:
    Crc32();

    quint32 calculateFromFile(QString filename);

    void initInstance(int i);
    void pushData(int i, char *data, int len);
    quint32 releaseInstance(int i);
};

#endif // CRC32_H

and CRC32.cpp is:
#include "crc32.h"

#include <QFile>

Crc32::Crc32()
{
    quint32 crc;

    // initialize CRC table
    for (int i = 0; i < 256; i++)
    {
        crc = i;
        for (int j = 0; j < 8; j++)
            crc = crc & 1 ? (crc >> 1) ^ 0xEDB88320UL : crc >> 1;

        crc_table[i] = crc;
    }
}

quint32 Crc32::calculateFromFile(QString filename)
{
    quint32 crc;
    QFile file;

    char buffer[16000];
    int len, i;

    crc = 0xFFFFFFFFUL;

    file.setFileName(filename);
    if (file.open(QIODevice::ReadOnly))
    {
        while (!file.atEnd())
        {
            len = file.read(buffer, 16000);
            for (i = 0; i < len; i++)
                crc = crc_table[(crc ^ buffer[i]) & 0xFF] ^ (crc >> 8);
        }

        file.close();
    }

    return crc ^ 0xFFFFFFFFUL;
}

void Crc32::initInstance(int i)
{
    instances[i] = 0xFFFFFFFFUL;
}

void Crc32::pushData(int i, char *data, int len)
{
    quint32 crc = instances[i];
    if (crc)
    {
        for (int j = 0; j < len; j++)
            crc = crc_table[(crc ^ data[j]) & 0xFF] ^ (crc >> 8);

        instances[i] = crc;
    }
}

quint32 Crc32::releaseInstance(int i)
{
    quint32 crc32 = instances[i];
    if (crc32) {
        instances.remove(i);
        return crc32 ^ 0xFFFFFFFFUL;
    }
    else {
        return 0;
    }
}

and here is how I call crc32 on my MainWindow:
void MainWindow::on_pushButton_configfile_clicked()
{

    QString txtfilename = "demoFES_1";
    QString configFileName = QCoreApplication::applicationDirPath()+"/data/config_file/"+txtfilename+".txt";

    Crc32 crc1; // crc32 instance
    qDebug()<<"CRC32 from file: "<<crc1.calculateFromFile(configFileName);

}

Any idea what might be the source of the link error?


text:
Q: Opposite of caregiver I want to write a book about the unfair expectations of a caregiver. A caregiver refers to somebody to looks after somebody else.  What is the term for that 'somebody else'.  'Patient' doesn't seem all encompassing.

A: Dependent works whether the caregiver is paid, unpaid, related or unrelated to the disabled individual.

A: The care recipient or receiver of care or person in care seemed to get used in official language.
The cared-for perhaps.

A: Charge or ward might be appropriate to this meaning.
Patient implies that they have a medical condition that requires looking after.  But, perhaps they merely have a generalized condition requiring constant care.  If it is medically stable and doesn't need any acute treatment, it seems inapt to refer to them as a patient.
Whereas, it would be a perfectly legitimate catchall to say:

The caretaker spent his time watching over his charge.

This does not imply that their relationship is restricted to being medical in nature.

A: Charge is a person or thing committed to the care (meaning in the care) of another. (source at 3d)
Children is day care are called charges.

A: In the BE version of the care sector, I've heard them called: Clients, Service Users, Residents (of a Care Home / Hospice), and even (occasionally) Caree.
Patients is still common in hospital settings, but not as a form of address where names are used to be assured of the correct treatment reaching it's target.


text:
Q: Java Interface Clarification I am confused with a line in Oracle Java docs here under the heading Interfaces In Java, which says:

Method bodies exist only for default methods and static methods.

As we cannot define method body in interface, I am confused if this line has some other meaning. Appreciate if somebody can help me in understanding this.

A: In Java 8, interfaces may contain default implementations for their methods, as well as implemented static methods.

A: Default methods and static methods are new features of java 8. Prior to java 8 it was not possible to define then in an interface.
Default methods have for example the benefit of changing extending interfaces (no in the inheritance sense) with other new methods for wich you have to may a default body so that existing implementations a not broken.
Static methods in interfaces have for example the benefit of sparing the need for the creation of other classes (utility/helper classes for example) of with the only pupose is to work on instances instances of that interface.


text:
Q: RuntimeError: Unable to create link (name already exists) Keras When I save my model I get the following error:
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-40-853303da8647> in <module>()
      7
      8
----> 9 model.save(outdir+'model.h5')
     10
     11
5 frames
/usr/local/lib/python3.6/dist-packages/h5py/_hl/group.py in __setitem__(self, name, obj)
    371
    372             if isinstance(obj, HLObject):
--> 373                 h5o.link(obj.id, self.id, name, lcpl=lcpl, lapl=self._lapl)
    374
    375             elif isinstance(obj, SoftLink):

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

h5py/h5o.pyx in h5py.h5o.link()

RuntimeError: Unable to create link (name already exists)

This does not happen when I use built-in layers to build my model or others user defined layers. This error arises only when I use this particular user defined layer:
class MergeTwo(keras.layers.Layer):

def __init__(self, nout, **kwargs):
    super(MergeTwo, self).__init__(**kwargs)
    self.nout = nout

    self.alpha = self.add_weight(shape=(self.nout,), initializer='zeros',
                             trainable=True)

    self.beta = self.add_weight(shape=(self.nout,), initializer='zeros',
                             trainable=True)

def call(self, inputs):
    A, B = inputs
    result = keras.layers.add([self.alpha*A ,self.beta*B])
    result = keras.activations.tanh(result)
    return result

def get_config(self):
    config = super(MergeTwo, self).get_config()
    config['nout'] = self.nout
    return config

I read the Docs but nothing worked, I cannot figure out why.
I am using Google Colab and Tensorflow version 2.2.0

A: I think the problem is that both of your weight variables have internally the same name, which should not happen, you can give them names with the name parameter to add_weight:
self.alpha = self.add_weight(shape=(self.nout,), initializer='zeros',
                         trainable=True, name="alpha")

self.beta = self.add_weight(shape=(self.nout,), initializer='zeros',
                         trainable=True, name="beta")

This should workaround the problem.

A: I found another solution, although from a different scenario.
I was using Keras-tuner to do some hyper parameter tuning, and when building (E.G 4 models), the layers of the models would have the same name, for each of the models.
As i was testing depth of the network as a parameter, i would have multiple lstm,lstm_1, and dense layers in my group. An example of a single model is shown below for context.
Layer (type)                 Output Shape              Param#
=================================================================
lstm (LSTM)                  (None, 12, 320)           536320
_________________________________________________________________
lstm_1 (LSTM)                (None, 12, 64)            98560
_________________________________________________________________
dense (Dense)                (None, 12, 1)             65

I found that changing the name of the layer using the name parameter, so something unique, meant that i wouldn't get this error.
Example for illustration purposes:
unique_id = random.randint(1,99999999) # quite unlike
model.add(LSTM(64, name="my_layer_name_{}".format(unique_id)))

When adding the unique_id, onto the custom name, i ensured that each layer for each model in my keras-tuner group would have unique layers.
In your case, you have a single model, however, as the layers are custom, i'm not quite sure how i would name them (given the current format they have).
Can you check if this is the case ?

A: Addition to the accepted answer
You may encounter the exact same error even without custom defined weights or layers. In jupyter notebooks, after re-compiling a loaded checkpoint, it can happen, depending on the optimizer, that the optimizers weights has duplicate names. To get rid of the bad state without losing your trained model:
model.save("model.h5", include_optimizer=False)
# Restart kernel
model = load_model("model.h5")
model.compile(**args)

Leaving this here not as strict answer to the question but as a broader hint. Merely, because this thread was the first that popped up when i searched for the problem.


text:
Q: How to run command then timer is ended ? C# I dont know how to make a command run then the timer stops
here is the code :
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using System.Threading;
using System;

public class introtogamescript : MonoBehaviour
{
    public class Example
    {
        public static void Main()
        {
            // Create an instance of the Example class, and start two
            // timers.
            Example ex = new Example();
            ex.StartTimer(7000);
        }

        public void StartTimer(int dueTime)
        {
            Timer t = new Timer(new TimerCallback(TimerProc));
            t.Change(dueTime, 0);
        }

        private void TimerProc(object state)
        {
            // The state object is the Timer object.
            Timer t = (Timer)state;
            t.Dispose();
            SceneManager.LoadScene(2);
        }
    }
}

Thanks for the help.

A: You can use coroutines like this:
public void  WaitAndExecute(float timer, Action callBack = null)
{
    StartCoroutine(WaitAndExecute_CR(timer,callBack));
}

IEnumerator WaitAndExecute_CR(float timer, Action callBack = null)
{
    yield return new WaitForSeconds(timer);

    if (callBack != null)
    {
        callBack();
    }
}

void Start()
{
    WaitAndExecute(5,() => {Debug.Log("This will be printed after 5 seconds");});

    WaitAndExecute(10,JustAnotherMethod);
}

void JustAnotherMethod()
{
    Debug.Log("This is another way to use callback methods");
}

A: When you start the timer use lambdas or anonymous delegate - this way you will have the timer as closure.

A: You can also use Invoke(string methodName, float callDelay)
Example:
void SomeMethod()
{
   Invoke("OtherMethod",3.5f);
}

//It should be called 3.5 seconds after SomeMethod
void OtherMethod()
{
    print(something);
}

And you can not invoke any parameter


text:
Q: Scan RS cost long time occasionally using G1 jvm using G1 works fine most of the time, but Scan RS cost long time occasionally([Scan RS (ms): Min: 4989.9, Avg: 4994.8, Max: 5006.3, Diff: 16.3, Sum: 39958.7])
Any options can be changed to optimize the Scan RS time?
jvm command line
-Xss1m -XX:ErrorFile=/usr/local/xxx/jvm_error.log -server -Xms16g -Xmx16g -XX:+UseG1GC -XX:+UnlockExperimentalVMOptions -XX:G1NewSizePercent=15 -XX:G1MaxNewSizePercent=35 -XX:+PrintFlagsFinal -XX:+PrintReferenceGC -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+UnlockDiagnosticVMOptions -XX:+G1SummarizeConcMark -XX:ConcGCThreads=8 -XX:ParallelGCThreads=8 -XX:MaxGCPauseMillis=150 -XX:G1HeapWastePercent=20 -XX:+ParallelRefProcEnabled -XX:InitiatingHeapOccupancyPercent=70 -XX:G1HeapRegionSize=8m -Xloggc:/usr/local/xxx/gc.log -XX:-ReduceInitialCardMarks

jinfo output
Server compiler detected.
JVM version is 25.45-b02
Java System Properties:

com.sun.management.jmxremote.authenticate = false
java.runtime.name = Java(TM) SE Runtime Environment
java.vm.version = 25.45-b02
sun.boot.library.path = /usr/local/xxx/jdk1.8.0_45/jre/lib/amd64
java.vendor.url = http://java.oracle.com/
java.vm.vendor = Oracle Corporation
path.separator = :
java.rmi.server.randomIDs = true
file.encoding.pkg = sun.io
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
sun.os.patch.level = unknown
sun.java.launcher = SUN_STANDARD
user.country = US
java.vm.specification.name = Java Virtual Machine Specification
com.sun.management.jmxremote.port = 5002
java.runtime.version = 1.8.0_45-b14
java.awt.graphicsenv = sun.awt.X11GraphicsEnvironment
os.arch = amd64
java.endorsed.dirs = /usr/local/xxx/jdk1.8.0_45/jre/lib/endorsed
line.separator =

java.io.tmpdir = /tmp
java.vm.specification.vendor = Oracle Corporation
os.name = Linux
sun.jnu.encoding = UTF-8
java.specification.name = Java Platform API Specification
java.class.version = 52.0
sun.management.compiler = HotSpot 64-Bit Tiered Compilers
os.version = 3.10.104-1-tlinux2-0041.tl1
user.home = /usr/local/xxx
user.timezone = PRC
java.awt.printerjob = sun.print.PSPrinterJob
file.encoding = UTF-8
java.specification.version = 1.8

java.class.path = xxx
java.vm.specification.version = 1.8
sun.arch.data.model = 64
sun.java.command = xxx
java.home = /usr/local/xxx/jdk1.8.0_45/jre
user.language = en
java.specification.vendor = Oracle Corporation
awt.toolkit = sun.awt.X11.XToolkit
com.sun.management.jmxremote.ssl = false
java.vm.info = mixed mode
java.version = 1.8.0_45
java.ext.dirs = /usr/local/xxx/jdk1.8.0_45/jre/lib/ext:/usr/java/packages/lib/ext
sun.boot.class.path = xxx
java.vendor = Oracle Corporation
file.separator = /
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding = UnicodeLittle
sun.cpu.endian = little
sun.cpu.isalist =

GC log(Scan RS time increase at 2018-11-16T07:54:19.442+0800)
     [Times: user=3.16 sys=0.00, real=0.40 secs]
2018-11-16T07:52:36.660+0800: 6705940.466: [GC pause (G1 Evacuation Pause) (young) (initial-mark)6705940.812: [SoftReference, 0 refs, 0.0003233 secs]6705940.812: [WeakReference, 2 refs, 0.0002399 secs]6705940.812: [FinalReference, 171 refs, 0.0001946 secs]6705940.812: [PhantomReference, 0 refs, 0 refs, 0.0003687 secs]6705940.813: [JNI Weak Reference, 0.0000142 secs], 0.3506144 secs]
   [Parallel Time: 344.4 ms, GC Workers: 8]
      [GC Worker Start (ms): Min: 6705940467.2, Avg: 6705940467.2, Max: 6705940467.3, Diff: 0.1]
      [Ext Root Scanning (ms): Min: 1.0, Avg: 1.0, Max: 1.2, Diff: 0.2, Sum: 8.3]
      [Update RS (ms): Min: 14.6, Avg: 14.8, Max: 15.0, Diff: 0.4, Sum: 118.0]
         [Processed Buffers: Min: 22, Avg: 31.8, Max: 67, Diff: 45, Sum: 254]
      [Scan RS (ms): Min: 305.7, Avg: 305.9, Max: 306.0, Diff: 0.3, Sum: 2447.3]
      [Code Root Scanning (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.0]
      [Object Copy (ms): Min: 22.0, Avg: 22.2, Max: 22.3, Diff: 0.3, Sum: 177.3]
      [Termination (ms): Min: 0.0, Avg: 0.2, Max: 0.2, Diff: 0.2, Sum: 1.3]
      [GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.1, Sum: 0.3]
      [GC Worker Total (ms): Min: 344.0, Avg: 344.1, Max: 344.1, Diff: 0.1, Sum: 2752.6]
      [GC Worker End (ms): Min: 6705940811.3, Avg: 6705940811.3, Max: 6705940811.3, Diff: 0.1]
   [Code Root Fixup: 0.1 ms]
   [Code Root Purge: 0.0 ms]
   [Clear CT: 1.0 ms]
   [Other: 5.2 ms]
      [Choose CSet: 0.0 ms]
      [Ref Proc: 1.3 ms]
      [Ref Enq: 0.1 ms]
      [Redirty Cards: 1.1 ms]
      [Humongous Reclaim: 0.0 ms]
      [Free CSet: 1.6 ms]
   [Eden: 2424.0M(2424.0M)->0.0B(2424.0M) Survivors: 32.0M->32.0M Heap: 13.5G(16.0G)->11.2G(16.0G)]
 [Times: user=2.80 sys=0.00, real=0.35 secs]
2018-11-16T07:52:37.011+0800: 6705940.817: [GC concurrent-root-region-scan-start]
2018-11-16T07:52:37.046+0800: 6705940.853: [GC concurrent-root-region-scan-end, 0.0353443 secs]
2018-11-16T07:52:37.046+0800: 6705940.853: [GC concurrent-mark-start]
2018-11-16T07:52:42.007+0800: 6705945.813: [GC concurrent-mark-end, 4.9605298 secs]
2018-11-16T07:52:42.009+0800: 6705945.815: [GC remark 6705945.815: [Finalize Marking, 0.0005259 secs] 6705945.816: [GC ref-proc6705945.816: [SoftReference, 88 refs, 0.0002698 secs]6705945.816: [WeakReference, 302 refs, 0.0002114 secs]6705945.816: [FinalReference, 2068 refs, 0.0010914 secs]6705945.817: [PhantomReference, 0 refs, 16 refs, 0.0003421 secs]6705945.818: [JNI Weak Reference, 0.0000552 secs], 0.0023971 secs] 6705945.818: [Unloading, 0.0063063 secs], 0.1153675 secs]
 [Times: user=0.91 sys=0.00, real=0.11 secs]
2018-11-16T07:52:42.127+0800: 6705945.934: [GC cleanup 11G->11G(16G), 0.3453918 secs]
 [Times: user=2.77 sys=0.00, real=0.34 secs]
2018-11-16T07:53:27.785+0800: 6705991.592: [GC pause (G1 Evacuation Pause) (young)6705992.024: [SoftReference, 0 refs, 0.0003114 secs]6705992.024: [WeakReference, 4 refs, 0.0001959 secs]6705992.025: [FinalReference, 217 refs, 0.0002370 secs]6705992.025: [PhantomReference, 0 refs, 0 refs, 0.0003876 secs]6705992.025: [JNI Weak Reference, 0.0000352 secs], 0.4375653 secs]
   [Parallel Time: 431.5 ms, GC Workers: 8]
      [GC Worker Start (ms): Min: 6705991592.4, Avg: 6705991592.5, Max: 6705991592.5, Diff: 0.1]
      [Ext Root Scanning (ms): Min: 0.8, Avg: 0.9, Max: 0.9, Diff: 0.1, Sum: 6.8]
      [Update RS (ms): Min: 17.7, Avg: 17.8, Max: 18.3, Diff: 0.6, Sum: 142.8]
         [Processed Buffers: Min: 19, Avg: 33.9, Max: 49, Diff: 30, Sum: 271]
      [Scan RS (ms): Min: 369.2, Avg: 369.6, Max: 369.8, Diff: 0.6, Sum: 2957.1]
      [Code Root Scanning (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.0]
      [Object Copy (ms): Min: 42.4, Avg: 42.5, Max: 43.1, Diff: 0.7, Sum: 340.1]
      [Termination (ms): Min: 0.0, Avg: 0.6, Max: 0.7, Diff: 0.7, Sum: 4.5]
      [GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.0, Sum: 0.3]
      [GC Worker Total (ms): Min: 431.4, Avg: 431.4, Max: 431.5, Diff: 0.1, Sum: 3451.6]
      [GC Worker End (ms): Min: 6705992023.9, Avg: 6705992023.9, Max: 6705992023.9, Diff: 0.0]
   [Code Root Fixup: 0.1 ms]
   [Code Root Purge: 0.0 ms]
   [Clear CT: 1.1 ms]
   [Other: 4.9 ms]
      [Choose CSet: 0.0 ms]
      [Ref Proc: 1.3 ms]
      [Ref Enq: 0.1 ms]
      [Redirty Cards: 1.1 ms]
      [Humongous Reclaim: 0.0 ms]
      [Free CSet: 1.6 ms]
   [Eden: 2424.0M(2424.0M)->0.0B(2424.0M) Survivors: 32.0M->32.0M Heap: 13.5G(16.0G)->11.2G(16.0G)]
 [Times: user=3.51 sys=0.00, real=0.44 secs]
2018-11-16T07:54:19.442+0800: 6706043.249: [GC pause (G1 Evacuation Pause) (mixed)6706048.747: [SoftReference, 0 refs, 0.0003203 secs]6706048.747: [WeakReference, 0 refs, 0.0001715 secs]6706048.747: [FinalReference, 158 refs, 0.0002620 secs]6706048.747: [PhantomReference, 0 refs, 0 refs, 0.0003442 secs]6706048.748: [JNI Weak Reference, 0.0000194 secs], 5.5439976 secs]
   [Parallel Time: 5465.8 ms, GC Workers: 8]
      [GC Worker Start (ms): Min: 6706043280.7, Avg: 6706043280.8, Max: 6706043280.8, Diff: 0.1]
      [Ext Root Scanning (ms): Min: 0.7, Avg: 0.8, Max: 1.2, Diff: 0.5, Sum: 6.6]
      [Update RS (ms): Min: 12.5, Avg: 12.8, Max: 12.9, Diff: 0.4, Sum: 102.2]
         [Processed Buffers: Min: 20, Avg: 30.9, Max: 85, Diff: 65, Sum: 247]
      [Scan RS (ms): Min: 4989.9, Avg: 4994.8, Max: 5006.3, Diff: 16.3, Sum: 39958.7]
      [Code Root Scanning (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.1, Sum: 0.3]
      [Object Copy (ms): Min: 410.2, Avg: 426.1, Max: 461.9, Diff: 51.7, Sum: 3408.9]
      [Termination (ms): Min: 0.0, Avg: 31.0, Max: 35.7, Diff: 35.7, Sum: 248.2]
      [GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.1, Sum: 0.3]
      [GC Worker Total (ms): Min: 5465.6, Avg: 5465.6, Max: 5465.7, Diff: 0.1, Sum: 43725.1]
      [GC Worker End (ms): Min: 6706048746.4, Avg: 6706048746.4, Max: 6706048746.4, Diff: 0.1]
   [Code Root Fixup: 0.1 ms]
   [Code Root Purge: 0.0 ms]
   [Clear CT: 1.0 ms]
   [Other: 77.1 ms]
      [Choose CSet: 31.2 ms]
      [Ref Proc: 1.3 ms]
      [Ref Enq: 0.1 ms]
      [Redirty Cards: 10.2 ms]
      [Humongous Reclaim: 0.0 ms]
      [Free CSet: 33.5 ms]
   [Eden: 2424.0M(2424.0M)->0.0B(2424.0M) Survivors: 32.0M->32.0M Heap: 13.5G(16.0G)->10.3G(16.0G)]
 [Times: user=44.35 sys=0.00, real=5.55 secs]
2018-11-16T07:55:14.726+0800: 6706098.533: [GC pause (G1 Evacuation Pause) (mixed)6706105.154: [SoftReference, 0 refs, 0.0002975 secs]6706105.154: [WeakReference, 0 refs, 0.0001962 secs]6706105.154: [FinalReference, 132 refs, 0.0002233 secs]6706105.155: [PhantomReference, 0 refs, 0 refs, 0.0003446 secs]6706105.155: [JNI Weak Reference, 0.0000171 secs], 6.6696695 secs]
   [Parallel Time: 6586.2 ms, GC Workers: 8]
      [GC Worker Start (ms): Min: 6706098567.4, Avg: 6706098567.5, Max: 6706098567.5, Diff: 0.1]
      [Ext Root Scanning (ms): Min: 0.8, Avg: 0.9, Max: 1.3, Diff: 0.5, Sum: 7.0]
      [Update RS (ms): Min: 12.2, Avg: 12.6, Max: 12.9, Diff: 0.7, Sum: 101.2]
         [Processed Buffers: Min: 21, Avg: 30.9, Max: 49, Diff: 28, Sum: 247]
      [Scan RS (ms): Min: 5767.0, Avg: 5787.1, Max: 5795.8, Diff: 28.8, Sum: 46296.4]
      [Code Root Scanning (ms): Min: 0.0, Avg: 0.1, Max: 0.3, Diff: 0.3, Sum: 0.4]
      [Object Copy (ms): Min: 575.3, Avg: 609.3, Max: 782.7, Diff: 207.5, Sum: 4874.4]
      [Termination (ms): Min: 0.0, Avg: 176.1, Max: 201.4, Diff: 201.3, Sum: 1409.0]
      [GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.0, Sum: 0.3]
      [GC Worker Total (ms): Min: 6586.1, Avg: 6586.1, Max: 6586.1, Diff: 0.0, Sum: 52688.6]
      [GC Worker End (ms): Min: 6706105153.5, Avg: 6706105153.6, Max: 6706105153.6, Diff: 0.0]
   [Code Root Fixup: 0.1 ms]
   [Code Root Purge: 0.0 ms]
   [Clear CT: 1.0 ms]
   [Other: 82.4 ms]
      [Choose CSet: 34.0 ms]
      [Ref Proc: 1.2 ms]
      [Ref Enq: 0.1 ms]
      [Redirty Cards: 12.4 ms]
      [Humongous Reclaim: 0.0 ms]
      [Free CSet: 33.8 ms]
   [Eden: 2424.0M(2424.0M)->0.0B(2424.0M) Survivors: 32.0M->32.0M Heap: 12.7G(16.0G)->9920.6M(16.0G)]
 [Times: user=53.39 sys=0.00, real=6.66 secs]
2018-11-16T07:56:10.064+0800: 6706153.870: [GC pause (G1 Evacuation Pause) (mixed)6706156.501: [SoftReference, 0 refs, 0.0003236 secs]6706156.501: [WeakReference, 2 refs, 0.0001976 secs]6706156.502: [FinalReference, 133 refs, 0.0002196 secs]6706156.502: [PhantomReference, 0 refs, 0 refs, 0.0003482 secs]6706156.502: [JNI Weak Reference, 0.0000205 secs], 2.6424790 secs]
   [Parallel Time: 2626.5 ms, GC Workers: 8]
      [GC Worker Start (ms): Min: 6706153874.2, Avg: 6706153874.3, Max: 6706153874.3, Diff: 0.1]
      [Ext Root Scanning (ms): Min: 0.8, Avg: 0.8, Max: 0.9, Diff: 0.1, Sum: 6.5]
      [Update RS (ms): Min: 16.1, Avg: 16.2, Max: 16.3, Diff: 0.3, Sum: 129.2]
         [Processed Buffers: Min: 22, Avg: 32.0, Max: 83, Diff: 61, Sum: 256]
      [Scan RS (ms): Min: 2489.9, Avg: 2502.5, Max: 2508.9, Diff: 19.0, Sum: 20020.1]
      [Code Root Scanning (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.1, Sum: 0.1]
      [Object Copy (ms): Min: 99.8, Avg: 106.4, Max: 119.1, Diff: 19.3, Sum: 851.2]
      [Termination (ms): Min: 0.0, Avg: 0.5, Max: 0.7, Diff: 0.7, Sum: 4.0]
      [GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.1, Sum: 0.4]
      [GC Worker Total (ms): Min: 2626.4, Avg: 2626.4, Max: 2626.5, Diff: 0.1, Sum: 21011.5]
      [GC Worker End (ms): Min: 6706156500.7, Avg: 6706156500.7, Max: 6706156500.7, Diff: 0.1]
   [Code Root Fixup: 0.1 ms]
   [Code Root Purge: 0.0 ms]
   [Clear CT: 1.2 ms]
   [Other: 14.7 ms]
      [Choose CSet: 3.3 ms]
      [Ref Proc: 1.3 ms]
      [Ref Enq: 0.1 ms]
      [Redirty Cards: 4.2 ms]
      [Humongous Reclaim: 0.0 ms]
      [Free CSet: 4.9 ms]
   [Eden: 2424.0M(2424.0M)->0.0B(2424.0M) Survivors: 32.0M->32.0M Heap: 12.1G(16.0G)->9883.9M(16.0G)]
 [Times: user=21.28 sys=0.00, real=2.65 secs]
2018-11-16T07:57:02.462+0800: 6706206.268: [GC pause (G1 Evacuation Pause) (young)6706206.352: [SoftReference, 0 refs, 0.0003257 secs]6706206.352: [WeakReference, 4 refs, 0.0001590 secs]6706206.353: [FinalReference, 261 refs, 0.0002023 secs]6706206.353: [PhantomReference, 0 refs, 0 refs, 0.0003479 secs]6706206.353: [JNI Weak Reference, 0.0000161 secs], 0.0890372 secs]
   [Parallel Time: 83.2 ms, GC Workers: 8]
      [GC Worker Start (ms): Min: 6706206268.6, Avg: 6706206268.7, Max: 6706206268.7, Diff: 0.1]
      [Ext Root Scanning (ms): Min: 0.8, Avg: 0.8, Max: 0.9, Diff: 0.1, Sum: 6.7]
      [Update RS (ms): Min: 15.1, Avg: 15.2, Max: 15.4, Diff: 0.3, Sum: 121.3]
         [Processed Buffers: Min: 22, Avg: 30.2, Max: 56, Diff: 34, Sum: 242]
      [Scan RS (ms): Min: 53.1, Avg: 53.3, Max: 53.4, Diff: 0.3, Sum: 426.6]
      [Code Root Scanning (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.0]
      [Object Copy (ms): Min: 13.7, Avg: 13.7, Max: 13.8, Diff: 0.1, Sum: 109.9]
      [Termination (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.1]
      [GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.0, Sum: 0.3]
      [GC Worker Total (ms): Min: 83.1, Avg: 83.1, Max: 83.2, Diff: 0.1, Sum: 664.8]
      [GC Worker End (ms): Min: 6706206351.8, Avg: 6706206351.8, Max: 6706206351.8, Diff: 0.0]
   [Code Root Fixup: 0.1 ms]
   [Code Root Purge: 0.0 ms]
   [Clear CT: 0.9 ms]
   [Other: 4.8 ms]
      [Choose CSet: 0.0 ms]
      [Ref Proc: 1.2 ms]
      [Ref Enq: 0.1 ms]
      [Redirty Cards: 1.0 ms]
      [Humongous Reclaim: 0.0 ms]
      [Free CSet: 1.7 ms]
   [Eden: 2424.0M(2424.0M)->0.0B(2424.0M) Survivors: 32.0M->32.0M Heap: 12.0G(16.0G)->9918.9M(16.0G)]
 [Times: user=0.69 sys=0.00, real=0.09 secs]
2018-11-16T07:57:53.995+0800: 6706257.802: [GC pause (G1 Evacuation Pause) (young)6706257.884: [SoftReference, 0 refs, 0.0003182 secs]6706257.885: [WeakReference, 2 refs, 0.0001466 secs]6706257.885: [FinalReference, 258 refs, 0.0002163 secs]6706257.885: [PhantomReference, 0 refs, 0 refs, 0.0003126 secs]6706257.885: [JNI Weak Reference, 0.0000166 secs], 0.0876269 secs]
   [Parallel Time: 81.9 ms, GC Workers: 8]
      [GC Worker Start (ms): Min: 6706257802.3, Avg: 6706257802.3, Max: 6706257802.4, Diff: 0.1]
      [Ext Root Scanning (ms): Min: 0.7, Avg: 0.8, Max: 0.8, Diff: 0.1, Sum: 6.3]
      [Update RS (ms): Min: 14.7, Avg: 14.7, Max: 14.9, Diff: 0.3, Sum: 117.9]
         [Processed Buffers: Min: 21, Avg: 29.6, Max: 57, Diff: 36, Sum: 237]
      [Scan RS (ms): Min: 52.3, Avg: 52.4, Max: 52.5, Diff: 0.2, Sum: 419.5]
      [Code Root Scanning (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.0]
      [Object Copy (ms): Min: 13.7, Avg: 13.8, Max: 13.8, Diff: 0.1, Sum: 110.1]
      [Termination (ms): Min: 0.0, Avg: 0.0, Max: 0.0, Diff: 0.0, Sum: 0.2]
      [GC Worker Other (ms): Min: 0.0, Avg: 0.0, Max: 0.1, Diff: 0.1, Sum: 0.3]
      [GC Worker Total (ms): Min: 81.7, Avg: 81.8, Max: 81.8, Diff: 0.1, Sum: 654.3]
      [GC Worker End (ms): Min: 6706257884.1, Avg: 6706257884.1, Max: 6706257884.1, Diff: 0.0]
   [Code Root Fixup: 0.1 ms]
   [Code Root Purge: 0.0 ms]
   [Clear CT: 0.9 ms]
   [Other: 4.7 ms]
      [Choose CSet: 0.0 ms]
      [Ref Proc: 1.2 ms]
      [Ref Enq: 0.1 ms]
      [Redirty Cards: 1.0 ms]
      [Humongous Reclaim: 0.0 ms]
      [Free CSet: 1.6 ms]
   [Eden: 2424.0M(2424.0M)->0.0B(2424.0M) Survivors: 32.0M->32.0M Heap: 12.1G(16.0G)->9953.0M(16.0G)]
 [Times: user=0.67 sys=0.00, real=0.09 secs]


text:
Q: How to calculate permutations for a collection, not a set Suppose we have the following collection of integers: {1,1,2}. We can arrange the order of this collection in 3 possible ways:
1,1,2
1,2,1
2,1,1
How can we calculate the number of ways we can arrange a collection of integers in general? Suppose the size of the collection is very large (10^5 in worst case scenario) but the answer is always small enough to fit into a long. Does an efficient solution to this problem exist, and if so, how could one implement it in Java?

A: Suppose you have n integers made from n_i copies of integer x_i.
To work out the number of arrangements simply compute
t = n!

However, as you don't care about how numbers with the same value are arranged, for each value of i reduce the total by:
t = t / n_i!

In you case, you have 3 integers, with 1 copy of 2, and 2 copies of 1.
You compute:
t = 3! = 6
t = t/1! = 6/1 = 6
t = t/2! = 6/2 = 3

so the answer is 3.

A:
How can we calculate the number of ways we can arrange a collection of integers in general?

Loop through the collection, counting the number of times each number appears in the collection.
The formula for the number of permutations is size factorial / number of duplicate integers factorial.  In your example of 1, 1, 2, the size is 3 and the number of duplicate integers is 2.
3! / 2! = 3 * 2 * 1 / 2 * 1 = 3;
Another, more computer friendly way of calculating 3! / 2! is to divide out the 2 factorial first, which leaves you with 3.
If the collection has no duplicate integers, then the number of permutations is size factorial.


text:
Q: Laravel how to change passport table names to start with capital letters? I am trying to build and API, and I am using passport for authentication, the problem is I want all table names to start with capital letter for example "Oauth" instead of "oauth", how to achieve this without directly modifying the vendor files?

A: You can't directly modify table names but you can modify the model names that passport uses.
If you look at Passport Class there are static class variables:

    /**
     * The auth code model class name.
     *
     * @var string
     */
    public static $authCodeModel = 'Laravel\Passport\AuthCode';

    /**
     * The client model class name.
     *
     * @var string
     */
    public static $clientModel = 'Laravel\Passport\Client';

    /**
     * The personal access client model class name.
     *
     * @var string
     */
    public static $personalAccessClientModel = 'Laravel\Passport\PersonalAccessClient';

    /**
     * The token model class name.
     *
     * @var string
     */
    public static $tokenModel = 'Laravel\Passport\Token';

    /**
     * The refresh token model class name.
     *
     * @var string
     */
    public static $refreshTokenModel = 'Laravel\Passport\RefreshToken';

and etc.
These are models that passport uses to communicate with database. You can make your own model and extend Passport models.
For example:
class MyOwnAuthCodeModel extends Laravel\Passport\AuthCode {

    public $table = 'Auth_codes';

}

Then in Passport ServiceProvider File you have to change models:
Passport::$clientModel = '\App\Models\MyOwnAuthCodeModel';
...

Then you have to make migration files to rename all passport tables:
Schema::rename('oauth_codes', 'Oauth_codes');
...

That steps is too much if you don't want to change table names in vendor migrations and models.
And it's ready to work correctly.

Remember you have to do this for all passport tables and models.


text:
Q: Nginx behaves differently with the same site configuration in different docker images nginx site config
    server {
    listen 80;
    server_name _;
    server_tokens off;
    gzip_static on;

    location ~* \.(html)$ {
        add_header 'X-XSS-Protection' '1';
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
}

it works perfect with docker image node:14.19.3 (nginx/1.14.2), but with node:14-alpine (nginx/1.22.1) it behaves differently:

*

*trying accessing index.html (or /) redirects to default /var/lib/nginx/index.html (renders "Welcome to Nginx!"), though /usr/share/nginx/html/index.html exists and with permissions everything is OK

*if copy /usr/share/nginx/html/index.html to /usr/share/nginx/html/index.txt  - it is opened (http://<<mydomain>/index.txt)

*if copy /usr/share/nginx/html/index.html to /usr/share/nginx/html/i.html  - 404 - not found (http://<<mydomain>/i.html, well, it just can't find it in /var/lib/nginx/i.html)

*if remove the upper location block from the site config everything works perfect (there is just no that extra response header)


text:
Q: Posting to multiple friends walls after the Feb 6th change As of Feb 6th Facebook no longer allows us to post to someone's wall using the graph API.
Their suggested fix is to use the feed dialog to post to a friend's wall using the "to:" parameter. As far as a I can tell, the "to:" parameter can only be a single user.
Is there anyway using javascript or PHP apis (or any other way) to allow the user to post to multiple users' walls (either selected inside the dialog or from a list of ids I get from somewhere else) ?

A: Fine question and this is actually something that I've been in contact with Facebook about.
The short answer is no, there is no clear and succinct way to post to multiple walls at once anymore.
The longer answer....
Word from Facebook is that they removed the option to post to multiple walls because of the sheer amount of spam that went out through the open graph API.  To save everyone's sanity they decided to remove the functionality entirely.  Not necessarily an ideal scenario for those of us who try to use it legitimately, but I suppose you pick your battles when you have 1 billion users.
The short version of their answer was that their are two options:

*

*(as you mentioned) you can select a series of friends and use the to: parameter in the feed dialog to send them one at a time.  This makes it diffic

*If possible figure out which users are already a user on your Facebook app and send an email to their @facebook.com email address.  IF they have already authenticated your app, the notification jewel will light up for them and it will appear as unread in their inbox.  If they have NOT authenticated your app, it will go to the user's "other" mailbox which does not light up the jewel.  Not quite the same thing as the feed dialog because it doesn't actually post to their wall, but hypothetically still gets their attention.
Those are the only options left for those of us with web apps.


text:
Q: Earlyish '90s PC Space War / Battle Game This was a PC game I remember from the earlyish '90s (1992–1993 or somewhere around then). I remember some specific pieces but not the overall gameplay. It was a game where you built up your army (or maybe empire) and sent ships out for space battles.
The two distinct elements I remember are:

*

*There was a specific self-destruct sequence you could undertake for your spaceships. I remember this serving a purpose; i.e., you could get to a point in the game where it made more sense to self-destruct rather than continue. On the screen, it revealed a series of numbers you had to type in. It was 'done up' and presented as a measure of last resort

*I also remember a lot of purples and yellows from the game. That might sound laughable, but I believe the screen was divided into multiple panels, trying to look like 'real' computer screens  on a spaceship. I believe a lot of that framing was in purples or yellows perhaps?

I know that isn't much to go on but I've been digging and just can't find anything. I remember playing Overlord in this time period, but I don't believe the above elements are from that game, but I could be wrong....
Thanks in advance! Hopefully this is enough to job someone's memory out there.

A: This sounds like one of the Star Fleet games, Star Fleet I:  The War Begins (1985) or the sequel Star Fleet II:  Krellan Commander (1989).  If you played it in the early 1990s, I would bet on the second game.  (Both games are available as abandonware.)
The appearance of the game interface sounds like what you describe, with the colorful display broken up into panels like the instruments on a starship.  There was also more purple than you typically saw in video games.

Self-destructing was also an option in at least one of the games, if a mission was hopeless, although I don't remember how the interface worked.  (The two Star Fleet games seemed to me to be intellectual descendants of the 1971 BASIC-programmed Star Trek video game, which had similar grid attacks and also a self-destruct option, and I can only remember the self-destruct sequence from the earlier game.)

A: I am trying to figure out the exact same game and I think it was VGA Planets. It was incredibly fun to play!


text:
Q: How to create zip without subfolders in Python? I've got some files in /tmp/1234/ and I'm creating a zip using Python:
def create_local_zip_file(zipjob_number, folder_path):
    zip_file_path = os.path.join('/tmp/', f'{zipjob_number}.zip')
    with ZipFile(zip_file_path, 'w') as zip_obj:
        for filename in glob.glob(os.path.join(folder_path, "*")):
            zip_obj.write(filename)
    return zip_file_path

This creates a zip, but when I unzip the created zip file I get a folder called tmp which in turn contains a folder called 1234 which then contains the files.
How can I make sure the unzip creates a folder called 1234 containing the files directly?

A: It looks like each of your filenames includes the folder, which is why they're being written in to a directory within the zipfile.
You can use the "arcname" parameter to give the files a different name within the archive
I can see a way to do this with string splitting, however can I suggest using pathlib instead. Something like:
from pathlib import Path

...
for file in Path(folder_path).glob("*"):
    zip_obj.write(file, arcname=file.name)
...


text:
Q: Add test dependency in Protractor & Jasmine test framework I looked up controlling the test flow but couldn't find a direct way to do it. Still wondering if someone found an alternate way to manage below situation.
How to write test case which are dependent on previous test case success? Consider below example:
describe('Test scenario started', function() {
    BeforeEach(function() {
        //Doing the login here and executing it once
    });

    it('TC001 (independent)', function() {
        // Perform steps and validate
        // Click a link for newpage and verify it's loaded
    });

    describe('Navigate to next page', function() {
        it('TC002 (Dependent on success of TC001)', function() {
            // Perform steps and validate
            // Click a link for nav to page #3 and verify it's loaded
        });

        describe('Navigate to Page #3', function() {
            it('TC003 (Dependent on success of TC002)', function() {
                // Page #3 is available, let's perform the tasks now
            });
        })
    });
});

I'd like to skip the test which are dependent if the parent test case fails thereby avoiding unnecessary delay of trying to execute them. I can add all the functionality to one test case but breaking up in smaller cases is something we prefer.
Anyone have an elegant way to handle this?

A: You can use any one of the below:
jasmine-bail-fast
jasmine-fail-fast
It will allow you to fail tests faster.


text:
Q: adb shell cmd overlay resets to it's previous state (doesn't activate) after reboot I'm trying to switch between gestural and threebutton navigation using
cmd overlay enable com.android.internal.systemui.navbar.gestural
and
cmd overlay enable com.android.internal.systemui.navbar.threebutton
or via system-->gestures-->system navigation and then selecting gesture navigation and 3-button navigation.
I checked the changes using -
cmd overlay list --user current  and I was able to see the exact changes made.
But when i reboot my android device, it just reverts back to the previous selected navigation; rarely (after 5-6 tries) the changes made remain after reboot.
Example: If my present selection is threebutton and I change it to gestural, then after reboot it goes back to threebutton or sometimes (after 5-6 tries and reboots), it stays as gestural.
How do i keep the changes permanent even after reboot??

A: I also have the same issue. The changes made using the adb cmd overlay does not remain after reboot. However, in some forums, i saw that the changes still stayed for some even after reboot but they were probably running android 10. I am currently running Android 11. I don't really know if they changed this feature with android upgrades.


text:
Q: retrieve MySQL auto increment in Java I'm trying to retrieve idPatient from the database but i keep getting errors, idPatient is auto increment. But i don't know if that's what causing the problem.
This is the code i'm trying
public List<Patient> getPatientsFromDatabase() {
    String sql = "SELECT naam, voornaam, gebit, idPatient from patienten";
    try (Connection con = sql2o.open()) {
        return con.createQuery(sql)
                .throwOnMappingFailure(false)
                .executeAndFetch(Patient.class);
    }
}

the DB:

The error:

Edit - Patient:
public Patient(String voornaam, String naam, String gebit, int id) {
    this.voornaam = voornaam;
    this.naam = naam;
    this.id = id;
    if (null != gebit)switch (gebit) {
        case "melkgebit":
            g = new Melkgebit();
            this.gebit = "melkgebit";
            break;
        case "volwassengebit":
            g = new Volwassengebit();
            this.gebit = "volwassengebit";
            break;
        case "wisselgebit":
            this.gebit = "wisselgebit";
            break;
        default:
            break;
    }
}

A: It seems Patient doesn't have the property idPatient. Check it

A: The mapping between columns and properties are done automatically by name. Of course this is not always possible
In your case you have defined id (java properties) as idPatient  (corresponding column in the database table). The easiest solution for this, is to use aliases in sql queries.
Try to change your sql:
SELECT naam, voornaam, gebit, idPatient id from patienten;

For more information visit http://www.sql2o.org/docs/column-mappings/


text:
Q: How to distinguish between items returned by EnumObjects of IShellFolder I am trying to get the computers in my workgroup using Shell
HRESULT hr = S_OK;
ULONG celtFetched;
LPITEMIDLIST pidlItems = NULL;
LPITEMIDLIST netItemIdLst = NULL;
IShellFolder* pFolder = NULL;
IEnumIDList* pEnumIds = NULL;
IShellFolder* pDesktopFolder = NULL;
LPITEMIDLIST full_pid;

hr = SHGetMalloc(&pMalloc);
hr = SHGetDesktopFolder(&pDesktopFolder);
hr = SHGetSpecialFolderLocation(NULL, CSIDL_COMPUTERSNEARME, &netItemIdLst);
hr = pDesktopFolder->BindToObject(netItemIdLst, NULL,
                                  IID_IShellFolder, (void **)&pFolder);

if(SUCCEEDED(hr))
{
  hr = pFolder->EnumObjects(NULL, SHCONTF_NONFOLDERS, &pEnumIds);

  if(SUCCEEDED(hr))
  {
    STRRET strDisplayName;
    while((hr = pEnumIds->Next(1, &pidlItems, &celtFetched)) == S_OK && celtFetched > 0)
    {
      hr = pFolder->GetDisplayNameOf(pidlItems, SHGDN_NORMAL, &strDisplayName);
      if(SUCCEEDED(hr))
      {
        wprintf(L"%s\n", strDisplayName.pOleStr);
      }
    }
  }
}

But this returns the Computers, Media Devices, and Streaming Devices (is that it name?).
Like say, a computer is called OSOFEM on my workgroup... STRRET::pOleStr returns strings OSOFEM (which is the computer), OSOFEM (I think streaming device), and OSOFEM:example@email.com: (which is the Windows Media Player).
My question is how can I distinguish which is the Computer? Of course, there names can't be used because two exactly the same name will always be returned...


text:
Q: R Vapply with IF & String Output I'm trying to replace my for loop with a vapply due to efficiency. I have 1 column (x) with values that I want to ID which quartile they fall into. Then paste that into another column. Initially my for loop was...
for (i in 1:length(x)){
  if(x[i]> quantile(x,.75,na.rm=TRUE)) {
    y[i]="Q4"
  } else if (x[i]> quantile(x,.5,na.rm=TRUE)){
    y[i]="Q3"
  } else if (x[i]> quantile(x,.25,na.rm=TRUE)){
    y[i]="Q2"
  } else if (x[i]>=0) {
    y[i] = "Q1"
  } else (y[i]="")
}

And this worked great! but I read an article that discussed how more efficient vlook up is. So, I played around and tried the code...
vapply(quantiletable, function(x,y)
  if(x> quantile(x,.75,na.rm=TRUE)) {
    y="Q4"
  } else if (x> quantile(x,.5,na.rm=TRUE)){
    y="Q3"
  } else if (x> quantile(x,.25,na.rm=TRUE)){
    y="Q2"
  } else if (x>=0) {
    y = "Q1"
  } else (y="")
,rep(0,2))

This is my first attemp at vapply, so I'm sure I'm missing something/not allowed to do something.
The error I get is...
Warning message:
In FUN(X[[i]]) : argument length is > 1 and only the first element will be used (4 times)
Error: values must be length 2, but FUN(X[[1]]) result is length 1

Any help would be greatly appreciated!


text:
Q: How do I change the default permission of file created by myself? [root@ test_project]$ touch test.txt
[root@ test_project]$ ll test.txt
-rw-rw-r-- 1 root root  0 2011-08-03 13:57 test.txt

Currently it seems to be 664,how can I change it to 700?

A: You can use the umask command to change the file creation mask. This though only masks bits. If the application creating the file does not request a bit to be set then umask wont set it. With a umask 077 then files will generally be created 600 and directories 700
You can set your default umask in your $HOME/.profile

A: You want to use umask
sente@oslo: $ umask
0022
sente@oslo: $ umask -S
u=rwx,g=rx,o=rx

sente@oslo: $ touch foo
sente@oslo: $ ls -l foo
-rw-r--r-- 1 sente pg2662512 0 2011-08-02 23:13 foo

sente@oslo: $ umask -S u=rwx,g=,o=
u=rwx,g=,o=

sente@oslo: $ touch bar
sente@oslo: $ ls -l bar
-rw------- 1 sente pg2662512 0 2011-08-02 23:13 bar

I think you'll need to chmod u+x still.
sente@oslo: $ help umask:
umask: umask [-p] [-S] [mode]
    The user file-creation mask is set to MODE.  If MODE is omitted, or if
    `-S' is supplied, the current value of the mask is printed.  The `-S'
    option makes the output symbolic; otherwise an octal number is output.
    If `-p' is supplied, and MODE is omitted, the output is in a form
    that may be used as input.  If MODE begins with a digit, it is
    interpreted as an octal number, otherwise it is a symbolic mode string
    like that accepted by chmod(1).


text:
Q: How to suppress job status output I am trying to suppress this output
Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Job1            BackgroundJob   Running       True            localhost            ...
3      Job3            BackgroundJob   Running       True            localhost            ...
5      Job5            BackgroundJob   Running       True            localhost            ...

My code is written as following
foreach($line in $db) {
    $job = {
            #code
            }
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
    if ($running.Count -le $jobLimit) {
        Start-Job -ScriptBlock $job
    } else {
         $running | Wait-Job -Any | Out-Null
    }
    Get-Job | Receive-Job | Out-Null
}

I can not figure out what I am missing to hide this status output...

A: Also add | Out-Null to this line: Start-Job -ScriptBlock $job.
foreach($line in $db) {
    $job = {
            #code
            }
    $running = @(Get-Job | Where-Object { $_.State -eq 'Running' })
    if ($running.Count -le $jobLimit) {
        Start-Job -ScriptBlock $job | Out-Null
    } else {
         $running | Wait-Job -Any | Out-Null
    }
    Get-Job | Receive-Job | Out-Null
}


text:
Q: sharing WPF ControlTemplates I'm trying to learn more about WPF. I ran through an online tutorial that created a button and then created a template to be applied to additional buttons. The problem is this template is in the Window.xaml and I can only access the template from within that application. How do I make the template more globablly available? I'm thinking of some way to reference the xaml like you can reference an assembly from a different project or solution.

A: You can use "resource dictionaries" which you reference in your App.xaml like this (Expression Blend does it automatically):
<Application.Resources>
    <!-- Resources scoped at the Application level should be defined here. -->
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ResourceDictionary1.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

How to reference a resource from another assembly, use pack URI syntax. This link covers it as well.


text:
Q: Dynamic query using variable number of IN (p1, p2, p3) arguments I have the following:
Dim strdepToDelete As String
Dim strOtherToDelete As String
strdepToDelete = String.Join(",", depToDelete)
strOtherToDelete = String.Join(",", otherToDelete)
strdepToDelete = strdepToDelete.Replace(Chr(34), Chr(39)).Substring(1, 77)
strOtherToDelete = strOtherToDelete.Replace(Chr(34), Chr(39)).Substring(1, 77)

cmd.CommandText = "delete from database.tableA where guid in(@strdepToDelete, @strOtherToDelete);"
cmd.Parameters.Add("@strdepToDelete", MySql.Data.MySqlClient.MySqlDbType.String)
cmd.Parameters("@strdepToDelete").Value = strdepToDelete
cmd.Parameters.Add("@strOtherToDelete", MySql.Data.MySqlClient.MySqlDbType.String)
cmd.Parameters("@strOtherToDelete").Value = strOtherToDelete
Dim answer = MsgBox("Data will be deleted if you continue", MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Are You Sure")
If answer = vbYes Then
    Try
        cmd.ExecuteNonQuery()
        success = True
    Catch ex As Exception

    End Try
    Return success
End If

I hover over
cmd.Parameters("@strdepToDelete").Value = strdepToDelete

and
cmd.Parameters("@strOtherToDelete").Value = strOtherToDelete

and have a string value in format that MySql is looking for. Why are the records not deleted from the table?

A: From comments:
depToDelete and otherToDelete are list(of string) which passes from a function call. These hold the 1 or many guids that I wish to delete
For that, your code doesnt format it correctly for the SQL.  For a list of 2 Guid Strings, after the join you get this:
"af489fbf-982a-49de-b73e-2ac3f3192225, 0feab28d-4f96-456a-9f36-0a0376627128"

Then, strOtherToDelete = strOtherToDelete.Replace(Chr(34), Chr(39)).Substring(1, 77) apparently wants to try to remove the quote and replace with a tick.  The problem is that the string itself doesnt include a Quote.  You see it in the IDE because that is VS's way of telling you it is a string.
The SubString step is trimming valid Guid chars from the result (and a Magic Number of 77 allows it to crash when there are not just the right number of them):
Before:   "9b842f14-7932-4e3d-8483-07790ccc674c, ...
& After:   "b842f14-7932-4e3d-8483-07790ccc674c,...
This wont work because the contents are not one very long Guid.  Each element in the List needs to be ticked.  To tick each element in the list you need to loop and build a string, or use linq.
But that wont work either.  MySQL just doesn't like the resulting string from the NET provider that way and it doesnt do parameter arrays so...
So lets build a parameters engine:
There is no sense working with 2 sets of Guids, so concat them (these are an actual List(of String) containing guids, not something else, not json):
Dim depVals = depToDelete.Concat(otherToDelete).ToList

' your sql here
Dim sql = "DELETE FROM DEMO WHERE GuidString IN (@magic)"
' param storage
Dim gvalues As New List(Of String)

' create a list of "@g" param placeholders
Dim ndx As Int32 = 0
For ndx = 0 To depVals.Count - 1
    ' adds a "@gN" value to the List
    gvalues.Add(String.Format("@g{0}", (ndx + 1).ToString))
Next

' insert them into the SQL string
sql = sql.Replace("@magic", String.Join(", ", gvalues))
' '@magic' replaced with "@g1, @g2, @g3..."

Using cmd As New MySqlCommand(sql, dbcon)
    dbcon.Open()

    ' create an equal number of Paramerters, set the value of each
    For n As Int32 = 0 To gvalues.Count - 1
       ' add parm "@gN", assign value from 'depVals`
       cmd.Parameters.Add(gvalues(n), MySqlDbType.String).Value = depVals(n)
    Next

   ' debug:
   Dim fullSQL = GetFullCommandSQL(cmd)
   Console.WriteLine(fullSQL)

   Dim rows = cmd.ExecuteNonQuery()
End Using

The debug output is syntactically correct:

DELETE FROM DEMO WHERE GuidString IN ('2abfa4c4-36e2-47ea-8218-6f568a31fa88', 'fd02865e-5da2-4d4e-ba4b-84bf5b5f1444', '7376d9a3-35c9-4b44-8b85-4cd663b31d5e')

...and the 3 rows with those GUIDs get deleted!
Also:

*

*Empty Catch blocks are bad because they hide problems from the only person who can fix it (you).

*You should us Option Strict to avoid VB guessing what you mean by certain things.


text:
Q: Sigmoid output - can it be interpreted as probability? Sigmoid function outputs a number between 0 and 1. Is this a probability or is it merely a 'yes or no' depending on whether it's above or below 0.5?
Minimal example:
Cats vs dogs binary classification. 0 is cat, 1 is dog.
Can I perform the following interpretation of the sigmoid output values:

*

*0.9 - it's most certainly a dog

*0.52 - it's more likely to be a dog than a cat, but still quite unsure

*0.5 - completely undecided, could be either a cat or a dog

*0.48 - it's more likely to be a cat than a dog, but still quite unsure

*0.1 - it's most certainly a cat

Or would this be the right way to interpret the results:

*

*0.9 - it's a dog

*0.52 - it's a dog

*0.5 - completely undecided, could be either a cat or a dog

*0.48 - it's a cat

*0.1 - it's a cat

Note how in first case we utilise the numeric value to also express probabilities, while in the second case we completely ignore the probability interpretation and collapse the answers to binary. Which is correct? Can you explain why?

Background context, feel free to skip this:
I've found a number of sources that suggest that yes, sigmoid output can be interpreted as probability:

*

*Source yes 1 - (...)  sigmoid(z) will yield a value (a probability) between 0 and 1.

*Source yes 2 -  The "output" must come from a function that satisfies the properties of a distribution function in order for us to interpret it as probabilities. (...) The "sigmoid function" satisfies these properties.

*Source yes 3 - tf.sigmoid(logits) gives you the probabilities.
And a number of sources that suggest contrary, that sigmoid output cannot be interpreted as probabilities:

*

*Source no 1 - (...) the raw values cannot necessarily be interpreted as raw probabilities!

*Source no 2 - Sigmoid (...) is not a probability distribution function

*Source no (and also yes) 3 - the short answer is no, however, depending on the loss you use, it may be closer to truth than you may think.
(bonus questions, answer to win a car!) Why are there so many contradicting answers? What do these answers differ in? I find it unlikely that it's just a lot of people being completely wrong about it - I'm thinking they're just talking about different cases or some different fundamental assumptions. What's the difference that I'm missing?

I know I can just use a softmax. I also know that sigmoid can be used for non-exclusive multi-class classification (Source multi 1, Source multi 2, Source multi 3) - although even then it's unclear whether such multiple sigmoids output probabilities of various classes or again simply a 'yes or no', but for multiple classes. In my case though, I'm interested in exclusive two-class (binary) classification, and whether sigmoid can be used to determine its probabilities, or should two-class softmax be used.

A: A sigmoid function is not a probability density function (PDF), as it integrates to infinity. However, it corresponds to the cumulative probability function of the logistic distribution.
Regarding your interpretation of the results, even though the sigmoid is not a PDF, given that its values lie in the interval [0,1], you can still interpret them as a confidence index. With that in mind, I would say that your first interpretation is the most appropriate one, although you are free to implement whichever classifier suits your purposes better.

A: I think the contradiction between your provided links comes from a semantic definition of probability vs an intuitive one.  I think the intuitive interpretation of "an output closer to 1 is more likely to be correct" is the right intuition, but that the number isn't a direct correlation with the probability.  For example, we couldn't say that a 1 is twice as likely as .5 to be a dog.
There are problems like overfitting that make the purely mathematics probability viewpoint incorrect.  However, since you have to pick one of the two options for your program, it makes sense to interpret the result as the binary greater or less than .5 approach, or maybe you should try allowing an adjustable margin of error (for example, .5 +/- x is undecided).


text:
Q: Make element fixed of static after scroll and dynamic height I have a footer area, that should be always visible on the bottom of the page. But, if there is not enought height above it, it should stick under ( static/relative ).
I've come up with this very basic code:
if( footer.offset().top < sidebarContents.innerHeight() ) {
    footer.addClass('static');
}
else {
    footer.removeClass('static');
}

And this is wrapped in $(window).scroll().
The problem is, the footer flickers when on, or below the proper height. It jumps from fixed to static with every scroll change. I know, that the if is somehow wrong.
Can anyone give me some advice on how to handle it, please?


text:
Q: How to specify different command timeouts in the same accessor in BLToolkit? Let's consider I have FruitAccessor with two methods: GetBananas and GetApples.
public abstract class FruitAccessor : DataAccessor
{
    [SprocName("GetAllBananas")]
    public abstract IEnumerable<Banan> GetBananas([ParamName("@MaxCount")] int count);

    public abstract IEnumerable<Apple> GetApples();
}

The default command timeout for both methods is 30 seconds. It's fine for GetBananas, but not enough for GetApples, so I want to increase it to 1 minute.
I can override OnInitCommand in DbManager but it will affect both methods.
It would be great to drop something like [CommandTimeout(60 * 60)] attribute on GetApples method, but unfortunately there is no such attribute.
So the question is how to achieve different timeouts for methods in the same DataAccessor?

A: You can request this feature here - https://github.com/igor-tkachev/bltoolkit/issues


text:
Q: Java keeps returning the value of a variable even after mathimatical process? even after the tprice = 75 + (2/10) * distance takes place it still inputs the minvalue as  26.
this program is NOT ALLOWED to contain if statements hence the  Math.Min(tprice, cprice);
Hope this is enough info.
class UserCalc {

    public static void main(String [] args) {
        int cPrice, tPrice, distance, selfCont, minValue;
        double refund;

        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter the distance by car");
        distance = scanner.nextInt();

        System.out.println("Please enter the self contribution");
            selfCont = scanner.nextInt();
            scanner.nextLine();

        tPrice = 75 + (2/10) * distance;
        cPrice = 26 + (7/10) * distance;

        minValue = Math.min(tPrice, cPrice);
        System.out.println(minValue);

        refund = minValue * (100 - selfCont)/100;
    }
}

A: tPrice = 75 + (2/10) * distance;
cPrice = 26 + (7/10) * distance;

2 / 10 is interpreted as integers, which cannot represent a value behind the comma. This means 2 / 10 = 0.2 = 0.
resulting in tPrice = 75 and cPrice = 26.
Use 2.0 / 10 to indicate you're using a double instead, or 2.0f / 10 to use a float.
You're storing the result in a float, but that is only after the operation has finished on integers.

A: You're encountering a case of integer division. Let's break it up, piece by piece:
cPrice = 26 + (7/10) * distance;

The order of operations will perform the parentheses first - since you're dividing an integer by an integer, the result (0.7) will be truncated to 0:
cPrice = 26 + (0) * distance;

Then the multiplication is straightforward, as anything multiplied by 0 is 0:
cPrice = 26 + 0;

Thus:
cPrice = 26;

To improve your code, ensure that when you want to maintain precision for division/multiplication, you need to use double values in your calculation:
cPrice = 26 + (0.7) * distance;

See this article describing the behavior:
http://www.cs.umd.edu/~clin/MoreJava/Intro/expr-int-div.html

A: tPrice = 75 + (2/10) * distance;  // loss of
cPrice = 26 + (7/10) * distance;  // precision due to int

The above two lines are the problem. You are having a loss of precision due to the usage of int. You need to switch to double
Instead, try this:
tPrice = 75 + (2.0/10.0) * distance;  // loss of
cPrice = 26 + (7.0/10.0) * distance;  // precision due to int

Your variables tPrice and cPrice also need to be double so as to be able to accomodate the numbers after decimal.

A: int value of 7/10 and 2/10 is 0. That's the issue here.

A: Since no one has mentioned it so far, if you want to continue using an int you can rearrange the expression to: (2*distance)/10
This is mathematically equivalent, but the integer division will make less of a difference(as it doesn't happen until the end. It's like "rounding" in the middle of a calculation vs. at the end). This will still not give you an exact answer, but it was worth pointing out that order actually matters here. Some cases you really do want an integer answer so it's good to know about how changing the order of operations makes a difference.


text:
Q: Can we turn on/Off monitor with respect to time intervals in windows 8? I am using this code to turn off the monitor but I need to turn off/on the monitor with some condition e.g. turn it off at 6.00 pm and turn it on at 7.00 pm, Is it Possible?
    private int SC_MONITORPOWER = 0xF170;

    private uint WM_SYSCOMMAND = 0x0112;

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    enum MonitorState
    {
        ON = -1,
        OFF = 2,
        STANDBY = 1
    }

    private void OnMonitor()
    {
        IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(this).Handle;
        SendMessage(hwnd, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)MonitorState.ON);
    }

    private void OffMonitor()
    {
        IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(this).Handle;
        SendMessage(hwnd, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)MonitorState.OFF);
    }

A: I am not sure whether your code is working or not, but assuming that it's working then you can use some kind of timers to achieve this
say you want to turn off monitor at 6:00 pm then
    System.Timers.Timer timer = new System.Timers.Timer();
    TimeSpan tsDifference = DateTime.Parse("06:00 pm").Subtract(DateTime.Now);
    timer.Interval= (double)((tsDifference.Hours * 60 * 60) + (tsDifference.Minutes * 60) + (tsDifference.Seconds)) * 1000 + (tsDifference.Milliseconds);
    timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    timer.Enabled=true;

      void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
               //turn off your monitor
             }


text:
Q: using inherited_resource, how do you customize collections use in belongs_to relationships Here's what I have:
https://gist.github.com/chewmanfoo/9791992
But the collections rendered in the form are as if the controller create action had not been run.  (it renders Environment.all, Role.all).
I can't figure out how to customize those collections.  Note that the change should not affect Environment and Role permanently (I can't change Environment so that it's collection is always filtered), I have to change the refreshes_controller.


text:
Q: how to return type t from a method I have the following method that sets a few properties of IEntity. My general idea is that i would like all of my classes that implement IEntity to use this helper. The issue is that this returns IEntity and not Type T. How would do that?
    public static IEntity Create(IEntity entity, Company company)
    {
        entity.Company = company;
        entity.Key = Guid.NewGuid();
        entity.Created = DateTime.Now;
        entity.Modified = DateTime.Now;
        entity.ModifiedByUserName = "xxx";
        entity.CreatedByUserName = "xxx";
        return entity;
    }

I currently call the class from my controller like so. ( TaskOrder implements IEntity )
var taskOrder = EntityHelper.Create(TaskOrder(), company);

A: Read about generics in C#, there's a lot of material on the web.
Here is an example based on your code:
public static T Create<T>(T entity, Company company) where T : IEntity
{
    entity.Company = company;
    entity.Key = Guid.NewGuid();
    entity.Created = DateTime.Now;
    entity.Modified = DateTime.Now;
    entity.ModifiedByUserName = "xxx";
    entity.CreatedByUserName = "xxx";
    return entity;
}


text:
Q: Generating robots.txt dynamically I have a subfolder WP installation. It serves multiple domains, which are linked to the same folder. The requested domain is received in wp-config.php (from the $_SERVER variable) and used to define WP_SITEURL, WP_HOME and DOMAIN_CURRENT_SITE. So we can open the same both from domain.com and domain.co.uk. I need to add the link to XML sitemap to robots.txt and, obviously, it should be different depending on the domain requested.
There is the do_robots() native WP function which generates robots.txt for multisite and allows changing it dynamically using its robots_txt action from theme's functions.php file or from a plugin. However, it does not seem the case for a single-site installation.
I can call do_robots from theme functions to generate the content and write to the robots.txt file but am not sure where I should hook it.
The question is: how do I have the robots.txt dynamically generated or have the possibility to change its content with hooks from theme functions.php?

A: I just tested the 'robots_txt' filter on a single installation to modify the output of the virtual /robots.txt that WordPress displays and it worked fine for me:
add_filter('robots_txt', 'wpse_248124_robots_txt', 10,  2);

function wpse_248124_robots_txt($output, $public) {

  return 'YOUR DESIRED OUTPUT';
}

What is really happening when you try to reach /robots.txt? Does it display the default robots.txt content or a 404? If you're getting a 404, then you might have Apache or Nginx rules that are not allowing the /robots.txt request to go through PHP. It is very common to have something like this on a nginx configuration:
# Don't log access to /robots.txt
location = /robots.txt {
    access_log    off;
    log_not_found off;
}

You should replace it with something like:
# Don't log access to /robots.txt
location = /robots.txt {
    try_files     $uri $uri/ /index.php?$args;
    access_log    off;
    log_not_found off;
}

You should also check if the WordPress own internal rewrite rules are working correctly using the Rewrite Rules Inspector (or any other method available) by making sure the following rewrite rule exists:
robots\.txt$ index.php?robots=1

If it doesn't, you should try to deactivate plugins, activate a default theme and flush the rewrite rules to check if the rewrite rule comes back, but if you have no time for that, just add this rewrite rule to your .htaccess:
RewriteRule robots\.txt$ index.php?robots=1


text:
Q: How to calculate field as a substring of another? I have a text field, field1, that's populated with 14-digit identifiers, like "01234567890123".
I create a new field, field2, that I want to show the first four digits of field1.
I would like to do this using arcpy.

A: kind of figured it out as soon as I posted. Figured I should post the answer...
arcpy.CalculateField_management(myFeatureLayer, field2, "!field1![0:4]", "PYTHON")

suppose I should add that one can apply any standard Python string functions to !field1! and that this syntax can be used in the Field Calculator if one toggles the Python radio button to the on position.

A: Here is an Update Cursor approach:
import arcpy

shp = r'C:\path\to\your\shapefile.shp'

with arcpy.da.UpdateCursor(shp, ["field1", "field2"]) as cursor:
    for row in cursor:
        row[1] = row[0][:4]
        cursor.updateRow(row)


text:
Q: How can I count up by a random integer / variable (onclick)? I'm trying to simulate a race between a red and a blue dot. A dot wins if it equals or exceeds the value inputted into the text box for distance. As of now, when you click the "Take a step!" button, each dot's location/distance goes up by 1. What I'm not sure how to do is get that location/distance to go up by a random integer, in this case, a random integer from 1 to 3. How can I do that?
Here's what I have:
<!DOCTYPE html>

    <title>Dot Race</title>
    <link href="dotrace.css" type="text/css" rel="stylesheet" />

Dot Race

      Race distance: <input type="text" id="DistanceBox" placeholder="0" />

      Red dot location: 0

      Blue dot location:
      0

      <input type="button" value="Take a step!" onclick="TakeAStep();" />

A: You are incrementing the value of redcount and bluecount but that has nothing to do with x and y.
I added these lines after x= and y=. Seems to fix the root cause.
document.getElementById("reddotspan").innerHTML=parseInt(document.getElementById("reddotspan").innerHTML)+x;
redcount = document.getElementById("reddotspan").innerHTML;
document.getElementById("bluedotspan").innerHTML=parseInt(document.getElementById("bluedotspan").innerHTML)+y;
bluecount = document.getElementById("bluedotspan").innerHTML;
distance = parseFloat(document.getElementById("DistanceBox").value);

A: <!doctype html>

    <title>Dot Race</title>
    <link href="dotrace.css" type="text/css" rel="stylesheet"></link>

Dot Race

            Race distance:
                <input type="text"
                       id="DistanceBox"
                       placeholder="0">

    Red dot location: 0

    Blue dot location:
    0

        <input type="button"
               value="Take a step!"
               onclick="TakeAStep();">

A: You were almost there. When you were using the ++ operator, you were modifying the current state of the innerHTML to just add one. Instead, you need to set it equal to the new value.
You should also use Number.parseInt so it parses it to a number explicitly. Otherwise, if you do "0" + 1, it will result in "01".

  <title>Dot Race</title>
  <link href="dotrace.css" type="text/css" rel="stylesheet" />

Dot Race

    Race distance:
    <input type="text" id="DistanceBox" placeholder="0">

    Red dot location: 0

    Blue dot location:
    0

    <input type="button" value="Take a step!" onclick="TakeAStep();" />

A: You can use:
Math.round(Math.random()*3);

Math.random() returns a random number between 0 and 1.
Multiply by 3 to get 3 as highest number.
Round.


text:
Q: Unity: how to specify to use specific instance of a type when resolving another type I'm trying the following in Unity:
I have a type with the following constructor
public Type1(Type2 firstDependency, Type3 secondDependency)

When resolving Type1 using Unity, I want to specify the specific instance for Type2 to inject. This specific instance of Type2 is not registered in the container. Type3 is registered in the container and should be resolved as usual.
To be more specific, consider Type1 is a DocumentViewer class. Type2 is a specific Document. Type3 is a SpellingChecker.
I want to be able to resolve DocumentViewer for a Document that is only known at runtime. Multiple DocumentViewer instances for differenct Documents can be created.
How can I do this?

A: Here is a quick example I have made, you use RegisterInstance or you can use a Lifetime management Claas
static void Main(string[] args)
{
    IUnityContainer container = new UnityContainer();

    container.RegisterType<Type1>();

    container.RegisterInstance<Type2>(new Type2());

    Type1 t = container.Resolve<Type1>();

    Type2 t2 = container.Resolve<Type2>();

    Type3 t3 = container.Resolve<Type3>();

    Console.ReadKey();
}

public class Type1
{
}

public class Type2
{
}

public class Type3
{
    private Type1 t;
    private Type2 t2;
    public Type3(Type1 t, Type2 t2)
    {
        this.t = t;
        this.t2 = t2;
    }
}

Update: I included a type with two parameters in constructor to show it can also be resolved.

A: Try using named instances:

IUnityContainer container = new UnityContainer();
container.RegisterType<Type1>();
container.RegisterType<Type2>("Instance 1", new ContainerControlledLifetimeManager());
container.RegisterType<Type2>("Instance 2", new ContainerControlledLifetimeManager());
container.RegisterType<Type3>();

Type1 type1 = container.Resolve<Type1>();
if (type1 == ...)
{
  Type2 instance1 = container.Resolve<Type2>("Instance 1");
}
else
{
  Type2 instance2 = ontainer.Resolve<Type2>("Instance 2");
}

You can do some checks on type 1 and decide which instance of type 2 you will need. Note that the "new ContainerControlledLifetimeManager()" parameter will initialize a singleton instance of the resisted type, so you will always get the same instance of type 2.
Update: Same with interfaces. Hope this helps.

IUnityContainer container = new UnityContainer();
container.RegisterType<TextDocument>();
container.RegisterType<ImageDocument>();
container.RegisterType(typeof (IView), typeof (TextView), "Text", new ContainerControlledLifetimeManager());
container.RegisterType(typeof (IView), typeof (ImageView), "Image", new ContainerControlledLifetimeManager());

IDocument document = container.Resolve<TextDocument>();

IView view = null;
if (document is TextDocument)
{
    view = container.Resolve<IView>("Text");
}
else
{
    view = container.Resolve<IView>("Image");
}

view.Show();

A: If you have a class with multiple constructors, you can decide which constructor is used by the Unity container using the "InjectionConstructor" attribute. This gives you the possibility to set some parameters manually.

public class Test
{
    public Test()
    {
    }

    // Always use the following constructor
    [InjectionConstructor]
    public Test(Type1 type1) : this()
    {
    }

    public Test(Type1 type1, Type2 type2) : this(type1)
    {
    }
}

A: Use a factory.
public class Type1Factory
{
  private Type3 type3;

  public Type1Factory(Type3 _type3)
  {
     type3 = _type3;
  }

  public GetType1(Type2 type2)
  {
    return new Type1(type2, type3);
  }
}

Call it this way:
// SpellingChecker is subclass of Type3
IUnityContainer container = new UnityContainer();
container.RegisterType<Type3>(typeof(SpellingChecker));

// DocumentViewer is subclass of Type2
Type1Factory factory = container.Resolve<Type1Factory>();
Type1 type1 = factory.GetType1(new DocumentViewer());

This assumes that you are only trying to use Unity to resolve the Type3 dependency, and that you have no control over the constructors in Type1. If you can edit Type1, use Alexader R.'s suggestion to make Unity only resolve the one parameter constructor.

A: You can use container hierarchy, please read my answer for similar question here: Microsoft Unity. How to specify a certain parameter in constructor?.
The only difference is that looks like you should use RegisterInstance() in your child container instead of RegisterType(). And maybe not, it depends on whether you created instance before somewhere outside of your code or not.


text:
Q: How to add event handler in MVVM in Windows Phone 8? All
I have a issue. Now I'm using MVVM framework to develop Windows Phone 8 app. I just want to when I press the button, then begin to record something, when release the button, stop recording, I used InvokeCommandAction to bind the command in ViewModel, this is the code as follow
Xaml:
<Button x:Name="BtnRecord" Height="50" Width="180" Background="#D43637" Content="Record" Margin="20,0,0,0" Style="{StaticResource BasicButtonStyle}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding StartRecordCommand}"/>
         </i:EventTrigger>
        <i:EventTrigger EventName="MouseLeftButtonUp">
            <i:InvokeCommandAction Command="{Binding EndRecordCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

ModelView:
public ICommand StartRecordCommand
{
    get
    {
        return new DelegateCommand(StartRecord);
    }
}

public ICommand EndRecordCommand
{
    get
    {
        return new DelegateCommand(EndRecord);
    }
}

private void StartRecord(object parameter){}

private void EndRecord(object parameter){}

When I debug the app, I found it didn't fire the neither the MouseLeftButtonDown nor MouseLeftButtonUp events, so I register the two event handler as follow:
BtnRecord.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(Button_MouseLeftButtonDown), true);
BtnRecord.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Button_MouseLeftButtonUp), true);

private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}
private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
}

OK, keep on going, but the next problem is coming, it didn't fire the ICommand in ViewModel, it called the Button_MouseLeftButtonDown, oh, god, I crazy
Anyone know how to call the ICommand in ViewModel?
Or another way to implement it?

A: You can use ICommand.Execute. So, your handler should be
private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    StartRecordCommand.Execute(null);
}

A: Try binding the IsPressed property of the Button with a TwoWay binding to a bool property called IsRecording in your ViewModel and start/stop your recording logic from inside the setter based on the new bool value (true would mean start).
Let me know if it works.


text:
Q: Probability and statistics of biased coin Suppose we have a biased coin, with probabilities p of coming up heads and $q = 1 -p$
of coming up tails on any given toss, but we are not given what $p$ or $q$ are. We know
from class that the expected value of the number of heads in $n$ tosses is $E(X) = np$. If we
repeatedly flip the coin and record the results, the number of heads that actually turn up,
call it $\hat E$, can be divided by the number of tosses, $n$, to give an estimate, $p = \frac{\hat E}n$ , of $p$.
The problem is that we're likely to have to be pretty lucky for $\hat{p} = p$, so the real question
is how likely it is that $\hat{p}$ is close to $p$. (This sort of thing is what statistics is all about:
trying to infer from actual data what is really true and then estimate the likelihood that
what is inferred is close to reality.)
Let us suppose, for the sake of argument, that we know that $0.5\le p\le 0.6$ (so
$0.4 \le q = 1 -p\le 0.5$) for our biased coin and that we have the time and patience to toss it any finite number of times $n$ that we want.
 Further, let us suppose that we desire to get
an estimate of $p$ that is within $5\%$ of the real value, i.e. $0.95p\le \hat{p}\le 1:05p$.

*

*How many times do we need to toss the coin, keeping track of the number of tosses
and the number of success, to ensure that $P( 0.95p\le \hat{p}\le 1.05 p)\ge  0.95$? Please justify
your answer as fully as you can. [10]
Note: That is, what does $n$ have to be to ensure that the probability that $\hat{p}$ is within $5\%$
of $p$ is at least $0.95$?

A: Start with assuming that the true value is $p=0.6$, for example and assume you know $n$.
What is $P(0.95\cdot0.6\cdot n\le \hat E\le 1.05\cdot0.6\cdot n)$?
How big must $n$ be to make this at least $0.95$?
Next assume that the true value is $p=0.5$, for example and assume you know $n$.
What is $P(0.95\cdot0.5\cdot n\le \hat E\le 1.05\cdot0.5\cdot n)$?
How big must $n$ be to make this at least $0.95$?
What happens if the true value of $p$ is somewhere between $0.5$ and $0.6$? Can we perhaps conclude that the values of $n$ that work for both of the extreme cases also work here?

A: For $\varepsilon=0.05$ solve for $n$
$$\sum_{k={\lceil}pn(1-\varepsilon){\rceil}}^{{\lfloor}pn(1+\varepsilon){\rfloor}}{{n \choose k} p^k (1-p)^{n-k}}>1-\varepsilon$$
I do not think it is tractable to find an $n$ in terms of arbitrary $p,\varepsilon$. Computing some bounds or parametric models on bounds can be possible.


text:
Q: How can I reduce the verbosity of matching every call that returns a Result or Option? I have a case where I need to pull some data out of a TOML file. It's working just fine, but the vast majority of the code is matching Results or Options.
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use std::process::exit;

extern crate toml;

fn main() {
    // Get the path of the config file
    let homedir = match env::home_dir() {
        Some(path) => path,
        None       => {
            println!("Error: Could not find home directory");
            exit(1);
        }
    };
    let mut config_path = PathBuf::from(homedir);
    config_path.push(".relay");
    config_path.set_extension("toml");

    // Open the config file
    let mut file = match File::open(&config_path) {
        Ok(file) => file,
        Err(why) => {
            println!("Error opening {}: {}", config_path.display(),
                                             Error::description(&why));
            exit(1);
        },
    };

    // Read the contents of the config file into memory
    let mut config_str = String::new();
    match file.read_to_string(&mut config_str) {
        Ok(_)    => (),
        Err(why) => {
            println!("Couldn't read {}: {}", config_path.display(),
                                             Error::description(&why));
            exit(1);
        }
    }

    // Parse the toml
    let config: toml::Value = match config_str.parse() {
        Ok(config) => config,
        Err(errs)   => {
            println!("Error Parsing config file:");
            for err in &errs {
                println!("  {}", Error::description(err));
            }
            exit(1);
        }
    };

    let host = match config.lookup("relay.host") {
        Some(host) => match host.as_str() {
            Some(s) => s.to_string(),
            None    => {
                println!("Error: 'host' option is not a valid string");
                exit(1);
            }
        },
        None       => {
            println!("Error: 'host' option not found under [relay] block");
            exit(1);
        }
    };
    println!("{}", host);
}

This seems quite verbose, and as I start pulling more data out of that files it's going to get worse. Is there something I'm missing that would make this cleaner? I know I could replace most of those match statements with unwrap() or expect(), but I would like to print some prettier error messages if something goes wrong, and avoid stuff like:
thread '<main>' panicked at '<actual error message>', ...
note: Run with `RUST_BACKTRACE=1` for a backtrace

A: You should peruse the error handling section of The Rust Programming Language. The easiest thing to do is to extract the core of the logic to another method and pervasively use Result.
Become very familiar with the methods on Option and Result. Methods like map, map_err, ok_or, are extremely useful. The lynchpin is the ? operator (previously the try! macro).
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;

extern crate toml;

fn inner_main() -> Result<(), Box<Error>> {
    let mut config_path = env::home_dir().ok_or("Could not find home directory")?;

    config_path.push(".relay");
    config_path.set_extension("toml");

    let mut file = File::open(&config_path)
        .map_err(|e| format!("Could not open {}: {}", config_path.display(), e))?;

    let mut config_str = String::new();
    file.read_to_string(&mut config_str)
        .map_err(|e| format!("Couldn't read {}: {}", config_path.display(), e))?;

    let config: toml::Value = config_str
        .parse()
        .map_err(|e| format!("Error parsing config file: {}", e))?;

    let relay = config.get("relay").ok_or("[relay] block not found")?;

    let host = relay
        .get("host")
        .ok_or("'host' option not found under [relay] block")?;

    let host = host.as_str()
        .map(ToString::to_string)
        .ok_or("'host' option is not a valid string")?;

    println!("{}", host);

    Ok(())
}

fn main() {
    inner_main().expect("Error")
}

Check out crates like quick-error that allow you to easily make your own error enumerations.


text:
Q: g:message with arguments inside Javascript / jQuery not working as expected I had an issue where String arguments were being truncated to the first character in our g:message tags (longs/integers seemed to be fine).
Ultimately, I figured out we were not calling g:message syntactically correct from within Javascript so some minor tweaks fixed the issue. Problem is - I don't understand why the former doesn't work.
Can anyone describe what was happening here?
jQuery("#myId").html("<g:message code='domain.message.path' args="${command?.foo?.name}"/>"); //incorrect, only displays first character of message

jQuery("#myId").html("${g.message(code: 'domain.message.path', args: [command?.foo?.name])}"); //correct, displays full string

A: I assume you're rendering this as part of a .gsp page?  Here's the thing.  In the first one, you're nesting quotes, essentially leaving the ${} section out of the string.  Even Stackoverflow can tell; note how that part is a different color:
jQuery("#myId").html("<g:message code='domain.message.path' args="${command?.foo?.name}"/>");

See how the quote at the end of html( is ended by the quote before ${, leaving the ${command?.foo?.name} block outside the string?  If command.foo.name was the string "bob", then when this rendered, you'd get:
jQuery("#myId").html("<g:message code='domain.message.path' args="bob"/>");

You might think this looks right, but javascript will handle this poorly.
If you used single quotes for the internal string, like you do with 'domain.message.path', it should work fine:
jQuery("#myId").html("<g:message code='domain.message.path' args='${command?.foo?.name}'/>");