text:
Q: Run a XAML method (Not BindingContext) In a XAML file, I would like to Invoke a method of some class (Not the bindingContext or C# code behind linked to said XAML). The class can then return an instance of a transient or a singleton service, in my case a viewModel.
XAML :
 BindingContext="{custom:XAMLServiceHelper {viewModel:HomePageViewModel}}"

Class:
[ContentProperty(nameof(ViewModel))]
public class XAMLServiceHelper
{
    /// <summary>
    /// Gets or sets the path.
    /// </summary>
    public object ViewModel { get; set; }

    public XAMLServiceHelper()
    {

    }

    public XAMLServiceHelper(object viewModel)
    {

    }

    public object GetViewModel(object viewModel)
    {
       return ServiceProvider.GetService<viewModel>();
    }
}

I know I am missing quite a bit, but I am not sure if it is at all possible.
I know something similar although still quite different is possible for converting strings. I was wondering if there was something I would need to inherit.
XAML:
<Image Source="{custom:FileImage myImage.png}"/>

Class:
[ContentProperty(nameof(Path))]
public class FileImageExtension : IMarkupExtension<FileImageSource>
{
    /// <summary>
    /// Gets or sets the path.
    /// </summary>
    public string Path { get; set; }

    /// <summary>
    /// Convert to file image source.
    /// </summary>
    /// <param name="path">path.</param>
    /// <returns><see cref="FileImageSource"/>FileImageSource.</returns>
    public static FileImageSource Convert(string path)
    {
        if (path == null)
        {
            return null;
        }

        if (DeviceInfo.Platform == DevicePlatform.WinUI)
        {
            path = System.IO.Path.Combine("Assets/", path);
        }

        return (FileImageSource)ImageSource.FromFile(path);
    }

    /// <summary>
    /// Provide value to the file image source provider.
    /// </summary>
    /// <param name="serviceProvider">serviceProvider.</param>
    /// <returns><see cref="ServiceProvider"/>serviceProvider.</returns>
    public FileImageSource ProvideValue(IServiceProvider serviceProvider) => Convert(this.Path);

    /// <summary>
    /// Get provider value.
    /// </summary>
    /// <param name="serviceProvider">serviceProvider.</param>
    /// <returns><see cref="ProvideValue"/>provideValue.</returns>
    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        return this.ProvideValue(serviceProvider);
    }
}


text:
Q: why isn't saga function accepting a request for the 2nd time around? so I am guessing I am doing something fundamentally wrong. When I upload an image from the browser the first time, the below function triggers but it only happens once. so next time I upload an image, I don't see watchFileReader function running again.. so strange that it is happening..because I am getting other saga function to behave as expected!
Could someone tell me what I may be doing wrong?
export function* watchFileReader() {
  const action = yield take("DROP_FILE")
  console.log('action', action)
  let file = action.file[0];
  readFile(file, function(e) {
    sessionStorage.removeItem('img')
    console.log('alskdjfalsdjkf', e.target.result)
    sessionStorage.setItem('img', e.target.result)
  })
}

export const readFile = (file, callback) => {
  let reader = new FileReader()
  reader.onloadend = callback;
  reader.readAsDataURL(file)
}

export function* rootSaga() {
  yield [
    watchFileReader()
  ]
}

A: the take effect only gets yielded once. You can either stick the watcher code inside a while loop, or use the takeEvery helper from redux-saga.
Because its a generator function, the saga is suspended until the action is caught by the middleware and yielded again, so its not like you'll have a bunch of infinite loops whirring around in the background hogging cpu.
I use the same design patterns as a lot of the docs, which is to have a 'watcher' saga / process that runs on a loop to take every action dispatched, and fires of a worker saga or process that does the real heavy lifting.
TakeEvery (or takeLatest if you only want the latest one fetched) acts like a forever-running while loop, and each time it gets the action its looking for, forks a new worker, which makes it a non-blocking operation.
export function* fileReaderWorker(action) {
  console.log('action', action)
  let file = action.file[0];
  readFile(file, function(e) {
    sessionStorage.removeItem('img')
    console.log('alskdjfalsdjkf', e.target.result)
    sessionStorage.setItem('img', e.target.result)
  })
}

export function* watchFileReader() {
  yield takeEvery("DROP_FILE", fileReaderWorker)
}
// or the loop version
// while (true) {
//  const action = yield take("DROP_FILE")
//  yield fork(fileReaderWorker, ...args.concat(action))
//}

export const readFile = (file, callback) => {
  let reader = new FileReader()
  reader.onloadend = callback;
  reader.readAsDataURL(file)
}

export function* rootSaga() {
  yield [
    watchFileReader()
  ]
}

A: After the first file is dropped, the status of saga generator function would be suspended i.e {done: false}. To keep the status as active you can either wrap your yield function in an infinite while loop:
export function* watchFileReader() {
  while(true) {
   const action = yield take("DROP_FILE")
   console.log('action', action)
   let file = action.file[0];
   readFile(file, function(e) {
    sessionStorage.removeItem('img')
    console.log('alskdjfalsdjkf', e.target.result)
    sessionStorage.setItem('img', e.target.result)
  })
 }
}

or make use of the takeEvery or takeLatest side-effect provided by redux-saga.

redpajama_set_name: RedPajamaStackExchange


text: Q: Spring RequestScoped bean declared inside ApplicationScoped bean is thread safe? Spring application scoped bean contains Request scoped bean. What will happen when multiple requests concurrently access request scoped bean inside the application scoped bean?


text:
Q: New mail notifications for Outlook additional mailboxes I use multiple mailboxes in Outlook.
My primary mailbox is ap@mywork.dk
But I also have additional mailboxes e.g. reception@mywork.dk, support@mywork.dk
Now whenever I get a mail in my inbox, ap@mywork.dk, I get a notification - a small blue box with the topic and name of sender is displayed on the lower right corner of my monitor for a few seconds.
Is it possible to apply that form of alert to other mailboxes, like reception@mywork.dk?
I want to make clear though, I can't just autoforward the mails from that inbox to my own. it would create more problems than solutions to mix the inboxes like that.
I've attempted to look through the possible settings on the inbox 'reception@mywork.dk' can't seem to find anywhere to turn on notifications or alerts.

A: You can accomplish this by setting up a rule in the relevant mailbox:

*

*In the Rules and Alerts dialog, click New Rule...

*Select Apply rule on messages I receive then click Next:

*Select the condition sent to people or public group, selecting the group mailbox identifier, then click Next:

*Select the action display a Desktop Alert:

*Click Finish. Accept the prompt that states this will be run on the client only.

A: According to this page this possibility is available in Outlook 2010:

Are either the primary or secondary Exchange accounts running in Cached Exchange Mode? If the second account is in Cached Mode, then you will see the new email notifications.

Unfortunately this option does not exist in Outlook 2007. Here is a blog post that suggests a workaround using VBA:

It doesn't look or behave the same as the built-in notification, but it is functional. The solution is to use a bit of scripting to monitor the additional mailbox's inbox, watch for new items, and display a pop-up dialog-box when it detects one. The dialog-box is a standard Windows' dialog, not the slick-looking notification that Outlook uses. The dialog doesn't fade in and out, nor does it offer the ability to open or delete the message as Outlook's notification dialog does. It will steal focus and you have to click a button to make it go away.


text:
Q: C# Order List by List of Internal Properties Suppose I have an object like so..
public class Child
{
    public string Name {get;set;}
    public int Age {get;set;}
}

public class Mother
{
    public string Name {get;set;}
    public Child child;
}

And now I have a list of Mothers
List<Mother>

I already have List<Child> ordered
Child is 1 to 1 with Mother.
I'd like to order the list of Mother based of the order of List<Child>
Any suggestions?

A: If the lists are equinumerous and all mothers have child and vice versa, then this works out-of-the-box. If there are more mothers than children or mothers whose child is not on the children's list, then those mothers are not returned. Similarly, if there are more children than mothers or children whose mother is not on the mothers' list, then motjers of those children are not returned.
public IEnumerable<Mother> GetOrderedMothersByChildren(
    IEnumerable<Mother> mothers, IEnumerable<Child> children)
{
    foreach (var child in children)
    {
        var mother = mothers.FirstOrDefault(m => m.Child == child);
        if (mother != null)
            yield return mother;
    }
}

//Usage
var orderedMothers = GetOrderedMothersByChildren(mothers, children).ToList();


text:
Q: ORMLite performance: ArrayAdapter vs CursorAdapter vs a custom adapter I have relatively small H2 database. I am expecting no more than 100 entries and even that feel highly over the top.
I have a list view with some controls and use an ArrayAdapter with a call to QueryAll() to populate the data. It works perfectly as I can modify the data in the array in memory when a button is pressed and then write the result to DB without having to reload it. But the initial load is surprisingly slow
What I wonder is whether I should rather use a CursorAdapter, since it seems more fitting to the problem or write a custom adapter to make use of the DAO Iterator.
Will there be a performance improvement using Cursor or a custom adapter? In my mind it feels like a custom adapter should give the best performance.

A: CursorAdapter is more appropriate when there is a database because it does not load all the records as ArrayAdapter. It loads only the visible records in the ListView is between 5 and 10.
So I think if you use a  CursorAdapter you will not have loading problems.
Regards

A: Its better to use a custom adapter with
Content provider.


text:
Q: Finding a specific word that might have an RTF tag inside it
I am currently writing a program that formats certain words in a Rich Text document by       putting RTF tags around them.

As the program allows for additional formatting rules that can overlap (i.e. colouring the phrase "please help me" all in yellow and colouring "please" in blue), the program has difficulty finding matches that have already been formatted by a previous rule (i.e. "please help me", from the previous example becomes "\cf1 please\cf0  help me", which will not match the other rule.

I have been getting around this by using regular expressions and putting an expression that matches any RTF tag after each character in the phrase (as the rules are defined by the user, and I don't know the specific point of overlap), like this:

line = Regex.Replace(line, @"\bP(?:\\[^ ]* )*l(?:\\[^ ]* )*e(?:\\[^ ]* )*a(?:\\[^ ]*   )*s(?:\\[^ ]* )*e(?:\\[^ ]* )*", Evaluator);

The '(?:\\[^ ]* )*' expression in the above sequence finds the preceding character regardless of any tags after it, but doing this with every rule slows down the code drastically and requires me to generate a regular expression for each one; which may not work as expected depending on the rule.

Err, sorry for the wall of text, I'll get to the point now. Does anyone know a more efficient way of finding a word that has RTF tags inside it at an unknown point?

A: One possibility is to never allow overlap of similar tags - if you need to start formatting the text in red but it's already being formatted in blue, close the blue tag before you start the red tag. Otherwise I'd imagine that the formatting rules could get quite ambiguous.
Edit
If you absolutely need to have overlap, then create a stack of formatting. End the old tag as I said above, but save it to the stack. Start the new tag, and when your new tag is done, if the old formatting was not closed (and is still in the stack) start the old formatting again. Whenever you close a tag you remove it from the stack.


text:
Q: Is it possible to update Carbon Fields using update_post_meta I have a plugin that uses the Carbon Fields SDK and in another plugin I would like to update that field without requiring the Carbon Library.
Is it possible, or are there any pitfalls, to simply doing something like:
update_user_meta($id, '_carbon_field_name', 'meta value');

or does one have to use the native carbon functions?

A: It should work:
update_user_meta($id, '_carbon_meta_key', 'meta value');


text:
Q: timer2 in pic16f877A to be used for pwm as well as uart I am doing a project on pic16f877A to control dc motor speed control.
I am working for the first time with pic microcontrollers . In my project i am generating pwm signals and to generate pwm pic uses timer2 . And i am also using serial communication and i read on google that timer2 is used for UART.
so i wanted to know how pwm and uart will work together using single timer.
I demonstrated the output on proteus and it works fine.

A: You shouldn't believe everything you read on Google.
Your first port of call should always be the datasheet.  In there it describes exactly how each peripheral works, and even gives you some simple block diagrams to follow so you don't need to understand all the terminology.
For instance, the UART section gives this nice diagram:

You can instantly see that the baud rate, generated by the SPBRG (Serial Port Baud Rate Generator) gets its clock direct from \$F_{OSC}\$ (the OSCillator Frequency) and there is no connection anywhere to any timer peripheral.
So I don't know what you read, or where you read it, but it may have been referring to some completely different chip, or have been written by someone who doesn't actually possess a clue.

A: "i read on google that timer2 is used for UART".  Seriously!!?  Design by heresay is not a good technique.
The proper source of information about any electronic device is its datasheet, and this case is no exception.  The UART is very well described in the datasheet.  It has it's own chapter 10 Addressable Universal Synchronous Asynchronous Receiver Transmitter starting on page 111.  Section 10.1 on page 113 goes into great detail on the baud rate generator.  There is also a complete diagram of the USART in section 10.2.2 on page 117 that shows, among other things, how the baud rate generator fits into the whole device.  There is no dependence on timer 2 described anywhere in that chapter.
Once again, Read the Manual!


text:
Q: Making a Class Immutable I am learning about immutable Objects. I have to make following class immutable. Did i do it right?
import java.awt.Point;
public class MyImmutablePoint {
    Point point;

    public MyImmutablePoint(Point point) {
        super();
        this.point = point;
    }

    public MyImmutablePoint() {
        this (new Point (0,0));
    }

    public Point getPoint() {
        return point;
    }

    public void setPoint(Point point) {
        this.point = point
    }
}

"Immutable" Class:
public final class MyImmutablePoint {
    private final Point point;

    public MyImmutablePoint(Point point) {
        this.point = point;
    }

    public MyImmutablePoint() {
        this (new Point (0,0));
    }

    public Point getPoint() {
        return point;
    }
}

Iam not sure about the toString method though.
and maybe returning an object like Point can be modified as well like an array but not sure

A: No
final Point p = new Point(0,0);
final ImmutablePoint ip = new ImmutablePoint(p);

Two examples:
//change the original Point passed in
p.x = 10
//use the getter and change the Point
ip.getPoint().x = 10

So, first you need to create a defensive copy of the Point taken in the constructor:
public MyImmutablePoint(Point point) {
    this.point = new Point(point);
}

Then you need to create a defensive copy of the Point returned from the getter:
public Point getPoint() {
    return new Point(point);
}

This all leads me to suggest that it would probably be better not to expose the internal point at all:
public final class MyImmutablePoint {

    private final Point point;

    public MyImmutablePoint(Point point) {
        this.point = new Point(point);
    }

    public MyImmutablePoint() {
        this.point = new Point (0,0);
    }

    public int getX() {
        return point.x;
    }

    public int getY() {
        return point.y;
    }
}

Further format your code and order your members.

A: No it is not immutable. Point can still be modified by the creator of MyImmutablePoint. Ex:
    Point point = new Point(1, 1);
    MyImmutablePoint immutablePoint = new MyImmutablePoint(point);
    point.setLocation(0, 0);


text:
Q: WPF InputManager KeyDown not handled First of all I already have a working solution I just need some explanation on what is happening here.
I have the following code:
var e = new KeyEventArgs(Keyboard.PrimaryDevice,
                         Keyboard.PrimaryDevice.ActiveSource,
                         Environment.TickCount,
                         Key.D1)
{
   RoutedEvent = Keyboard.KeyDownEvent
};
InputManager.Current.ProcessInput(e);

The purpose of this code is to add the value 1 to a currently focused textbox (= Keyboard.PrimaryDevice.ActiveSource).
But if I execute this code the text which is contained in the textbox wont change. But the routed "KeyDown" event is executed.
If I change the code from above to this, it is working:
var eventArgs = new TextCompositionEventArgs(Keyboard.PrimaryDevice,
                                             new TextComposition(InputManager.Current,
                                             Keyboard.FocusedElement, "1"))
{
   RoutedEvent = ContentElement.TextInputEvent
};

InputManager.Current.ProcessInput(eventArgs);

Now my question is, why is it not working with the first example. In my understanding if the control receives a KeyDown Event the result should be that the text is changed? The interessting part is if I want to send special key events like Enter or Backspace I HAD to use code example 1 code example 2 wont work there.
This is a little bit tricky and I thought maybe someone can enlighten me?
Thank you in advance


text:
Q: Node doesn't rejoin cluster after being downed I'm using Akka.NET's cluster (1.0.5) functionality to implement a service that consists of a master node that receives requests over HTTP and farms the work out to worker nodes that have joined the cluster.
The idea is to be able to easily accomplish the following:

*

*add worker nodes to cluster when demand is high (check)

*be able to reboot the master node or take it offline (maintentance/misbehaviour/whatever) and have the workers reconnect when it becomes available (check)

*upgrade/reboot a misbehaving worker and have it reconnect to the master node (fail!)
The first point works as you'd expect: a new instance (Azure Cloud Service worker role) is spun up, and joins the master - which is also the seed node.
For the second point, all worker nodes have an actor that listens to cluster gossip and it determines if the master node has died. If this is the case, the worker node actor system will be rebooted.
The last point is where I'm stuck. The master node also listens to cluster gossip to determine when a worker has become unreachable (ClusterEvent.UnreachableMember) or is shutting down (Exiting status) and decides if it should be downed. According to what I've understood from documentation, the only way to have a "new" version of the same node rejoin the cluster is to down the old version first.
Unfortunately this doesn't seem to be happening. In the test scenario I ran to reproduce the problem locally in the compute emulator, these were the steps:

*

*Start the master node (port 8090)

*Start the worker node (port 9090)

*Do some work

*Kill the worker node abruptly

*Start the worker node back up
Below are relevant snippets from the logs I collected for both nodes during this test:

Master:
Worker becomes unreachable:
[WARNING][07/12/2015 20:39:35][Thread 0023][[akka://InventoryService/system/cluster/core/daemon]] Cluster Node [akka.tcp://InventoryService@127.0.0.1:8090] - Marking node(s) as UNREACHABLE [Member(address = akka.tcp://InventoryService@0.0.0.0:9090, status = Up]

Master node calls Cluster.Leave() and Cluster.Down() on the worker's address:
[DEBUG][07/12/2015 20:39:35][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.ClusterUserAction+Leave
[INFO][07/12/2015 20:39:35][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] Marked address [akka.tcp://InventoryService@0.0.0.0:9090] as Leaving]
[DEBUG][07/12/2015 20:39:35][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.ClusterUserAction+Down
[INFO][07/12/2015 20:39:35][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] Marking unreachable node [akka.tcp://InventoryService@0.0.0.0:9090] as Down
[DEBUG][07/12/2015 20:39:35][Thread 0020][[akka://InventoryService/system/cluster/core/daemon/heartbeatSender]] Cluster Node [akka.tcp://InventoryService@127.0.0.1:8090] - Heartbeat to [akka.tcp://InventoryService@0.0.0.0:9090]
[INFO][07/12/2015 20:39:36][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] Leader is removing unreachable node [akka.tcp://InventoryService@0.0.0.0:9090]

Master confirms the old node will no longer be allowed to join (seems to have a bug though, see the first line - gated instead for akka.tcp://InventoryService@0.0.0.0:9090 ms, which I imagine would be the time it is supposed to be gated):
[WARNING][07/12/2015 20:39:36][Thread 0013][remoting] Association to [akka.tcp://InventoryService@0.0.0.0:9090] with unknown UID is reported as quarantined, but address cannot be quarantined without knowing the UID, gated instead for akka.tcp://InventoryService@0.0.0.0:9090 ms
[DEBUG][07/12/2015 20:39:36][Thread 0015][[akka://InventoryService/system/endpointManager/reliableEndpointWriter-akka.tcp%3a%2f%2fInventoryService%400.0.0.0%3a9090-2/endpointWriter]] Disassociated [akka.tcp://InventoryService@127.0.0.1:8090] -> akka.tcp://InventoryService@0.0.0.0:9090
[DEBUG][07/12/2015 20:39:36][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Association to [akka.tcp://InventoryService@0.0.0.0:9090] having UID [1198519768] is irrecoverably failed. UID is now quarantined and all messages to this UID will be delivered to dead letters. Remote actorsystem must be restarted to recover from this situation.
[WARNING][07/12/2015 20:39:36][Thread 0013][remoting] Association to [akka.tcp://InventoryService@0.0.0.0:9090] having UID [1198519768] is irrecoverably failed. UID is now quarantined and all messages to this UID will be delivered to dead letters. Remote actorsystem must be restarted to recover from this situation.

Worker boots and tries to connect to the master:
[DEBUG][07/12/2015 20:40:20][Thread 0013][remoting] Associated [akka.tcp://InventoryService@127.0.0.1:8090] <- akka.tcp://InventoryService@0.0.0.0:9090
[DEBUG][07/12/2015 20:40:21][Thread 0023][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:21][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:23][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:28][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:33][Thread 0023][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:38][Thread 0022][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:43][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:48][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:53][Thread 0023][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:40:58][Thread 0022][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:41:03][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:41:08][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:41:13][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin
[DEBUG][07/12/2015 20:41:18][Thread 0023][[akka://InventoryService/system/cluster/core/daemon]] [Initialized] Received Akka.Cluster.InternalClusterAction+InitJoin

What is happening here?

Worker:
Booting back up after being killed:
[DEBUG][07/12/2015 20:40:18][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Uninitialized] Received Akka.Cluster.InternalClusterAction+JoinSeedNodes
[DEBUG][07/12/2015 20:40:18][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Uninitialized] Received Akka.Cluster.InternalClusterAction+Subscribe
[DEBUG][07/12/2015 20:40:18][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Uninitialized] Received Akka.Cluster.InternalClusterAction+JoinSeedNodes
[DEBUG][07/12/2015 20:40:20][Thread 0021][[akka://InventoryService/system/cluster/core/daemon]] [Uninitialized] Received Akka.Cluster.InternalClusterAction+Subscribe
[DEBUG][07/12/2015 20:40:18][Thread 0020][[akka://InventoryService/system/cluster/core/daemon]] [Uninitialized] Received Akka.Cluster.InternalClusterAction+Subscribe
[DEBUG][07/12/2015 20:40:21][Thread 0015][[akka://InventoryService/system/endpointManager/reliableEndpointWriter-akka.tcp%3a%2f%2fInventoryService%40127.0.0.1%3a8090-1/endpointWriter]] Drained buffer with maxWriteCount: 50, fullBackoffCount: 1,smallBackoffCount: 0, noBackoffCount: 0,adaptiveBackoff: 10000

And thats it...nothing else gets written to the log!

Full log files:

*

*Master: http://pastebin.com/raw.php?i=WtjEhV1V

*Worker: http://pastebin.com/raw.php?i=QGPxkqEd
Master cluster config:
cluster {
    seed-nodes = ["master's address here"]
    roles = [ InventoryServiceMaster, InventoryServiceWorker ]
    failure-detector {
        acceptable-heartbeat-pause = 5s
        threshold = 10.0
    }
}

Worker's config is the same, but only has the InventoryServiceWorker role.
What am I missing here? Is this a configuration problem? (I'm hoping its not a bug - I've seen someone else report a similar problem on Github).
EDIT:
Just to be clear, I'm not using the Akka.dll from Nuget since it contains a serialization bug - I checked ou the current master applied the fix and did a Release build. The logs have debug information because I kept the PDB from the build.
EDIT 2:
In the worker log, after rebooting, the event Akka.Cluster.InternalClusterAction+JoinSeedNodes appears twice because I originally had a manual call to Cluster.JoinSeedNodes(). I've since removed this but the result is still the same.

A: This has been resolved as of Akka.NET 1.1 - our UID system wasn't implemented correctly prior to that (1.0.5, at the time of this post) but it works fine now.


text:
Q: Xcode Deploy to iPhone 5 and later? My app does not play nice with 3.5 inch screens. How do I deploy to the iPhone 5 and later only? So far my solution is to make the valid architecture arm64 only. But this leaves out the iPhone 5 & 5C.

A: Not building for iphone 4s goes against Apples choice of allowing it to go to iOS9, which is probably why they don't allow people to choose specific device support in the Info.plist.  You can only filter out by features,  so perhaps look for a feature that is not in iPhone 4s but in other devices, and say you only support that type.
https://developer.apple.com/library/ios/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/DeviceCompatibilityMatrix/DeviceCompatibilityMatrix.html


text:
Q: How do I add exposed function signatures to Lua Eclipse? I expose a number of C++ objects and functions to my Lua scripts via ToLua++, for example:
function BeginZone_Toto_Enters()

local mass = Level:GetPhysicsBodyByName("C1"):GetMass();
mass = mass * 50;
Level:GetPhysicsBodyByName("C1"):SetMass(mass);

Level:GetPhysicsBodyByName("C2"):SetActive(false);
Level:GetPhysicsBodyByName("C3"):SetActive(false);
InGameScreen:ShowMessage("Toto say meow,Toto say meowToto say meowToto say meow");

AudioManager:PlaySound("CinematicBoom");
end

I understand that Lua Eclipse allows autocompletion and display of function signatures (and associated descriptions) that are written in Lua, through Lua Doc. Is there a way to have similar functionality with functions that are exposed from an external source?

A: I guess, you may generate fake annotated Lua code from your C++ modules and feed it to the LuaEclipse.


text:
Q: Disable vertical scroll when user scrolling horizontally in android I have a vertical custom list and each item of vertical list contains a horizontal list-view. When I scroll horizontally then list also moves little vertically. Which makes it less user friendly. Can I disable vertical scrolling while scrolling horizontally. I am using
<com.devsmart.android.ui.HorizontalListView
        android:id="@+id/hlistview"
        android:layout_width="match_parent"
        android:layout_height="155dp"
        android:layout_margin="6dp"
        android:background="#fff"
        android:fitsSystemWindows="true"
    />

for horizontal list view

A: The idea is to disable the parent listview to intercept touch event. This might work :
HorizontalListView hv = (HorizontalListView)findViewById(R.id.hlistview);
    hv.setOnTouchListener(new ListView.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                case MotionEvent.ACTION_DOWN:
                    // Disallow ListView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    break;

                case MotionEvent.ACTION_UP:
                    // Allow ListView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    break;
                }

                // Handle HorizontalScrollView touch events.
                v.onTouchEvent(event);
                return true;
            }
        });

Reference : https://stackoverflow.com/a/22609646/1239966

A: Best way to do this.
put given code on your horizontal listview onScroll method it work perfact
ViewParent view_parent = getParent();
if (view_parent != null)
{
 view_parent.requestDisallowInterceptTouchEvent(true);
}


text:
Q: When i create an angular project, it is not getting built successfully? I reinstalled windows recently and have been facing this issue with angular since then.
My old projects are running fine, but when I create new project I am getting the following error.
I have tried to install angular CLI and Node.js again, I also reinstalled VS code.
I have tried adding the paths in the tsconfig.app.json file.
At this point, I am totally clueless.

PS D:\C#LTI\WebApi\new_project_angular> ng build
✔ Browser application bundle generation complete.
Warning: ▲ [WARNING] Comments in CSS use "/* ... */" instead of "//"
D:/C#LTI/WebApi/new_project_angular/src/app/app.component.css:1:18:
  1 │ /******/ (() => { // webpackBootstrap
    ╵                   ~~

Warning: ▲ [WARNING] Unexpected "("
D:/C#LTI/WebApi/new_project_angular/src/app/app.component.css:1:9:
  1 │ /******/ (() => { // webpackBootstrap
    ╵          ^

../../../C#LTI/WebApi/new_project_angular/src/environments/environment.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: D:\C#LTI\WebApi\new_project_angular\src\environments\environment.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
at D:\C#LTI\WebApi\new_project_angular\node_modules@ngtools\webpack\src\ivy\loader.js:64:26
Error: Module not found: Error: Can't resolve 'D:/C#LTI/WebApi/new_project_angular/src/app/app.component.css?ngResource' in 'D:\C#LTI\WebApi\new_project_angular'
Error: The loader "D:/C#LTI/WebApi/new_project_angular/src/app/app.component.css" didn't return a string.


text:
Q: Contour integral of $z^n(1-z)^m$ around circle of radius 2 The problem is $\int z^n (1-z)^m$ along the circle contour parameterised by $2e^{it}$, $t = 0$ to $2\pi$, where $n, m < 0$ are integers.
I've used the keyhole contour argument to show that the radius of the circle doesn't matter as long as it's no less than 2, and the notes say this is useful. We can effectively set our own value $R > 2$ for the radius, so the value of the integral is independent of the radius of the contour. I don't know how to proceed from here.
We were told not to use the residue theorem.
(I asked this yesterday but had a typo in my equation which resulted in a different problem).

A: Hint: consider the limit as $R \to \infty$.


text:
Q: Zend_Log in application.ini is there any example how to setup an instance of zend log from application.ini? I have only found an example for logging to an file, but i want to log into an SQLITE database table?
Zend Log resource

A: Good question.  I can't find a way to instantiate the Zend_Log_Writer_Db from a bootstrap config.  The writer class requires a Zend_Db_Adapter object.  It doesn't accept a string.
The ZF project needs to develop this use case further.  They don't even have any unit tests for Zend_Application_Resource_Log that include a Db writer.
The best I can suggest until then is that you Bootstrap class needs to customize the Log resource in an _initLog() method.
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

  protected function _initDb()
  {
    if ($this->hasPluginResource("db")) {
      $r = $this->getPluginResource("db");
      $db = $r->getDbAdapter();
      Zend_Registry::set("db", $db);
    }
  }

  protected function _initLog()
  {
    if ($this->hasPluginResource("log")) {
      $r = $this->getPluginResource("log");
      $log = $r->getLog();

      $db = Zend_Registry::get("db");
      $writer = new Zend_Log_Writer($db, "log", ...columnMap...);
      $log->addWriter($writer);

      Zend_Registry::set("log", $log);
    }
  }

}

A: Here in the  manual: you can find an example how to write your log file into the database.Is that what you mean?

A: This should work - I will test fully later (not at my dev machine now)
Zend_Application_Resource_Log can setup an instance of a Zend_Log from application.ini
resources.log.writerName = "db"
resources.log.writerParams.db.adapter = "PDO_SQLITE"
resources.log.writerParams.db.dbname = APPLICATION_PATH "/../db/logdb.sqlite"
resources.log.writerParams.db.table = "log"

A: Since ZF 1.10alpha (at least), the following has been true.
// e.g. 1 - works
resources.log.firebug.writerName = "Firebug"
// e.g. 2 - fails
resources.log.writerName = "Firebug"

NOTE: the arbitrary array key 'firebug'. When the Zend_Log factory churns over the resource's log config, example 1 will be passed as an array to Zend_Log->addWriter() (triggering the _constructWriterFromConfig() method), whilst example 2 will simply pass a string (triggering an exception).
(I know this is old, and I'm using a Firebug logger example, but the same applies to all log writers)


text:
Q: Symfony Unit tests failing on Travis CI I'm creating a Symfony 3.4 application.
Then I started to write some tests, which totally pass locally :
/**
  * Two steps :
  * 1) Checks if page goes on 200 status
  * 2) Posts sample datas
  */
    public function testDistanceAmongSequencesAction()
    {
        /**
         * 1 - Access to the page OK
         */
        $this->client->request('GET', '/minitools/distance-among-sequences');
        static::assertEquals(200, $this->client->getResponse()->getStatusCode());
    }

But when I push my code and execute it with Travis CI, it fails automatically : 3) MinitoolsBundleTest\Controller\MinitoolsControllerTest::testDistanceAmongSequencesAction
Failed asserting that 500 matches expected 200.
He is my .travis.yml file :
language: php
sudo: required
dist: trusty

php:
  - '7.1.16'

services:
  - mysql

script:
  - composer self-update
  - composer install --no-interaction --no-suggest
  - bin/console server:run &
  - vendor/bin/phpunit

The PHP version is the same as mine. I think the VM Travis can't access to y path, but why ? Thank you for your help !

A: OK, in my controller I called the TWIG templates using @ annotation, and Travis doesn't understand it. So I modified each call and moved the TWIG into app/ressources. Thanks.


text:
Q: Can a custom Git server provide updates even if it stores no code at all? I read Pro Git book up to Git on the Server chapter, where it shows how to make a Git server: it says that (page 94):

In order to initially set up any Git server, you have to export an existing repository into a new bare
  repository — a repository that doesn't contain a working directory

Once the server was done, I realized that no working directory means no code: if I got this right, no code is stored in our server.
My principal asked me to set up a Git server in our company network to store the most recent production code, but he wants the code to be there: he thinks of this server both as Git server and updates server.
This means that our Git server, with no code inside, should provide updates with the code we developers make.
Is this actually possible or should I give different advices about the updates, splitting the jobs between storing code (with Git server) and providing updates (with another server)?

A: No working directory does not mean no code.  The code history is stored in the database, and that is the primary purpose of a bare repository.

A: As Mark Adelsberger noted, the database (the .git/objects/ and .git/objects/pack/ directories, in a non-bare repository) stores everything.
The point of Git is to store commits, generally forever.  These commits aren't files, although they do (indirectly) contain files.  The objects—files, which Git calls blobs; commits, and two more internal object types called trees and annotated tags—are all stored in a special, compressed (sometimes very compressed), Git-only format.  These are only useful to Git itself, in general.
In order for you, or the rest of your computer, to work with files, they need to be in ordinary format, not some special Git-only format.  Git lets you do this in an area where you will do your own work: a work-tree.
If you have a work-tree, though, you are likely to use it to do work.  If a Git repository is supposed to receive and act upon push requests, what happens to the in-progress work in some poor fellow's work-tree when, out of the blue, bam! someone pushes new stuff into his repository?  Bad things happen, is what.
The obvious solution is the one Git uses: if you're going to receive pushes, eliminate the work-tree.  Now there's nowhere to put in-progress work, so there is never anything that gets overwritten.  That's what a --bare repository is: it eliminates the work-tree, so that there's no place to do work, so it can't be abruptly overwritten by someone else.
There are a number of ways to compromise, but like most compromises, they tend to have various problems.  The bare repository can receive pushes to take commits in, and can accept fetch connection requests to send commits out, and the ony thing that gets overwritten by a push request is the bare repository's idea of which commit any particular branch name means—ideally, in a "fast forward" manner so that this merely adds new commits to the set of commits reachable from the name.  (Remember that in Git, a branch name is just a moveable pointer to one specific commit.  See also What exactly do we mean by "branch"?)


text:
Q: Request timeouts on DigitalOcean NGINX server blocks I'm getting request timeouts when I try to access any of the domains on my droplet in a browser. New droplet at DigitalOcean with Ubuntu 18.04 following How To Set Up Nginx Server Blocks (Virtual Hosts) on Ubuntu 16.04 and How to install a LEMP stack on Ubuntu 18.04
All of the domains are set up in the Networking section for my droplet.
If I ping the domains from my Mac the domain names resolve to the correct IP address but the request times out. If I ping the domains when I'm logged in with SSH they work.
All of the domains have server blocks set up like this:
server {
    listen 80;
    listen [::]:80;

    root /var/www/congressbios.com/public;
    index index.html;

    server_name congressbios.com www.congressbios.com;

    location / {
        try_files $uri $uri/ =404;
    }
}

There is an index.html file in the public directory of each domain root.
Running sudo nginx -t shows success
I've restarted nginx

A: I've done telnet to Your server and also pinged got timeouts.
Try to open ports:
sudo ufw allow http
sudo ufw allow https
sudo ufw allow echo

Doing service scan with nmap confirmed that You've closed ports:
$ nmap -sV congressbios.com

Starting Nmap 7.60 ( https://nmap.org ) at 2018-05-31 02:21 EEST
Nmap scan report for congressbios.com (138.68.62.22)
Host is up (0.35s latency).
Not shown: 998 filtered ports
PORT    STATE  SERVICE VERSION
22/tcp  open   ssh     OpenSSH 7.6p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
443/tcp closed https
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

and only ssh (22) is open:
$ telnet congressbios.com 22
Trying 138.68.62.22...
Connected to congressbios.com.
Escape character is '^]'.
SSH-2.0-OpenSSH_7.6p1 Ubuntu-4

A: Maybe your firewall? Try from a shell on the server...
sudo ufw status

...and make sure you've got port 80 open. You can find more information about configuring the firewall on an Ubuntu server at DigitalOcean here...
https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-16-04
Another option would be try to see if you can get the page locally. That will tell you at least if your nginx configuration is okay. Again from a shell open on the server...
curl 127.0.0.1

And FWIW from here, that domain resolves to an IP address that doesn't respond to pings or http requests...
$ ping congressbios.com
PING congressbios.com (138.68.62.22): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2


text:
Q: Perl: How to print variables and values from @EXPORT I'm trying to create a log that lists all the perlvar I have exported from my package, for debug purposes. I'm having trouble getting the de-referencing from the @EXPORT to work.
I have a package that looks like something like this:
package my_lib;
use strict;
no strict 'refs';
use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
our @ISA qw(Exporter);
our @EXPORT = qw();
use Exporter;

our $var1 = 1;
our $var2 = 5;
our $var3 = $var1 + $var2;
our @vars = [$var1, $var2];

my @my_exported = qw(
    $var1
    $var2
    $var3
    @vars
    );

sub dump_vars {
    foreach my $entry (@my_exported) {
#        my $value =~ s/(\$\w+)/$1/eeg;
        my $value =~ s/\$(\w+)/${$1}/g;
        print "$entry = $value\n";
    }
}

push(@EXPORT, @my_exported);
push(@EXPORT_OK, qw(&dump_vars));

1;

*

*I've tried both versions for dereferencing $value, but it results in an empty string each time

Then I have perl script to generates a log that contains all the values in the package:
#!/usr/bin/perl

use my_lib qw(dump_vars);

#dump_vars();
eval dump_vars();

*

*I tried both versions of calling the subroutine

I use this script like this:
gen_vars_lib_log.pl > vars_lib.log

I'm expecting the log to look something like this:
$var1 = 1
$var2 = 5
$var3 = 6
@vars = [1, 5]

But instead, I get this:
$var1 =
$var2 =
$var3 =
@vars =

Can someone help me see what I'm missing? I've read a bunch of pages on evaluating variables embedded in strings, but I can't get this to work.

A: The substitution operator is used as follows:
$var_to_modify =~ s/.../.../

So the following tries the modify the value of newly-created variable $value.
my $value =~ s/\$(\w+)/${$1}/g;

Always use use strict; use warnings;!! It would have caught that error.
(Yeah, I realize you need use no strict 'refs'; here, though you should limit its scope to the portions of the code where its needed.)

The second issue is that you even try to handle arrays. But before you could even try to do that, you would have to realize that the following creates an array with a single element:
@vars = [ $var1, $var2 ];   # Assign 1 scalar, a reference to an array to @vars

Presumable you wanted
@vars = ( $var1, $var2 );   # Assign 2 scalars to @vars

I'm going to use Data::Dumper to dump the values.

package my_lib;

use strict;
use warnings;

use Data::Dumper qw( Dumper );
use Exporter     qw( import );

our $var1 = 1;
our $var2 = 5;
our $var3 = $var1 + $var2;
our @vars = ( $var1, $var2 );

our @EXPORT = qw(
    $var1
    $var2
    $var3
    @vars
);

our @EXPORT_OK = qw( dump_vars );

sub dump_vars {
    no strict qw( refs );
    local $Data::Dumper::Indent = 0;
    local $Data::Dumper::Terse  = 1;
    for my $entry (@EXPORT) {
        my $value;
        if ($entry =~ /^\$(\w+)\z/) {
           $value = Dumper(${ \$$1 });
        }
        elsif ($entry =~ /^\@(\w+)\z/) {
           $value = Dumper(\@$1);
           $value =~ s/^\[/(/;
           $value =~ s/\]\z/)/;
        }
        elsif ($entry =~ /^\%(\w+)\z/) {
           $value = Dumper(\%$1);
           $value =~ s/^\{/(/;
           $value =~ s/\}\z/)/;
        }
        else {
           next;
        }

        print "$entry = $value\n";
    }
}

1;

Output:
$ perl -I. -e'use my_lib qw( dump_vars ); dump_vars()'
$var1 = 1
$var2 = 5
$var3 = 6
@vars = (1,5)


text:
Q: Behaviour of solutions of a differential system at bifurcation values What are the local and global behavior of solutions of
$$\left\{\begin{array}{ll}r'&=r−r^2\\
\theta'&=(\sin\theta /2)^2+a\end{array}\right.$$
at all bifurcation values?


text:
Q: React JS - Firestore, How to save the UID of an specific collection doc inside the doc I'm trying to register the UID of the New Doc that is going to be generated after I create it so far I Only understand how to make sure the AUTH.UID is the same as the UID of a registered user and so on (basically auth user UID matchs doc user register UID).
What I'm struggling with is How to I "copy" or "get" the UID of a DOC that is about to be created and add it on the information of the Document

So in this picture the doc UID matches not only the outside information but the INSIDE information (if that makes sense) but it also matches my USER UID

Now let's move on to the issue (Idk if I should go straight to the point or explain, I have plenty of questions for a while but now I find this site exists so I'm sorry if I'm asking a lot).
So each USER can create their own personal collection (I think it was the best way to go to not confuse myself)

As you can see the user can create "students" in their own collection of data (so it doesn't mix with the others users students) but I'm unable to grab that doc UID.
I have try to use doc.uid or a whole database.doc.uid and stuff like that and even though I don't get an error in the syntax (until it tries to create it) it doesn't work, so since I was unable to figure out the doc I decided to use the user.uid meanwhile until I find a solution (which I haven't) and I'm pretty sure the fix is something very silly but I can't find "specific" information of the issue I'm having only general situations This is the relevant part of the code
function CrearEstudiante({user}) {

    const register = (e) => {

            e.preventDefault();
               db.collection('usuarios')
               .doc(user.uid)
               .collection('estudiantes').doc()
               .set({

                name: firstName + " " + lastName,
                school: idType1,
                grade: idType2,
                uid: user.uid

            }).then((r) => {
                history.push("/Inicio")
            })
    }

This is what I tried:

*

*db.collection('usuarios').doc(user.uid).collection('estudiantes').uid

*doc.uid

and if I try to add "uid" on the top argument of auth
so like this:
db.collection('usuarios').doc(user.uid).collection('estudiantes').doc(uid).set(
it doesn't like it neither
Any tips are welcome, also I'm NOT using real-time database just the firestore.

A: If you want to know the uid of the document to be created, you can do something like this:
const register = (e) => {
  e.preventDefault();
  const docRef = db.collection('usuarios').doc(user.uid).collection('estudiantes').doc();
  docRef.set({
    name: firstName + " " + lastName,
    school: idType1,
    grade: idType2,
    uid: docRef.id,
    // docRef.id is the id you want.
  }).then((r) => {
      history.push("/Inicio");
  })
}


text:
Q: Get string of all possible characters given iOS keyboard language I'm trying to verify that every character in a text box is limited to the language's keyboard options. This means that in English, you would only be able to type characters which are accessible through the iOS keyboard. If there is a string containing all characters, or a code solution - either will work.
Thanks for the help.

A: Try something like this. Let me know if it helped :) Good luck!
    let letters = CharacterSet.letters
    let text = textField.text
    let range = text.rangeOfCharacters(from: letters)
    if range != nil {
      // Yay it's correct
    }else{
      // Oh no
    }

The CharacterSet documentation has multiple options for the characters you want to restrict the field to. You can even make your own character sets! Check out the link: https://developer.apple.com/documentation/foundation/characterset

A: You could check it like that (is Swift):
let charactersSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
if yourString.rangeOfCharacter(from: charactersSet.inverted) != nil {
    print("string contains special characters")
}

A: You can try some thing like:
NSString *inputString = @"abc0129yourcontent";
BOOL success = [inputString isMatchedByRegex:@"^[0-9a-zA-Z]+$"];

You can convert in Swift if required.


text:
Q: For $1For $1<p<q<\infty$ show $L^q[0, 1] \subset L^p[0, 1]$
I know I'm supposed to use holders inequality to solve this, but can't work it out. We haven't learnt anything about measure theory, so all the answers I've come across previously using measures haven't made sense.

A: There's a very nice proof without Holder. Take $f \in L^q([0,1])$ and write
$\int_0^1 |f(x)|^pdx = \int_{|f|<1,x\in[0,1]} |f(x)|^pdx+\int_{|f|\geq1,x\in[0,1]} |f(x)|^pdx.$
Then use the hypotheses to bound the RHS.


text:
Q: displaying one div after all first div in php foreach I have two div for example div1 and div2. Both div is in same loop but having different contents. I want to display all the elements of div1 and then all the elements of div2 in foreach loop. Right now it is showing div1 content and then div2 content. I want to display all the content of div1 first and then all the contents of div2. How to do this in php loop?
<?php foreach($array as $val){ ?>

test

code

<?php } ?>

if array is having three elements :-
//current output :-
test code test code test code
//Expected outpur :-
test test test code code code

A: Run two loops, first one for div1 and second for div2, that way you will get this

I want to display all the content of div1 first and then all the contents of div2

Ok so you still want to run only 1 loop: You can take some help from variables
$div1=$div2="";
foreach($array as $val){
  $div1.="
$val
";   // store in a temporary variable
  $div2.="
$val
";
}
echo $div1;        //print 1
echo $div2;        //print 2

However in HTML you cant really have multiple elements with same id

A: Just do like this way..
<?php
    $div1_content = '';
    $div2_content = '';
    foreach($array as $val){
        $div1_content .= '
test
';
        $div2_content .= '
test
';
    }
    echo $div1_content;
    echo $div2_content;
?>


text:
Q: Database optimised for set operations I want to know the database or platform that will be most suitable for performing heavy set operations.
Especially INTERSECTION, DIFFERENCE over millions of values in sets.


text:
Q: Server / Client Connection Outside Local Computer Hi I have a socket Server / Client program written in Java I wan't to use this on to devices like Android Phone Client and Mac/Pc Server. My code runs perfect but I'm a bit confuse on How I'm making this connection between devices?. I was thinking on renting a server that supports Java but I'm still not sure yet.
Can someone gave me some tips on this? The server use sockets by the way.

A: It depends on what the socket connection is doing for example if the application is for chat then you probably need a server and every client is handled by a thread in the server


text:
Q: docker confusion between internal and external users so - I'm building a docker container using apache2 on the inside - but I'm having issues with permissions and I don't know how to solve it...
If I run the container with no --user specifications, it runs fine - but I want to externally be able to assign it to a user and limit that user to only reading and writing to a particular directory (the one I map in with -v).
However when I run the docker container with --user to that user, the external permissions seem all correct - but internally - apache2 then goes bang saying it can't bind to port 80 - and other things fail writing to code internally.
How do I map users - like mapping ports or volumes.   What I want to achieve is that the container externally only has the permissions of user X in the outer system - but internally it's root, running as the root user id and so on.

A: One possible way to achieve externally only has the permissions of user X in the outer system - but internally it's root is the use of sudo.
Create an 'internal' user which the UID should be same as the 'external' user:
FROM alpine
RUN apk add --no-cache apache2 sudo \
  && adduser -S newuser -s /bin/ash -D -H -u 1000 \
  && echo "newuser ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/newuser \
  && chmod 0440 /etc/sudoers.d/newuser
USER newuser
EXPOSE 80
ENTRYPOINT ["bin/ash","-c","sudo httpd -DFOREGROUND"]

Example on the host an there's a directory dedicated to a user:
drwx------ 2 ec2-user ec2-user 24 Aug 29 11:53 html

The directory can be mount as usual:
docker built -t myapache2 .
docker run -it -v ${PWD}/html:/html -p 8080:80 myapache2

docker exec -t 31c6cc627813 ls -l /html
total 4
-rwx------    1 ec2-user 1000            58 Aug 29 03:53 index.html

curl localhost:8080

It works!

Alpine is used here but you can of course use any distro that suits your need.
NOTE: httpd site & folder permission is another topic and is not cover here.


text:
Q: Matlab xlsread while Excel File is Open I need to use the xlsread command (and eventually the xlswrite command) in Matlab to import/export data from/to Excel.  However, I need to do this while the excel file is open.  Is this possible? How to do it?
Thanks,
Alaa

A: xlsread is does not care if the file is already open or not.  Just use it with the standard calling convention.
[numData, txtData, rawData] = xlsread('filename.xls')

To use xlswrite on an open file, you need to open the file in a way that allows changes.  There are two ways to do this, by opening it read-only, or using the "share" feature.
To use the "share" feature

*

*First, set up your spreadsheet to allow writes from multiple simultaneous users.  In Office 2007 you do this from the "review" ribbon, "share workbook", "allow changes by more than one user at the same time ..."

*After performing an xlswrite from Matlab, you need to press save in the open file to force the changes to appear.
To open the file read-only
From Excel, press the open icon, select the file, and use the "Open read only" drop down selection in the "Open" dialog box.  In this case it looks like you have to re-open the file to get the new data to appear.

A: Great answer from @Pursuit. You could also try looking at the command actxGetRunningServer.


text:
Q: How to get console integer input from user in a dart program? I want to get integer input from console in dart but unable to do so . How do I do that?
    main()
{
    int n = stdin.readLineSync();
}

A: You need to parse string captured by stdin.readLineSync() using int.parse()
import 'dart:io';
void main() {
    int n = int.parse(stdin.readLineSync());
}


text:
Q: MQTT SSL peer did not return a certificate I generated CA, server and client certificates following the link, https://mosquitto.org/man/mosquitto-tls-7.html
Also added the following lines to the mosquitto server config file.
listener 8883
cafile certs/ca.crt
certfile certs/server.crt
keyfile certs/server.key
require_certificate true

Then I wrote the below javascript client to connect to the server.
    var mqtt = require('mqtt');
    var fs = require('fs');
    var KEY = fs.readFileSync('G:/Projects/test/client.key');
    var CERT = fs.readFileSync('G:/Projects/test/client.crt');
    var TRUSTED_CA_LIST = [fs.readFileSync('C:/Program Files (x86)/mosquitto - Copy/certs/ca.crt')];

    var PORT = 8883;
    var HOST = 'localhost';

    var options = {
      port: PORT,
      host: HOST,
      protocol: 'mqtts',
      keyPath: KEY,
      certPath: CERT,
      passphrase: 'testnode',
      rejectUnauthorized : false,
      //The CA list will be used to determine if server is authorized
      ca: TRUSTED_CA_LIST,
      secureProtocol: 'TLSv1_method',
      protocolId: 'MQIsdp',
      protocolVersion: 3
    };

    var client = mqtt.connect(options);

    client.subscribe('messages');
    client.publish('messages', 'Current time is: ' + new Date());
    client.on('message', function(topic, message) {
      console.log(message);
    });

    client.on('connect', function(){
        console.log('Connected');
    });

But when I run this code, the below error is thrown at the server.
1464240743: New connection from 127.0.0.1 on port 8883.
1464240743: OpenSSL Error: error:140890C7:SSL routines:ssl3_get_client_certifica
te:peer did not return a certificate
1464240743: Socket error on client <unknown>, disconnecting.

A: According to this.
Change keyPath to key, and certPathto cert.


text:
Q: What can other administrators access on my machine? I've been given a new MacBook Pro at work, and it has an administrator account which I assume the IT department has the credentials to. I have been created a local account which is also an administrator.
I'm just wondering, as another administrator, what of my data can they access and read? I have iCloud Drive and other services turned on, and I don't particularly like the idea that someone can go in and grab that stuff.

A: Short answer: Generally an administrator account can access and read any file on the computer. To protect files, either remove all untrusted admin accounts except for yours or encrypt the specific files you need protected with your admin password. Another admin can reset your password, but not see it to unlock things like your keychain. Of course a new password for encryption is ideal if you don't trust another admin.
There are certain files within your account that are encrypted and can not be read without your password.
The main file I'm thinking of is the "Keychain" which may contain your iCloud password and any other passwords you've allowed Safari (or other apps) to remember.

As an IT system administrator myself I would recommend not to store personal data on your work computer that you don't want anyone else to see.
The computer may have backup software that's backing up all files on the computer - including your iCloud Drive.
Also remember that if you're fired, the computer may be taken away before you have a chance to remove your personal files.

A: This document provided by Apple titled: Set up users, guests and groups on Mac covers the types of privileges each user type is allowed.

Administrator: An administrator can add and manage other users, install apps and change settings. The new user you create when you first set up your Mac is an administrator. Your Mac can have multiple administrators. You can create new ones, and convert standard users to administrators. Don't set up automatic login for an administrator. If you do, someone could simply restart your Mac and gain access with administrator privileges. To keep your Mac secure, don't share administrator names and passwords.

Expanding on this, basically an Administrator can access any of your files and pretty much do anything on the system.
References

*

*Protect files from other administrator accounts

A: An Administrator account should be able to install software to log keystrokes, a keylogger.  With your keyboard input captured, any passwords input would be captured and could be used to open otherwise secure applications and files.  I cannot say whether Apple prevents their use on macOS, but anyone sufficiently determined would be able to circumvent such restrictions.
Also, screen capture software can often be used to determine what keystrokes have been made, especially on mobile devices where the on-screen keyboard keys pop-up as typed.
It is not your computer.  Treat it as such.


text:
Q: How do I get user input for Gherkin/Cucumber & Ruby? I need to be able to prompt for user input (username, password and authorisation code) so my tests can access a GUI. These details cannot be stored as test data, so they'll have to be input part way through a test.
I've tried the following, but it's not working how I want:
Feature file:
Feature: user input as part of a test

  Scenario: user input at the start
  Given the test requires a name

Step definition:
Given(/^the test requires a name$/) do
  get_a_name
end

Method:
def get_a_name
  puts "Gimme a name"
  @input_name = gets.chomp
  puts "Hello #{@input_name}"
end

Result:
Gimme a name

Hello Feature: user input as part of a test

Any help would be much appreciated. Thanks.

A: You have a number of options when dealing with external services in test automation. In this particular case you can

*

*Change your source so the authentication behaves differently when testing

OR

*Record a response from the external service and use that response instead of going to the external service (see https://github.com/vcr/vcr). As the response is recorded you will know the authorisation code

OR

*Use a test version of the external service which gives back know responses

I suspect there are a number of other solutions, but all three of the above are used widely and work fine.
There is certainly no need to have manual interactions to test your system unless you are running your tests against a production system (which is a very bad idea!).


text:
Q: Use loopback token for authentication of socket.io I'm working with loopback 2.0 and socket.io 1.0.6.
I'd like to use loopback authentication method for authentication of socket.io.
I found the method to authenticate users in loopback/lib/middleware/token.js. https://github.com/strongloop/loopback/blob/master/lib/middleware/token.js
Then I write like below:
var loopback = require('loopback');
var ioapp = module.exports = socketio;

function socketio(server) {
  var io = require('socket.io')(server);

  // auth
  io.use(function(socket, next) {
    loopback.token()(socket.request, null, next);
  });

  // listeners
  ...

  return io;
};

But actually I won't work and causes error like this.
/Users/.../project_root/node_modules/loopback/lib/models/access-token.js:201
    id = req.param(params[i]);
             ^
TypeError: Object #<IncomingMessage> has no method 'param'
    at tokenIdForRequest (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/models/access-token.js:201:14)
    at Function.AccessToken.findForRequest (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/models/access-token.js:123:12)
    at /Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/loopback/lib/middleware/token.js:53:16
    at Array.0 (/Users/ksuzuki/Projects/appsocially/repo/chat-center/server/socket.js:15:28)
    at run (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:114:11)
    at Namespace.run (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:126:3)
    at Namespace.add (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/namespace.js:155:8)
    at Client.connect (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/client.js:67:20)
    at Server.onconnection (/Users/ksuzuki/Projects/appsocially/repo/chat-center/node_modules/socket.io/lib/index.js:309:10)
    at Server.EventEmitter.emit (events.js:95:17)

I guess this is because I pass the wrong object type to loopback.token() method.

A: Well I believe Loopback token is built to be used with express request object. In the latest version(2.x) you could use it if you override AccessToken.findForRequest and implement it you yourself.
But there's another approach to this which is covered in the official documentation:
Basically it suggest using socketio-auth(Which "provides hooks to implement authentication in socket.io without using querystrings to send credentials, which is not a good security practice") and using AccessToken model directly.
I put the code here with a little bit of simplification:
On server-side:
app.io = require('socket.io')(app.start());
require('socketio-auth')(app.io, {
  authenticate: function (socket, value, callback) {

      var AccessToken = app.models.AccessToken;
      //get credentials sent by the client
      var token = AccessToken.count({
        userId: value.userId,
        id: value.id,
      }, callback);
    }
});

On client-side:
socket.on('connect', function() {
    // You should have retrieved tokenId/userId by calling user.login and
    // saving it in cookies or localStorage.
    socket.emit('authentication', {id: tokenId, userId: userId });
});


text:
Q: Watching a Samba share for modifications from Linux I'm trying to monitor a remote Windows Share for changes (the server can be an actual Windows machine or a Linux machine with Samba server). AFAIK the SMB protocol supports a kind of event-based notification:
http://msdn.microsoft.com/en-us/library/jj216044.aspx
And I can find it implemented server-side in Samba in the change_notify option in smb.conf.
My question is: how can I watch for such events from the client side from a Linux machine? I'd like to setup something that works in a fashion similar to inotifywait and be notified with an event when the content of files on the share changes, or when files are created, deleted or moved.

A: As 2022 I think using systemd path descriptor can work also with SAMBA share.
You have to create a path descriptor and a classical service descriptor, that runs something when triggered by the path:
# Path descriptor

[Unit]
Description=Watch a file this may work also with directory but is untested
Wants=<your_sevice>.service

[Path]
#
PathModified=/path/to/file

[Install]
WantedBy=multi-user.target

And a service descriptor triggerd by the path:
[Unit]
Description=Do something when path changes

[Service]
Type=simple
ExecStart=/path/to/program

[Install]
WantedBy=multi-user.target

As Using systemd path, path descriptors supports other kind of options.
Old answer
An idea is to use Inotify on linux to monitor changing on filesystem.
As SAMBA 3.0.23 (http://wiki.samba.org/index.php/Samba_3.0_Features_added/changed), the protocol now support Inotify, server site, to notify compatible client of filesystem changing.
But, as https://lkml.org/lkml/2007/4/7/129, seems that actually CIFS client does not support correctly Inotify.

A: After 9 years we are still stuck on this issue, but there is interest on the subject. here 2022 article from LWN.


text:
Q: DirectShow on multiple machines with wcf Is it any how possible to run DirectShow on multiple machines with wcf?

A: DirectShow and WCF are completely unrelated.
If your question is if you can stream a DirectShow graph using WCF to other computers then the answer is likely no.
Actually WCF can handle streaming data for SOME transports.
However neither DirectShow has direct support for this (you would have to develop your own graph components) nor has WCF any special media streaming capabilities.


text:
Q: Yet another Java generics "incompatible types" compilation error I checked dozens of threads at stackoverflow and could not find an answer. So, let me show you the minimized version of my class:
class db{
    private int idx;
    private Connection conn;
    db(int _idx){
        idx = _idx;
    }
    void Connect(){
        conn = DriverManager.getConnection("jdbc:mysql://...connection string");
        //System.out.println(conn.getClass().getName());
        //^^^ prints com.mysql.jdbc.JDBC4Connection
    }
    public static void main(String args[]){
       db d = new db(1);
       d.Connect();
    }
}

The code above compiles well. If however I try to convert it to a template class, it does not. The way I do it is like so:
class db<T>{
    private int idx;
    private T conn;
    db(int _idx){
        idx = _idx;
    }
    T Connect(){
        conn = DriverManager.getConnection("jdbc:mysql://...connection string");
        //System.out.println(conn.getClass().getName());
        //^^^ prints com.mysql.jdbc.JDBC4Connection
        return conn;
    }
    public static void main(String args[]){
       db<com.mysql.jdbc.JDBC4Connection> d = new db<com.mysql.jdbc.JDBC4Connection>(1);
       //d.Connect();
    }
}

And this results in a  "incompatible types" compilation error. I think, what I did is just basic - I checked the conn type is com.mysql.jdbc.JDBC4Connection and then I provided it as a template parameter. But for some reason, it does not work. What am I doing wrong?
EDIT
This is the whole error message:
$ javac db.java
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
db.java:34: error: incompatible types
            conn = DriverManager.getConnection("jdbc:mysql://" + host, user, password);
                                              ^
  required: T
  found:    Connection
  where T is a type-variable:
    T extends Object declared in class db
  1 error

A: The line
conn = DriverManager.getConnection("jdbc:mysql://" + host, user, password);

does not compile because the return type of getConnection() (which is Connection) is not known to be a subtype of the declared type of con (which is T, and specified by the caller of the constructor).
Therefore, you must add a type cast. One way to do this is:
conn = (T) DriverManager.getConnection("jdbc:mysql://" + host, user, password);

Here, the compiler will warn you that the cast is unchecked, meaning the correctness of the cast will not be verified at runtime, but succeed even if the connection is of the wrong type. I therefore recommend the more explicit solution:
conn = tClass.cast(DriverManager.getConnection("jdbc:mysql://" + host, user, password));

This reflective cast is checked at runtime, but needs a
Class<T> tClass;

passed as constructor parameter to your DB class.
As an unrelated note, you might wish to constrain the T parameter, because you know that only subtypes of Connection are valid, and abide by Java naming convenctions (lowerCamelCase for methods).
Here is the entire solution:
public class DB<T extends Connection> {
    private final Class<T> tClass;
    private T conn;

    public DB(Class<T> tClass) {
        this.tClass = tClass;
    }

    void connect(){
        conn = tClass.cast(DriverManager.getConnection("jdbc:mysql://...connection string"));
}

which can be used like:
new DB<>(com.mysql.jdbc.JDBC4Connection.class);

A: You defined conn to be of type T, not to Connection like before. So tecnically, T (and therefore conn) can be any object, which is not what your connection method returns.
If you want it to be generic, you need to define it as <T extends Connecion>. That way it will match the returned type

A: In your code, the template/generic type T could be anything.  Someone is allowed to create an instance of this class like new db<Integer>(5), in which case the returned type from Connect would be incompatible.  The compiler sees this impossibility so gives you a compile-time error.
What is your intent in making this class generic?  What other type would you expect could be returned by your Connect method?
Also, typically in Java, one should use capitalized class names and lowercase method names.  Code takes a bit longer to digest when it deviates from typical coding conventions.

A: There is no reason to use generics in the code you have shown us, because as explained in meriton's answer you need to cast to T. It might just as well be:
class db {
    private int idx;
    private Connection conn;
    db(int _idx){
        idx = _idx;
    }
    Connection Connect(){
        conn = DriverManager.getConnection("jdbc:mysql://...connection string");
        return conn;
    }
    public static void main(String args[]){
       db d = new db(1);
    }
}

It may well be that there are other methods in your class which justify the use of generics, but you would need to give more details for us to say for sure.
EDIT
However, if you require generics, here is how you could do it in such a way that does not involve casting to T.
Here is the abstract base class:
public abstract class Db<T extends Connection> {
    private int idx;
    private T t;
    public Db(int _idx) {
        idx = _idx;
    }
    public void setT(T t) {
        this.t = t;
    }
    public abstract T connect();
}

and here is an example of a concrete implementation:
public final class Concrete1 extends Db<JDBC4Connection> {
    public Concrete1(int id) {
        // I'm not sure whether the id is supposed to be the id of the type
        // of Connection. If so you should just pass a specific number
        // e.g. super(1) and get rid of the id parameter.
        super(id);
    }
    @Override
    public JDBC4Connection connect() {
        JDBC4Connection conn = whateverYouNeedToDoToGetSuchAThingIDontKnowIveNeverHeardOfIt();
        setT(conn);
        return conn;
    }
}

You could have other implementations for other specific types, but the idea is that most of the code is generic, and so can be written in the abstract base class.
Some people consider it an antipattern to expose classes that extend a generic class, but are not themselves generic. You may prefer to make the concrete classes private and provide static factory methods to return them:
public static Db<JDBC4Connection> getJDBC4Connection() {
    return new Concrete1(...);
}

I hope this helps!


text:
Q: How to develop a dropdown jtable for searchbar? I want to develop a search bar in java but after each key release event i want to show suggestions in table instead of list because i want to show two columns from database as suggestions.

A:
There are many solutions with combo-box but i want table as a pop down to show suggestions.

You a combo box that displays two columns of data. For example:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;

public class ComboBoxMultiColumn extends JFrame
{
    public ComboBoxMultiColumn()
    {
        getContentPane().setLayout( new GridLayout(0, 2) );

        Vector items = new Vector();
        items.addElement( new Item("123456789", "Car" ) );
        items.addElement( new Item("23", "Plane" ) );
        items.addElement( new Item("345", "Train" ) );
        items.addElement( new Item("4567", "Nuclear Submarine" ) );

        //  Use a JTextArea as a renderer

        JComboBox comboBox1 = new JComboBox( items );
        comboBox1.setRenderer( new TextAreaRenderer(5) );

        getContentPane().add( new JLabel("TextArea Renderer") );
        getContentPane().add( comboBox1 );

        //  Use a JTextPane as a renderer

        JComboBox comboBox2 = new JComboBox( items );
        comboBox2.setRenderer( new TextPaneRenderer(10) );

        getContentPane().add( new JLabel("TextPane Renderer") );
        getContentPane().add( comboBox2 );

        //  Use a JPanel as a renderer

        JComboBox comboBox3 = new JComboBox( items );
        comboBox3.setRenderer( new PanelRenderer(50) );

        getContentPane().add( new JLabel("Panel Renderer") );
        getContentPane().add( comboBox3 );

        //  Using HTML

        JComboBox comboBox4 = new JComboBox( items );
        comboBox4.setRenderer( new HTMLRenderer() );

        getContentPane().add( new JLabel("HTML Renderer") );
        getContentPane().add( comboBox4 );
    }

    class Item
    {
        private String id;
        private String description;

        public Item(String id, String description)
        {
            this.id = id;
            this.description = description;
        }

        public String getId()
        {
            return id;
        }

        public String getDescription()
        {
            return description;
        }

        public String toString()
        {
            return description;
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxMultiColumn();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
    }

    /*
    **  Tabs are easier to use in a JTextArea, but not very flexible
    */
    class TextAreaRenderer extends JTextArea implements ListCellRenderer
    {
        public TextAreaRenderer(int tabSize)
        {
            setTabSize(tabSize);
        }

        public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus)
        {
            Item item = (Item)value;
            setText(item.getId() + "\t" + item.getDescription());
            setBackground(isSelected ? list.getSelectionBackground() : null);
            setForeground(isSelected ? list.getSelectionForeground() : null);
            return this;
        }
    }

    /*
    **  Tabs are harder to use in a JTextPane, but much more flexible
    */
    class TextPaneRenderer extends JTextPane implements ListCellRenderer
    {
        public TextPaneRenderer(int tabColumn)
        {
            setMargin( new Insets(0, 0, 0, 0) );

            FontMetrics fm = getFontMetrics( getFont() );
            int width = fm.charWidth( 'w' ) * tabColumn;

            TabStop[] tabs = new TabStop[1];
            tabs[0] = new TabStop( width, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE );
            TabSet tabSet = new TabSet(tabs);

            SimpleAttributeSet attributes = new SimpleAttributeSet();
            StyleConstants.setTabSet(attributes, tabSet);
            getStyledDocument().setParagraphAttributes(0, 0, attributes, false);
        }

        public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus)
        {
            Item item = (Item)value;

            if (index == -1)
                setText( item.getDescription() );
            else
                setText(item.getId() + "\t" + item.getDescription());

            setBackground(isSelected ? list.getSelectionBackground() : null);
            setForeground(isSelected ? list.getSelectionForeground() : null);
            return this;
        }
    }

    /*
    **  Use a panel to hold multiple components
    */
    class PanelRenderer implements ListCellRenderer
    {
        private JPanel renderer;
        private JLabel first;
        private JLabel second;

        public PanelRenderer(int firstColumnWidth)
        {
            renderer = new JPanel();
            renderer.setLayout(new BoxLayout(renderer, BoxLayout.X_AXIS) );

            first = new JLabel(" ");
            Dimension d = first.getPreferredSize();
            d.width = firstColumnWidth;
            first.setMaximumSize(d);
            second = new JLabel();
            renderer.add(first);
            renderer.add(second);
        }

        public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus)
        {
            Item item = (Item)value;

            first.setText( item.getId() );
            second.setText( item.getDescription() );

            renderer.setBackground(isSelected ? list.getSelectionBackground() : null);
            renderer.setForeground(isSelected ? list.getSelectionForeground() : null);

            return renderer;
        }
    }

    /*
    **  Use HTML to format the text
    */
    class HTMLRenderer extends DefaultListCellRenderer
    {
        private static final String START = "

";
        private static final String MIDDLE = "	";
        private static final String END = "

";

        public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus)
        {
            super.getListCellRendererComponent(
                list, value, index, isSelected, cellHasFocus);

            Item item = (Item)value;
            setText(START
                + item.getId()
                + MIDDLE
                + item.getDescription()
                + END);

            return this;
        }
    }

}


text:
Q: PHP: convert date to datetime and insert it into mysql database? I have an input field in my html page that gets Date from jQuery datepicker.
The format looks like this:
18/02/2017

I have a MYSQL field which is DATETIME
I need to insert the Date above into this MYSQL field.
So i tried this code:
$mysqlDate = date('Y-m-d H:i:s', strtotime($_POST['php_date']));

but the result of $mysqlDate is this:
1970-01-01 01:00:00

Could someone please advise on this issue?
Thanks in advance.

A: Do one thing,
$mysqlDate = date('Y-m-d H:i:s', strtotime(str_replace("/","-",$_POST['php_date'])));
echo $mysqlDate;

Give it a try,
it should work.
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.
Source link.
Your new concern answer,
$mysqlDate = date('Y-m-d H:i:s', strtotime(str_replace("/","-",$_POST['php_date']).' + '.rand(30,60*60*24*3).' seconds'));

A: You have to convert the posted date to a
YYYY-MM-DD

Format before converting it into date time.
You can do
$date=$_POST['php_date'];
list($day,$month,$year)=explode('/', $date);
$date=$year.'-'.$month.'-'.$day;

And then use $date.


text:
Q: jQuery SIMULTANEOUSLY animate all objects in an array I am writing a script that does animations on a web-page.
In the process I need to add several elements to an array, and then simultaneously animate them.
Is it possible to use jQuery to SIMULTANEOUSLY animate all objects in an array? Or maybe there's a better method for that?
Thanx

A: $.each(ARRAY, function(index, value) {
  // do amazing things such as:
  $(this).hide(200);
});

A: If you have several DOM elements in an array, all you need to do is slip them into a jQuery object, and do your animation.
$( arrayOfElements ).fadeOut();


text:
Q: Split string on portion of matched regular expression (python) Say I have a string 'ad>ad>ad>>ad' and I want to split on this on the '>' (not the '>>' chars). Just picked up regex and was wondering if there is a way (special character) to split on a specific part of the matched expression, rather than splitting on the whole matched expression, for example the regex could be:
re.split('[^>]>[^>]', 'ad>ad>ad>>ad')
Can you get it to split on the char in parenthesis [^>](>)[^>] ?

A: You need to use lookarounds:
re.split(r'(?<!>)>(?!>)', 'ad>ad>ad>>ad')

See the regex demo
The (?<!>)>(?!>) pattern only matches a > that is not preceded with a < (due to the negative lookbehind (?<!>)) and that is not followed with a < (due to the negative lookahead (?!>)).
Since lookarounds do not consume the characters (unlike negated (and positive) character classes, like [^>]), we only match and split on a < symbol without "touching" the symbols around it.

A: Try with \b>\b
This will check for single > surrounded by non-whitespace characters. As the string in the question is continuous stream of characters checking word boundary with \b is simplest method.
Regex101 Demo


text:
Q: RxJava: How to interrupt thread on unsubscribe? I use Observable.create() to create an observable to perform some work on a scheduler (e.g. Schedulers.io() and then return a result on AndroidSchedulers.mainThread().
val subscription = observable<T> {
        try {
            // perform action synchronously
            it.onNext(action.invoke(context, args))
            it.onCompleted()
        } catch (t: Exception) {
            it.onError(t)
        }
    }.subscribeOn(scheduler)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    {
                        // handle result here
                        result.set(it)
                    },
                    {
                        // handle error here
                        errorHandler.handleTaskError(model, this, it)
                    },
                    {
                        // notify completed
                        model.completeTask(this)
                    }
            )

The operation inside action.invoke() is synchronous and might be a blocking IO operation. When user decides to cancel it, I unsubscribe from the observable: subscription.unsubscribe()
However, the I/O operation is not being interrupted. Is there any rx-java API to interrupt the operation?

A: When you call yourSubscription.unsubscribe();, Rx will call your unsubscribe code.
This unsuscribe code will be the Subscription class that you can add to your subscriber when you create your Observable.
Observable<Object> obs = Observable.create(subscriber -> {

      subscriber.add(new Subscription() {
            @Override
            public void unsubscribe() {
                 // perform unsubscription
            }

            @Override
            public boolean isUnsubscribed() {
                return false;
            }
        });
      subscriber.onNext(/**...*/);
      subscriber.onCompleted();
}

So in the unsubscribe method, you can interrupt your job, if you have a way to do so.
Please note that the unsubscribe method is called when you unsubscribe from an Observable or when An Observable when it's completed. (it will unsubscribe by itself)
edit : taking vladimir mironov comment in account

A: RxJava schedulers use Furure.cancel(true) to interrupt a running action so if you have an interrupt sensitive operation (such as Thread.sleep()), you should see the thread interruption, although you can't do much about it because at that point, the entire downstream chain has been unsubscribed and no further events are can reach your subscriber.
If your action is not sensitive to interruption and it doesn't provide any standard means to interrupt it (such as calling close() on a socket, or cancel() on a JDBC statement), RxJava can't do much about it.
If you can call some close() method asynchronously, consider using using() which let's you specify a cleanup callback that can close your resource on unsubscription.

A: As far as I know it's impossible with RxJava.
You can keep reference to the action object outside of the observable and interrupt it along with unsubscribe call.


text:
Q: Using CAST with an insert into ... select I am trying to cast some bad data into proper data using CAST(column AS DECIMAL(7,2)), which works when just SELECTing, but once combined with an INSERT statement, the statement fails:
/* setup */
drop table if exists dst;
create table dst (
  id int not null auto_increment
  , columnA decimal(7,2)
  , primary key (id)
);

drop table if exists src;
create table src (
  id int not null auto_increment
  , columnA varchar(255)
  , primary key (id)
);

insert into src (columnA) values ('');

/* test */

/* This works as I would like it to*/
select CAST(columnA AS decimal(7,2)) from src; /* returns 0.00 */

/* This fails */
insert into dst (columnA)
select CAST(columnA AS decimal(7,2)) from src;
/*0 19  21:01:56    insert into dst (columnA)
 select cast(columnA as decimal(7,2)) from src  Error Code: 1366. Incorrect decimal value: '' for column '' at row -1   0.000 sec*/

Edit: this is a pared down reproduction example - the data I am
  working with is much more varied than just an empty string - it might
  also be a non-numeric string value or a numeric value that is outside
  of the bounds of decimal(7,2) - in which the CAST statement works
  the way I would like it to when only in a SELECT but fails when
  trying to use them as part of the INSERT.

Am I doing something wrong, or is there another way to achieve what I am looking for?
I am using MYSQL 5.6.11 on WIN 7 x64

A: Set explicitly the value for the empty string with CASE or IF:

*

*SELECT CASE WHEN columnA = '' THEN 0 ELSE CAST(columnA AS decimal(7,2)) END
FROM src;

*SELECT IF(columnA <> '', CAST(columnA AS decimal(7,2)), 0)
 FROM src;
Or use 2 SELECTs with UNION ALL :
SELECT CAST(columnA AS decimal(7,2))
FROM src
WHERE columnA <> ''
 UNION ALL
SELECT 0
FROM src
WHERE columnA = '';

A: You can try using REGEXP to filter out any irregularities in source data:
INSERT INTO dst (columnA)
SELECT CAST(CASE
               WHEN columnA REGEXP '^[0-9]{0,7}(\.[0-9]{0,2})$' THEN columnA
               ELSE 0
            END AS decimal(7,2))
FROM src;

SQL Fiddle Demo here


text:
Q: How to find the maximum? I have in mind $$\max\left( \sqrt{(x-1) (y-x)}+\sqrt{(1-x) (7-y)}+\sqrt{(y-7) (x-y)}\right)$$
for $x\geq -2\land x\leq 3\land y\geq 0\land y\leq 11 $, of course, taking into account real values of the roots only. In order to avoid complex numbers I consider
f=(Sqrt[(x - 1)*(y - x)] + Sqrt[(7 - y)*(1 - x)] + Sqrt[(x - y)*(y - 7)])*
Boole[(x - 1)*(y - x) >= 0]* Boole[(7 - y)*(1 - x) >= 0]*Boole[(x - y)*(y - 7) >= 0]

Unfortunately, its plot does not give any prompt to me.
Plot3D[f, {x, -2,  3}, {y, 0, 11}]

Both
NMaximize[{f, x >= -2 && x <= 3 && y >= 0 && y <= 11},{x, y},AccuracyGoal-> 3,MaxIterations->200]

NMaximize::cvmit: Failed to converge to the requested accuracy or precision within 200 iterations. {0., {x -> 3., y -> 11.}}

and
FindMaximum[{f, x >= -2 && x <= 3 && y >= 0 && y <= 11}, {x, y}]

{0., {x -> 0.914707, y -> 9.31719}}

do not produce a correct answer in view of
f /. {x -> 1, y -> 3}

$ 2 \sqrt{2}$

A: In general, maximization and minimization algorithms will probably have difficulty when attempting to find a max/min when the landscape is mostly flat except at single values. Most of these algorithms take into account the shape of the landscape to direct them towards their goal, and if the function yields 0 almost everywhere, then it has no idea which direction to take.
I would say that doing a little bit of the work by hand first like Ulrich suggested is going to be the most successful route even though it's not as automated as you'd like. For this problem, however, I found the following worked well:
NMaximize[{f, -2 <= x <= 3, 0 <= y <= 11}, {x, y},
 MaxIterations -> 500, Method -> "DifferentialEvolution"]

Set the Method to "DifferentialEvolution" and increase the MaxIterations.
EDIT: The following also works and provides exact solutions.
Maximize[{f, -2 <= x <= 3, 0 <= y <= 11}, {x, y}]

A: If you replot the function
Plot3D[f, {x, -10,10}, {y, -10, 10}, Exclusions -> None, MaxRecursion ->5,AxesLabel -> {x, y, f}]

you can see that the maximum requires y==x!
Plot[f /. y -> x, {x, -5, 10}]

maximum lies on the left or right border of given x-intervall!

A: Well, this is not very suprising. Your function has imaginary parts pretty much everywhere, so the product of the Boole is zero practically everywhere.
Consider the function without the Boole part and plot its imaginary part
f = (Sqrt[(x - 1)*(y - x)] + Sqrt[(7 - y)*(1 - x)] + Sqrt[(x - y)*(y - 7)])
Plot3D[Im[f], {x, -2, 3}, {y, 0, 11}, PlotPoints -> 50]

You'll get something like this

So there are purely real numbers only along the lines $$y=7 \land 1\leq x \leq3$$, $$x=1 \land 1\leq y\leq 7$$ and $$x=y \land 0\leq x \leq 1$$
This is near impossible to catch with a general purpose optimizer. You'd be much better of by considering the three segments where f is real independently
f1 = f /. x -> 1;
f2 = f /. y -> 7;
f3 = f /. y -> x;

Maximize[ {f1, 0 <= y <= 11}, y]
Maximize[ {f2, -2 <= x <= 3}, x]
Maximize[ {f3, -2 <= x <= 3}, x]

And you'll get
{3, {y -> 4}}
{2 Sqrt[2], {x -> 3}}
{3 Sqrt[3], {x -> -2}}


text:
Q: How to omit the system fields when retrieving all fields for an object using Schema.getGlobalDescribe()? I am creating a dynamic query by passing the object using Schema.getGlobalDescribe(). The result includes system fields that you cannot query (in workbench or query editor).
Example: For contact object, the total fields retrieved includes
hasoptedoutofemail, hasoptedoutoffax, donotcall fields which you cannot query further to retrieve data.
Any suggestions please?

A: What you are facing I get typically when the schema call is in a utility apex class constructing a SOQL string and the final database.query() resides in a different class, such as a controller or trigger. Now if both apex files got different API Versions, the Schema call returns potentially obsolete fields which might not exists in the other class.
I make heavy use of schema since I write almost ALL queries with the help of utility functions to allow SELECT * FROM ... because I hate long and hard to maintain lists of field names as we should write it in vanilla apex.
If this might be true in your case, just keep all your apex classes at the same API version and you will be fine. If you can't match the versions, you could selectively exclude those fields. I did that with an self made query  syntax looking like this SELECT *.not(fieldname1|fieldname2|....)
More details and an older version of my utility class you can find here
Howto wildcard SELECT * to query all fields of objects in APEX?

A: I check this in my org and I don't get the fields hasoptedoutoffax, donotcall on contact using describe.
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap();

for(String str : objectFields.keySet())
    system.debug(str);

I only found the hasoptedoutofemail in describe. When I query on this I get the result.

If you still want to filter fields, you can use DescribeFieldResult Class to filter out field based on if current user can create/access the field. If field is custom or standard.


text:
Q: Xdebug profiler and xdebug_time_index() give different values I used Xdebug to profile my PHP application.
When I open the generated profile file with WinCacheGrind, it gives me a total cumulative time of 3ms for {main} (0.003s).
However, when I use the function xdebug_time_index() at the end of my code, it returns a time of 0.03s.
Anyone knows what might cause this difference and which one is more representative ?

A: Any chance adding that function actually increases the time needed?
Also, I can imagine the profiler will actually start running when PHP runs (time index 0) while XDebug's internal counter can start a bit earlier.