text:
Q: One to One response using pusher I am trying to create a one to one response between a user and an admin using laravel and pusher. The user is not logged in, just a visitor. When the user visits the site, they will type something and send it to an admin. If any admin is online they will click yes or no and this will then get sent back to the USER who sent it.
My issue is that I can not seem to get pusher to send the responses. I have seen this Pusher one to one chat structure but i do not quiet understand as in my scenario it is not a chat room and that is more specific to a chat room.
Anyways I have tried to use the session id but that didn't work as the user and admin are not on the same browser. I thought about somehow sending the session id with the pusher notification message but I similar did know how because the admin is on a /admin/events page while the user is on the home page.
This is my code
push.js
  var pusher = new Pusher('MY KEY');

  var channel = pusher.subscribe ('client');

  channel.bind('general_response', addMessage);

  var channel = pusher.subscribe ('customer_response');
  //bind to new_response on the channel
  channel.bind('message', addWaitingResponse);

  //user
  function addMessage (data) {
    //create list item
    var li = $('

');
    //Get text properity from data
    li.text(data.text);
    //hide it
    li.hide();
    //prepend to messages
    $('#messages').prepend(li);
    li.slideDown();
  }

//admin
function addWaitingResponse(data) {
    var li = $('

 ');
    li.text(data.text);
    li.hide();
    $('#WaitingNotification').prepend(li);
    li.slideDown();
  }

subscribing and listening
<?php
 namespace Scan\Subscriber;

class NotificationEventSubscriber {

    private $_pusher;
    public function __construct() {

        $this->_pusher = new \Pusher($_ENV['app_key'], $_ENV['app_secret'], $_ENV['app_id']);

    }

    //message to admin
    public function onCreate($event) {

            //$pusher = new \Pusher($_ENV['app_key'], $_ENV['app_secret'], $_ENV['app_id']);

            $data = array('text' => $event->track_no 'is awaiting approval');

            $this->_pusher->trigger('customer_response', 'message', $data);

        }
        //message to user

    public function onUpdate($event) {
            /*
            | Notify customer
            */

            $message = array('text' => $event->track_no' has been approved ');

            $this->_pusher->trigger('client', 'general_response', $message);

    }

    public function subscribe($events) {

            $events->listen('notification.insert','Scan\Subscriber\NotificationEventSubscriber@onCreate');

            $events->listen('notification.update','Scan\Subscriber\NotificationEventSubscriber@onUpdate');

    }

}

In laravel when the user sends the requests, I register and fire the event. The code above just shows how I am displaying the message to the user and admin
My question is: How do I make the admin response ONLY sent to the user who sent the request? Thank you very much.

A: It sounds like you are on the right lines. You need some way of creating a unique identifier that both the anonymous user and the admin user know about. That identifier can then be used to route messages - probably via a Pusher channel.
Since the user is anonymous using the session ID as part of a unique channel name for that user seems like a good idea.
Alternatively you could make the server respond with a unique ID when the anonymous user sends a request for help. With this in mind, here's a diagram showing a potential way of achieving this:

Once the above process has completed the Admin and the anonymous User can now communicate by triggering events on the channel identified by the request_id.


text:
Q: How to align contents title in Portuguese documents? In Portuguese, the name of "Table of Contents" is "Sumário". So, I'd like to get the word "Sumário" in the center of the page.
I know how to put the title in the center:
\documentclass{article}
\usepackage{tocloft}
\renewcommand{\contentsname}{\hfill\bfseries\Large Contents\hfill}
\renewcommand{\cftaftertoctitle}{\hfill}
\begin{document}
\tableofcontents
\end{document}

I also know how to replace "Table of Contents" by "Sumário":
\documentclass{article}
\usepackage[english,brazil]{babel}
\begin{document}
\tableofcontents
\end{document}

However, these two solutions does not work together. When using both, we obtain the word "Sumário", but not in the center.
What could I do?
Remark: I'm also using \usepackage{tocloft} and \usepackage[english,brazil]{babel} for other purposes in the documment. So, they cannot be removed from the preamble (i.e. the solution have to be compatible with both).

A: Simply merging your solutions doesn't work because babel defers the definition of the section headers after the \begin{document}. You can overcome this by inserting the \renewcommand{\contentsname} after \begin{document}:
\documentclass{article}
\usepackage[english,brazil]{babel}
\usepackage{tocloft}
\begin{document}
\renewcommand{\contentsname}{\hfill\bfseries\Large Sum\'ario\hfill\null}
\tableofcontents
\end{document}

As remco pointed out in the comments, the redefinition of \contentsname happens when you switch the language, for example, with \selectlanguage. So after every language-switching command you have to re-reset the \contentsname.
Another alternative is to add the redefinitions to \captionsbrazil:
\documentclass{article}
\usepackage[english,brazil]{babel}
\usepackage{tocloft}
\addto\captionsbrazil{\renewcommand{\contentsname}{\hfill\bfseries\Large Sum\'ario\hfill\null}}
\begin{document}
\tableofcontents
\end{document}

This would make the new definition of \contentsname as the "default". But I don't know about the robustness of this, because the \captions<language> macro is supposed to have only the names of the headers...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook notification from my app appears and disappears I have a problem since a several days now. Facebook notifications from my app (the red number one) appears and disappears. This functioning properly at first, but then but then stopped working.
I tried by entering in the Website url -> http://mipagina.com, in the canvas url -> http://mipagina.com/ and the secure url https.... I tried many other ways but nothing. I realized that the app request don't send a notification to the user for his acceptance. But I can add the app from the app page. If the user add the app the red number one appears and then disappears but the notification from my app shows in the facebook notifications page. But if the user doesn't add the app, the red number one appears and then disappears and then the notification doesn't appear in the facebook notifications page.
Hope you can help me...Please sorry for my english.

A: Since "user-to-user requests are only available in canvas apps" (see here), you must make sure your canvas app is properly set up.
Review that you have done ALL of the following steps:

*

*Set Sandbox Mode to off

*Selected a Namespace for your app

*Enabled App on Facebook (which is the canvas app settings)

*Filled out Canvas URL and Secure Canvas URL
Facebook will not notify you in its Javascript API about these issues: there it will seem like the app request notification has indeed successfully been delivered.


text:
Q: Localizing Bondy's metaconjecture on hamiltonicity Definitions:
Let $G$ be a graph on $n$ vertices. $G$ is Hamiltonian provided $G$ has a cycle of length $n$. $G$ is pancyclic provided $G$ has a cycle of length $\ell$ for every $3 \leq \ell \leq n$.
Background:
Dirac [1952] showed that if $G$ has $n \geq 3$ vertices and every vertex has degree at least $\frac{n}{2}$, then $G$ is Hamiltonian. Bondy [1971] showed this condition implies that either $G$ is the complete bipartite graph $K_{\frac{n}{2},\frac{n}{2}}$ or $G$ is pancyclic. Bondy [1973] then proposed the following metaconjecture (which I quote from Kevash and Sudakov 2010):

Metaconjecture. Almost any non-trivial condition on a graph which implies that the graph is Hamiltonian also implies that the graph is pancyclic. (There may be a simple family of exceptional graphs.)

Another instance of this metaconjecture is the following corollary of a theorem of Clark [1981].

Let $G$ be a connected, locally connected, claw-free graph on at least $3$ vertices. Then $G$ is pancyclic.

Given property $\mathcal{P}$ (such as "connected"), a graph is locally $\mathcal{P}$ provided the neighborhood of every vertex is $\mathcal{P}$. A graph is claw-free provided it has no induced copies of $K_{1,3}$. Being claw-free is equivalent to being locally $\overline{K_3}$-free.
It seems to me that such local properties might eliminate bothersome exceptional cases. Might we be able to prove a localized version of Bondy's metaconjecture such as the following?

Tentative Subconjecture. Let $\mathcal{P}$ be a graph property such that every connected graph on at least $3$ vertices that is locally $\mathcal{P}$ is Hamiltonian. Then every connected graph on at least $3$ vertices that is locally $\mathcal{P}$ is pancyclic.

A monotonicity assumption on the property--for example, if $A$ satisfies $\mathcal{P}$ and $A$ is a subgraph of $B$ and $|A|=|B|$ then $B$ satisfies $\mathcal{P}$--might also be useful.
(This question is inspired by Ortrud Oellermann's presentation at the 2016 Prairie Discrete Math Workshop.)


text:
Q: How can I disable the system feedback when using the "fn" button on a Touch Bar-equipped MBP? I use Shush to auto-mute my microphone on voice and video calls, where I toggle my mic on by holding the fn key.  But on a Touch Bar equipped MBP, the system issues a click and pop noise when pressing and releasing the fn button, and it's driving me batty.
How can I disable this feedback noise?  (And how did you figure this out?)
Update: I should note a few settings:

*

*System Preferences > Sound > Sound Effects > Play user interface sound effects is OFF

*System Preferences > Keyboard > Dictation is OFF

A: How embarrassing: the clicks were due to Shush's audio cues. I thought I had disabled them.

A: It's likely that you have enabled Dictation which is what that key is configured for by default.
You can disable this as follows:

*

*Click on the Apple menu

*Open "System Preferences"

*Select "Keyboard"

*Select "Dictation"

*Set "Dictation" to "Off"


text:
Q: URL for testing my app on facebook I'm just starting a new app with the php-sdk. I've done an app a few years ago, but this is the first time with the newer setup dialogs.
The canvas url is pointing to my web server and the app's subdirectory.
Right now this is the only code in my app...just the "hello world" from the php-sdk sample.
<?php
include 'facebook.php';
$facebook = new Facebook(array(
'appId'  => 'myappid',
'secret' => 'mysecret',
));
// Get User ID
$user = $facebook->getUser();
?>

Yes, the appid and secret are the actual numbers.
I've waited several minutes to propagate but when going to https://apps.facebook.com/myappsname it just tosses me a 404 error. Is there another URL I should go to when it's in sandbox?

A: To get https://apps.facebook.com/[APP_NAMESPACE] working, you must specify [APP_NAMESPACE] the App Namespace in the Dev App (https://developers.facebook.com/apps) under Basic settings.


text:
Q: Set background image of Button in Objective-C I get a problem that I cannot set the background image to the UIButton. My button is a colour button and I want to have an image at the background of the button. And also, I can increase the size of the background image. My code is:
in .h
@property (weak, nonatomic) IBOutlet UIButton *color1;

in .m
UIImage *colorimage = [UIImage imageNamed:@"57_bg_selected"];
[_color1 setBackgroundImage:colorimage forState:UIControlStateNormal];

What I got is background image is step on the button.

A: Button should be of custom type to set an image. Verify your code once again. Set the button to custom type in Storyboard.

A: I can see you are using IBOutlet of a button this means you are using button from nib, then you should change background image from Attributes Inspector on right side of your xcode
otherwise if you still need it to be changed programmatically
then try this
[self.color1 setBackgroundImage:[UIImage imageNamed:@"57_bg_selected.png"] forState:UIControlStateHighlighted];

Please Note you should mention extension of your image .jpg or .png in your file name

A:
I have a button and this button has a back color.

Are you trying to set the background color as well as background image of the button. You can only apply one thing at a time.

*

*Verify if your button's type is System or Custom.

*As you are having image in interface builder, try to set the background image property in xib/storyboard.


text:
Q: Is there built in method to get all __annotations__ from all base classes in Python? We have builtin dir() function to get all attributes available for class or instance, defined in based classes.
Is there same for annotations? I'd like to have get_annotations() function, which works like this:
def get_annotations(cls: type): ...  # ?

class Base1:
    foo: float

class Base2:
    bar: int

class A(Base1, Base2):
    baz: str

assert get_annotations(A) == {'foo': float, 'bar': int, 'baz': str}

A: This should do the trick, right?
def get_annotations(cls: type):
    all_ann = [c.__annotations__ for c in cls.mro()[:-1]]
    all_ann_dict = dict()
    for aa in all_ann[::-1]:
        all_ann_dict.update(**aa)
return all_ann_dict

get_annotations(A)
# {'bar': int, 'foo': float, 'baz': str}

Or a one-liner version of it:
get_annotations = lambda cls: {k:v for c in A.mro()[:-1][::-1] for k,v in c.__annotations__.items()}

get_annotations(A)
# {'bar': int, 'foo': float, 'baz': str}


text:
Q: Error: "Cannot add children to a ResourceDictionary when the Source property is set." I tried to add a global style that would be applied to all my control in my app.
I added my style in app.xaml:
<Application x:Class="SimulatorUi.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

        <Style TargetType="Button">
            <Setter Property="Background" Value="Red"></Setter>
            <Setter Property="FontSize" Value="24"></Setter>
        </Style>

    </Application.Resources>
</Application>

It work fine in a test app. But when I add the style to my real app, I receive a compiler error:
"Cannot add children to a ResourceDictionary when the Source property is set.".
I cannot figure out what I am doing wrong. Any helps would be appreciate?
Note1:
I can add a resource dictionary without problem:
<Application x:Class="WpfAppTestResource.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Note 2: (original question related only)
My app use "Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase" to ensure to run only a single instance. I was missing the "InitializeComponent()" before the _application.Run() which is essential. I fixed one problem, but I still have my initial problem and my test using SingleInstance pattern does work fine. Only my real app does fail to run properly.
Code used for Single Instance:
namespace WpfApplication1.SingleInstanceApp
{
    public class SingleInstanceManager : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
    {
        private App _application;
        private System.Collections.ObjectModel.ReadOnlyCollection<string> _commandLine;

        private static readonly SingleInstanceManager _instance = new SingleInstanceManager();

        private SingleInstanceManager()
        {
            IsSingleInstance = true;
        }

        public static SingleInstanceManager Instance
        {
            get { return _instance; }
        }

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
        {
            // First time _application is launched
            _commandLine = eventArgs.CommandLine;

            _application = new App();

            // Missing line in original code which I had to adapt.
            // _application.InitializeComponent();
            if (_contentLoaded)
            {
                return false;
            }
            _contentLoaded = true;

            // this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
            System.Uri resourceLocater = new System.Uri("/" + Assembly.GetExecutingAssembly().GetName().Name + ";component/app.xaml", System.UriKind.Relative);
            System.Windows.Application.LoadComponent(_application, resourceLocater);

            _application.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            // Subsequent launches
            base.OnStartupNextInstance(eventArgs);
            _commandLine = eventArgs.CommandLine;
            _application.Activate();
        }
    }
}

namespace WpfApplication1.SingleInstanceApp
{
    public class EntryPoint
    {
        [STAThread]
        public static void Main(string[] args)
        {
            SingleInstanceManager manager = SingleInstanceManager.Instance;
            manager.Run(args);
        }
    }
}

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        // ******************************************************************
        protected override void OnStartup(StartupEventArgs e)
        {
            // AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            // TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            base.OnStartup(e);
            this.MainWindow = new MainWindow();
            MainWindow.Show();
        }

        // ******************************************************************
        public void Activate()
        {
            MainWindow.Activate();
        }

        // ******************************************************************
    }
}

A: I fixed part of the problem by adding code equivalent of _application.InitializeComponent(); in OnStartup of SingleInstanceManager.
After I fixed the bug in OnStartup, the problem was still there.
I restarted Visual Studio and the the problem disapeared !!!   Grrrrrrrrrrrrrrrr!!!

A: I did not even have to restart visual studio. I cut and pasted my UserControl.Resources right above my x:Code and the error went away. It was right below it before.


text:
Q: Choose to show notification to user in Foreground Swift 5 [iOS] My App always Show notifications in Background and Foreground, bu it must ignore the notification sometimes according to the type.
Two functions do the job on Foreground Notifications:

*

*userNotificationCenter: It works only on Foregroud Notifications.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .badge, .sound])
}

*

*application: It works when the user tap the notification

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    ... JOB ...
}

I need to prevent (in foreground) "userNotificationCenter" from showing the visible notification sometimes but always run "application" (the job).
How can I directly call "application" without using "completionHandler([.alert, .badge, .sound])"


text:
Q: Play ScalaJSON Reads[T] parsing ValidationError(error.path.missing,WrappedArray()) i have a funny json data looking as:
[ {
  "internal_network" : [ {
    "address" : [ {
      "address_id" : 2,
      "address" : "172.16.20.1/24"
    }, {
      "address_id" : 1,
      "address" : "172.16.30.30/24"
    } ]
  } ],
  "switch_id" : "0000000000000001"
}, {
  "internal_network" : [ {
    "address" : [ {
      "address_id" : 2,
      "address" : "172.16.30.1/24"
    }, {
      "address_id" : 1,
      "address" : "192.168.10.1/24"
    }, {
      "address_id" : 3,
      "address" : "172.16.10.1/24"
    } ]
  } ],
  "switch_id" : "0000000000000002"
} ]

i wrote case classes and custom reads:
  case class TheAddress(addr: (Int, String))
  implicit val theAddressReads: Reads[TheAddress] = (
    (__ \ "address_id").read[Int] and
      (__ \ "address").read[String] tupled) map (TheAddress.apply _)

  case class Addresses(addr: List[TheAddress])
  implicit val addressesReads: Reads[Addresses] =
    (__ \ "address").read(list[TheAddress](theAddressReads)) map (Addresses.apply _)

  case class TheSwitch(
    switch_id: String,
    address: List[Addresses] = Nil)
  implicit val theSwitchReads: Reads[TheSwitch] = (
    (__ \ "switch_id").read[String] and
    (__ \ "internal_network").read(list[Addresses](addressesReads)))(TheSwitch)

  case class Switches(col: List[TheSwitch])
  implicit val switchesReads: Reads[Switches] =
    (__ \ "").read(list[TheSwitch](theSwitchReads)) map (Switches.apply _)

when i validate the provided data with:
val json: JsValue = Json.parse(jsonChunk)
println(json.validate[TheSwitch])

i get:
JsError(List((/switch_id,List(ValidationError(error.path.missing,WrappedArray()))), (/internal_network,List(ValidationError(error.path.missing,WrappedArray())))))

i can access it with JsPath like
val switches: Seq[String] = (json \\ "switch_id").map(_.as[String])

but i'm really at my wits end with what am i doing wrong with custom reads.
i've tried with putting another top level key, and other combinations, but seems i'm missing something crucial, since i've started with this just today.
thanks a lot.

A: The error is telling you that instead of /switch_id it got an array. So it seems like you should read the JSON as a List[Switch] instead of just Switch
Assuming your Reads (didn't test them) are correct this should work:
val json: JsValue = Json.parse(jsonChunk)
println(json.validate[List[TheSwitch]])


text:
Q: JavaFX FXMLLoader InvocationTargetException and NullpointerException i'm new to java and mvc and trying to do an example witha separation between Business logic and Frontend
this small app do the following:
we have a textField and label.
if you write something at the textField then you will become a text at the label ... it makes calculation which letter has the most ocurence.
i'm trying to run the app but i become a Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
Trace :
"C:\Program Files\Java\jdk1.8.0_181\bin\java.exe" "-javaagent:C:\Users\khale\AppData\Local\JetBrains\IntelliJ IDEA 2019.1.2\lib\idea_rt.jar=62820:C:\Users\khale\AppData\Local\JetBrains\IntelliJ IDEA 2019.1.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_181\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\rt.jar;C:\Users\khale\OneDrive\Dokumente\NetBeansProjects\ShowCharWithHighestOccurrence\target\classes" com.mycompany.showcharwithhighestoccurrence.MainApp
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$KeyHandler.process(Scene.java:3964)
    at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3910)
    at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2040)
    at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2501)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:217)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:149)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleKeyEvent$352(GlassViewEventHandler.java:248)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:247)
    at com.sun.glass.ui.View.handleKeyEvent(View.java:546)
    at com.sun.glass.ui.View.notifyKey(View.java:966)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    ... 29 more
Caused by: java.lang.NullPointerException
    at com.mycompany.showcharwithhighestoccurrence.javafxFrontend.FXMLController.showCharWithHighestOccurence(FXMLController.java:34)
    ... 39 more

Scene.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="com.mycompany.showcharwithhighestoccurrence.javafxFrontend.FXMLController">
  <children>
    <TextField fx:id="textField" layoutX="14.0" layoutY="90.0" onKeyReleased="#showCharWithHighestOccurence" prefWidth="209.0" />
    <Label fx:id="outputLabel" layoutX="14.0" layoutY="112.0" prefHeight="32.0" prefWidth="293.0" text="" />
  </children>
</AnchorPane>

MainApp.java
package com.mycompany.showcharwithhighestoccurrence;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add("/styles/Styles.css");

        scene.onKeyTypedProperty();
        stage.setTitle("JavaFX and Maven");
        stage.setScene(scene);
        stage.show();
    }

    /**
     * The main() method is ignored in correctly deployed JavaFX application.
     * main() serves only as fallback in case the application can not be
     * launched through deployment artifacts, e.g., in IDEs with limited FX
     * support. NetBeans ignores main().
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

FXMLController.java (Controller)
package com.mycompany.showcharwithhighestoccurrence.javafxFrontend;

import java.net.URL;
import java.util.*;

import com.mycompany.showcharwithhighestoccurrence.javafxBusinessLogic.BusinessLogic;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;

public class FXMLController implements Initializable {

    @FXML
    private TextField textField;

    @FXML
    private Label outputLabel;

    private BusinessLogic businessLogic;

    @FXML
    private void showCharWithHighestOccurence(KeyEvent event) {

        String input, output = "";
        businessLogic.hello();

        if (textField.getText() != null) {
             input = textField.getText();
             if (businessLogic.giveFinalResult(input) != null) {
                 output = businessLogic.giveFinalResult(input);
                 if (output != null) {
                     outputLabel.setText(output);
                 }
             }
        }

    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }
}

BusinessLogic.java
package com.mycompany.showcharwithhighestoccurrence.javafxBusinessLogic;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BusinessLogic {

    public void hello(){
        System.out.println("helllllo");
    }

    public String giveFinalResult(String text) {

        String input = " ";
        String output = " ";
        if (text != null) {

            input = text.toLowerCase().replaceAll("\\s+", "");

            int[] freq = new int[input.length()];
            int i, j, max, lastFreq;
            lastFreq = 0;

            //Converts given string into character array
            char inputChars[] = input.toCharArray();

            List<Character> maxChars = new ArrayList<>();

            //Count each word in given string and store in array freq
            for (i = 0; i < inputChars.length; i++) {
                freq[i] = 1;
                for (j = i + 1; j < inputChars.length; j++) {
                    if (inputChars[i] == inputChars[j] && inputChars[i] != ' ' && inputChars[i] != '0') {
                        freq[i]++;

                        //Set string[j] to 0 to avoid printing visited character
                        inputChars[j] = '0';
                    }
                }
            }

            //Determine maximum occurring characters
            if (freq.length > 0) {
                lastFreq = freq[0];
            }
            for (i = 0; i < freq.length; i++) {

                max = freq[0];
                if (freq[i] == lastFreq) {
                    max = lastFreq;
                }
                if (max == lastFreq && max < freq[i]) {
                    lastFreq = freq[i];
                    maxChars.add(inputChars[i]);
                    for (Character c : maxChars) {
                        if (c != null) {
                            output = "The most frequent letter is " + c + " with: " + freq[i] + "occurences";
                        }
                    }
                }
                if (lastFreq < freq[i]) {
                    maxChars.clear();
                    maxChars.add(inputChars[i]);
                    for (Character c : maxChars) {
                        if (c != null) {
                            output = "The most frequent letter is " + c + " with: " + freq[i] + "occurences";
                        }
                    }
                }

                if (max > 1 && max == freq[i]) {
                    maxChars.add(inputChars[i]);
                    Iterator iterator = maxChars.iterator();
                    while (iterator.hasNext()) {

                        output = "The most frequent letter are " + maxChars.get(0).toString() + ", "
                                + iterator.next().toString() + " with: " + freq[i] + "occurences";
                    }
                }
            }

        return output;
    }
}

A: It happened because you didn't initialized your business logic field in FXMLController
Replace
Private BusinessLogic businessLogic;

By
private BusinessLogic businessLogic = new BusinessLogic();


text:
Q: How do I execute kubelet --resolve-conf?: I am running into an issue where coredns doesn't seem to be working on my ubuntu instance, I get allot of the following errors from the logs:
2020-07-16T05:28:36.648Z [INFO] 172.17.0.8:60594 - 29368 "AAAA IN redis-master.cluster.local. udp 44 false 512" NXDOMAIN qr,rd 137 0.000053955s
2020-07-16T05:28:36.650Z [INFO] 172.17.0.8:43585 - 56935 "AAAA IN redis-master. udp 30 false 512" NXDOMAIN qr,rd,ra 30 0.001305981s
2020-07-16T05:28:36.650Z [INFO] 172.17.0.8:43585 - 55951 "A IN redis-master. udp 30 false 512" NXDOMAIN qr,rd,ra 30 0.001790145s
2020-07-16T05:28:36.803Z [INFO] 172.17.0.11:60313 - 14198 "A IN redis-master.cluster.local. udp 44 false 512" NXDOMAIN qr,rd 137 0.000083909s
2020-07-16T05:28:36.803Z [INFO] 172.17.0.11:60313 - 14670 "AAAA IN redis-master.cluster.local. udp 44 false 512" NXDOMAIN qr,rd 137 0.000078636s
2020-07-16T05:28:36.808Z [INFO] 172.17.0.11:42385 - 5737 "A IN redis-master.svc.cluster.local. udp 48 false 512" NXDOMAIN qr,rd 141 0.000095061s
2020-07-16T05:28:36.808Z [INFO] 172.17.0.11:42385 - 6139 "AAAA IN redis-master.svc.cluster.local. udp 48 false 512" NXDOMAIN qr,rd 141 0.000088591s
2020-07-16T05:28:36.809Z [INFO] 172.17.0.11:47547 - 18338 "A IN redis-master.cluster.local. udp 44 false 512" NXDOMAIN qr,rd 137 0.000077331s

I'm hoping that the following paragraph from the docs found here is the solution:

Some Linux distributions (e.g. Ubuntu) use a local DNS resolver by
default (systemd-resolved). Systemd-resolved moves and replaces
/etc/resolv.conf with a stub file that can cause a fatal forwarding
loop when resolving names in upstream servers. This can be fixed
manually by using kubelet's --resolv-conf flag to point to the correct
resolv.conf (With systemd-resolved, this is
/run/systemd/resolve/resolv.conf). kubeadm automatically detects
systemd-resolved, and adjusts the kubelet flags accordingly.

However, I lack an understanding of how to execute the call to the kubelet. I could use an explanation or code example of how it is supposed to be done.
I am not sure if it is relevant but I am using minikube to test my cluster.
Thanks in advance for any help,
Cheers!

A: Sounds like a conflict with systemd-resolved and coredns in your minikube. You can try disabling systemd-resolved since you didn't create your cluster using kubeadm:

*

*Disable systemd-resolved ⌨
sudo systemctl disable systemd-resolved
sudo systemctl stop systemd-resolved

*Put this line in the [main] section of your /etc/NetworkManager/NetworkManager.conf ⌨:
dns=default

*Delete the symlink /etc/resolv.conf ⌨
sudo rm /etc/resolv.conf

*Restart NetworkManager ⌨♀♀♀
sudo systemctl restart NetworkManager

A: I experienced this issue today, this is what I found - am still validating this answer.
https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/
Create the following file for every host running kubelet.
/etc/systemd/system/docker.service.d/10-docker-opts.conf
[Service]
MountFlags=shared
Environment="DOCKER_OPTS=--resolv-conf=/run/systemd/resolve/resolv.conf"

A: Although original question was about minikube cluster, here is a couple of methods for cluster created by using kubeadm.
First method, using deprecated as of time writing flag --resolv-conf
Source of information https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/kubelet-integration/#the-kubelet-drop-in-file-for-systemd

*

*sudo create file /etc/default/kubelet with following content
KUBELET_EXTRA_ARGS=--resolv-conf=path_to_your_resolv.conf

*restart kubelet service sudo systemctl restart kubelet

*recreate CoreDNS pods (restart rollout or delete existing pods)
Second uses KubeletConfiguration object
Source https://kubernetes.io/docs/tasks/administer-cluster/kubeadm/kubeadm-reconfigure/#updating-the-kubeletconfiguration

*

*edit kubelet config stored in cluster kubectl edit cm -n kube-system kubelet-config, look for resolvConf: ***

*then download it from cluster to local config on node kubeadm upgrade node phase kubelet-config

*restart kubelet service sudo systemctl restart kubelet

*recreate CoreDNS pods (restart rollout or delete existing pods)


text:
Q: Computational Complexity: confused about contradiction in proof that most decision problems can't be computed I'm a bit confused about this proof, which is given at 13 mins in this lecture here:
https://www.youtube.com/watch?v=moPtwq_cVH8
The proof relies on the fact that programs need to be finite, making the set of all programs less than the set of all functions.   That should imply that there's a theoretical maximum sized program, because lets say the set of all programs S, which is claimed to be finite, has size N.   Now, if we take the largest program in N, and add 1 bit to it, we've now created a program not in S, which contradicts the statement that S is the set of all programs.
But for any program of an arbitrarily large size K, you can make a program of size K+1.  This means there can't be a maximum sizes program.

A: You misunderstood. Each program is finite. Not the set of programs.


text:
Q: Omega model hierarchy of theories According to this Mathoverflow answer by Andres Caicedo, there is a hierarchy of theories $U_\alpha$ where $U_{\alpha+1}= U_\alpha+\text{"There is an $\omega$-model of $U_\alpha$"}$, that is, $U+\text{"There is an $\omega$-model of $U$"}$ is stronger than $U$ for theories $U$ in the hierarchy. The example in the post was $U_0=ZFC$ but I assume that it applies to every recursive theory that can interpret enough second-order arithmetic.
But what does that mean semantically? Does it mean that there are minimal $\omega$-models, that is, $\omega$-models of $U_0+\text{"There is no $\omega$-model of $U_1$"}$, and more generally, are there $\omega$-models of $U_{\alpha}+\text{"There is no $\omega$-model of $U_{\alpha+1}$"}$? That is relevant to another question of mine. I assumed that there are minimal $\omega$-models but comments by Hanul Jeon and Eric Wofsey said that it doesn't follow from Caicedo's answer.


text:
Q: Use Surface Pro 3 as second or extended monitor instead using it as a computer? Particularly how to use Surface Pro 3 as a 2nd monitor only. not as a surface pro itself. i.e. I have a laptop and use surface pro as a second monitor.

A: Download the free app Splashtop on the surface and install the Splashtop streamer on your laptop.
Now you can connect to your surface.


text:
Q: hibernate simultaneous updates Consider a scenario- 2 applications accessing/updating a single database. one of the applications is using hibernate & has got some records from db, will now process them & save it back. But before it saves, the same set of records is updated by the other application. What will happen in this scenario?
Will hibernate throw an error on saving ? or hibernate will have the intelligence to sync the updated records?

A: The hibernate will throw StaleObjectException. Here is why.
Hibernate uses optimistic locking to handle database concurrency. A StaleObjectExceptionis thrown if the data to be updated is modified by another transaction before current transaction commits the changes.
EDIT:
and how does hibernate identify that the state of object in memory is stale?
Hibernate uses a version field to track the changes to the entity. This version field updated on every commit. Now if the version number just before commit does not match the version number when the entity was read at the beginning of transaction,StaleObjectException is thrown.


text:
Q: How can I make my mongo update query the most efficient? I have a large test database I am using to test my queries, and I am wondering how I can possibly go about making this update query much more efficient as it is terrible right now. Here is what I have so far:
const query = {
  username:"billyBob",
  socialPlatform:"twitter",
  userUrl:"www.whoami.com"
};

const updateDoc = {
  $set: {
    'posts.0.sentiment': 'positive'
  }
}

db.socialContent.update(query, updateDoc);

Here is an example doc:
{
    "_id" : ObjectId("1234567890"),
    "socialPlatform" : "twitter",
    "username" : "billyBob",
    "userUrl" : "www.whoami.com",
    "posts" : [
        {
            "location" : "USA",
            "timezone" : "CST",
            "sentiment" : "perplexed",
            "tweetLink" : "https://www.tweetlink.com"
        }
    ]
}

username billyBob has thousands of posts for this specific social platform.


text:
Q: Make linked directories I have a class that pulls in an id, name and (if needed) parent-id, it converts these into objects and then links them.
If you look right at the end you will see what Im trying to fix at the moment, The folder objects know if they have a child and/or parent but if I were to run mkDirs() here it would only work for two levels (root, child-folder) but if there were multipul levels (root/folder1/folder1) it would not work.
Any Idea how I can solve this?
package stable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
public class Loop {

public static void main(String[] args) {
    int PID = 0;

    int RepoID = 1;
    Connection con = null;
    String url = "jdbc:mysql://localhost/document_manager";
    String user = "root";
    String password = "Pa55w0rd";
    try {
        con = DriverManager.getConnection(url, user, password);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    Map<Integer,Folder> data = new HashMap<Integer,Folder>();
    while( PID < 50 )
    {
    try {
        Statement st = con.createStatement();
        ResultSet result = st.executeQuery("SELECT name, category_id, parent_id FROM categories WHERE parent_id = '"+PID+"' AND repository_id = '"+RepoID+"'");
        while (result.next ())
        {
            String FolderName = result.getString ("name");
            String FolderId = result.getString ("category_id");
            String ParentId = result.getString ("parent_id");
            int intFolderId = Integer.parseInt(FolderId);
            int intParentId = Integer.parseInt(ParentId);
            System.out.println( FolderId+" "+FolderName+" "+ParentId );
            Folder newFolder = new Folder(FolderName, intFolderId, intParentId);
            data.put(newFolder.getId(), newFolder);
            }
    } catch (SQLException ex) {
        System.out.println(ex.getMessage());
    }
  PID++;
    }
    for(Folder folder : data.values()) {
        int parentId = folder.getParentFolderId();
        Folder parentFolder = data.get(parentId);
        if(parentFolder != null)
            parentFolder.addChildFolder(folder);
        //Added
        System.out.print("\n"+folder.getName());
        if(parentFolder != null)
            System.out.print("  IS INSIDE "+parentFolder.getName());
        else
            System.out.print("  HAS NO PARENT!");

    }
}
}

A: Looks like you could/should break out the directory creation logic into its own function and then make it recursive.  That should get you the ability to make 'infinite' depth directory hierarchies.
Side note:  Its horribly inefficient to make repeated DB calls in a loop.  Try a single Select and then loop thru results.  If needbe, you can use SQL's 'IN' operator to filter results:
http://www.w3schools.com/sql/sql_in.asp


text:
Q: When is QThread quit() or finished()? I'm new to Qt, and want to simply display a video in Qt GUI. I basically got everything figured out, except for some details handling the QThread, which is really annoying.
I reformulate my question into a simpler program, hope it will explains better
first I define this QObject class
#include <QObject>
#include <QDebug>
class myObject : public QObject
{
    Q_OBJECT
public:
    explicit myObject(QObject *parent = 0);
    bool stop;

signals:
    void finishWork();

public slots:
    void dowork();
    void onfinishThread();

};

myObject::myObject(QObject *parent) :
QObject(parent)
{
    stop = true;
}

void myObject::dowork(){
    qDebug()<<"start working!";
    while(!stop){
        qDebug()<<"working...";
    }
    emit finishWork();
    qDebug()<<"finish do work!";
}
void myObject::onfinishThread(){
    qDebug()<<"thread is finished!";
}

then the main function
#include <QCoreApplication>
#include <QThread>

#include <iostream>
#include <windows.h>

#include "myobject.h"

using namespace std;
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    myObject* myObj = new myObject();
    QThread* myThread = new QThread;

    myThread->connect(myObj, SIGNAL(finishWork()), SLOT(quit()));
    myObj->connect(myThread, SIGNAL(started()), SLOT(dowork()));
    myObj->connect(myThread, SIGNAL(finished()), SLOT(onfinishThread()));
    myObj->moveToThread(myThread);

    myObj->stop = false;

    myThread->start();

    cout<<"Press ENTER to continue....."<<endl<<endl;
    cin.ignore(1);

    myObj->stop = true;
    Sleep(10);

    if(myThread->isRunning()){
        qDebug()<<"The thread is still running?!!!";
    }

/*
    myObj->stop = false;
    Sleep(1000);
    myThread->start();
    myObj->stop = true;
*/

    myObj->deleteLater();
    myThread->deleteLater();
    return a.exec();
}

As you can see, I even used cin to try let the dowork() run first, but it didn't work at all, the output is

so I'm really confused on how scheduling works for QThread...
Also, if you uncomment the part
/*
    myObj->stop = false;
    Sleep(1000);
    myThread->start();
    myObj->stop = true;
*/

the output is exactly the same! only stays a while after printing

The thread is still running?!!!

Would anyone help me with this? Thanks a lot. You may simply copy all the code and test it yourself.

-------------------------Original Question, bad explanation, please ignore....----------------------------------------
I made a videoObj Class with only one function to Query the frames, the function is defined as:
void videoObj::ProcessFrame(){
bool getframe;
qDebug()<<"get in ProcessFrame";
while(!stop_flag){
    getframe = capture_.read(imgOriginal_);
    if(!getframe){
        qDebug()<<"Video End!";
        break;
    }
    cv::cvtColor(imgOriginal_, imgOriginal_, CV_BGR2RGB);
    QImage qimgOriginal((uchar*)imgOriginal_.data, imgOriginal_.cols, imgOriginal_.rows, imgOriginal_.step, QImage::Format_RGB888);

    emit imgProcessed(qimgOriginal);
    this->thread()->msleep(10);
    //qDebug()<<"processing frames";
}

emit stopProcess();
qDebug()<<"Stop thread";
}

Basically above code is just query frames and whenever got one emit the
SIGNAL imgProcessed(qimgOriginal)

and whenever the stop_flag is set on, stop the while loop and emit the
SIGNAL stopProcess()

I use this class in the MainWindow Class, here is how I define the connection in the constructor:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

video_obj_ = new videoObj();
video_thread_ = new QThread;
this->connect(video_obj_, SIGNAL(imgProcessed(QImage)), SLOT(onImgProcssed(QImage))); \\this is for displaying the image
video_obj_->connect(video_thread_, SIGNAL(started()), SLOT(ProcessFrame()));
video_obj_->moveToThread(video_thread_);
video_thread_->connect(video_obj_, SIGNAL(stopProcess()), SLOT(quit()));
}

Above code works fine in frame query. The problem I don't understand is, if I set video_obj_->stop_flag on in any MainWiow member function, the ProcessFrame() in videoObj Class should emit stopProcess() signal and trigger quit() of video_thread_, and then the thread should finish, that is video_thread_->finished() is true.
However, if I do something like:
connect(video_thread_, SIGNAL(finished()), this, SLOT(onStopProcess())); //onStopProcess() see below

void MainWindow::on_btnStart_clicked()
{
video_obj_->stop_flag = 1;
this->thread()->msleep(10);

video_obj_->capture_.open(ui->lineEditVidoeAddress->text().toStdString());
//... something about videoCapture setting here, not related

video_obj_->capture_.set(CV_CAP_PROP_POS_FRAMES, 0);
video_obj_->stop_flag = 0;
this->thread()->msleep(10);
if(video_thread_->isRunning()){
    qDebug()<<"The thread is still running?!!!";
}
video_thread_->start();
}

void MainWindow::onStopProcess(){
    qDebug()<<"thread is finished";
}

It will give me the output:
Stop thread
The thread is still running?!!!
thread is finished

Which means triggering the quit() is not finish the thread, or quit() has not been triggered.
If I use:
video_thread_->wait(); //instead of video_thread_->wait(10);

The program will just freeze.
Is anyone can help me with this, it really confuse me about this quit() and finished()...
Thanks!

A: Since when you call stop_flag=1, the video_thread_ finishes the current function which is
ProcessFrame

before ProcessFrame finish, quit is called on the video_thread_ through emit stopProcess().
However, quit is different from terminate, terminate can exit the thread any time (but it is not safe), quit works with the event loop, if the thread has no eventloop, quit has no effect.
I guess before qthread execute the next event in the eventloop, it checks some flag, which can be set by quit, it the flag is set by quit, then it won't execute the next event in the  eventloop. Or it can also be that a quit event is inserted into the eventloop, and the next event in the eventloop will be quit.
After stop_flag = 1, you called video_thread_->wait, that will block the video_thread_ from executing the next event in the eventloop, thus the quit will not take effect before time out, however, the nextlines which print "not finished?!!!" is executed immediately. Instead of calling video_thread->wait, if you call currentThread()->Sleep(some_enough_time), then there will be time for the video_thread_ to execute the next event and quit.
You can read the Qt documentation of QThread, wait is used with terminate to terminate a thread synchronously.
============================== The new code ================================
When you do:
myObj->connect(myThread, SIGNAL(started()), SLOT(dowork()));

The signal source is myThread, the slot also belongs to myThread, since the object "myThread" is created in the main thread, thus as a object it lives in the main thread. You can call myThread->thread() to see this, it will return the main thread instead of the new thread.
However, the started signal is emitted from the new thread namely the thread that myThread represents, thus the connection is a Qt::QueuedConnection. dowork() is posted in the event queue of main thread, and it'll be executed only after a.exec() which executes the main threads eventloop.
The same thing happens to the other 2 connect calls, all the slots will be executed in the eventloop of the main thread.
First the start is emitted from the new thread when myThread->start is called, dowork is posted in the main thread's event queue.
Nothing really happens before you call a.exec();
So the program will go ahead to cin and then set stop to true, and then print "Thread is still running?!!".
Second When a.exec() is called, the dowork is executed in the main thread and "start work" is printed. Nothing is done because the stop flag is already true, and the finishwork signal is emitted from the main thread, print "finish do work";
Third The last step the finishwork is emitted, and the quit slot is directly called. However, before the new thread can really quit, the main thread has already finished the eventqueue, because no more events are posted to the main thread. The application exits without waiting for quit() to take effect.
To test this is true, do not modify any of your code, just add after
emit finishWork();
currentThread()->sleep(1000);

you will see "thread is finished!" printed, because this make time for the new thread to emit finished(), and the onfinishThread() will be add to the main thread's eventqueue.
BTW, your way of working with thread looks like java style, which is not the standard qt way. You can read this before you work on qt thread.

A: This is not a scheduling issue.
That you did in your code looks like:

*

*Create a thread.

*Then this thread emits a signal that it started, run slot dowork()

*start a thread.

*Wait for user input

*echo about thread is running

*execute event loop
At point 3 thread is already running and signalled about that. Because myObj is created in main thread and not moved to any other thread (to process events there), your thread does not do anything else now, but just spins event loop. At the same time event that tells you want to run myObj's dowork() is posted on the main thread. At last then it comes to step 6 you start to execute event loop of it, and first thing it finds is event that it needs to call dowork() on myObj.
To make it clear to you how Qt threads and signal-slot connection works, I recommend you to read this article on Qt blog.
In simple to fix it, you can move your object myObj to the thread that you wan't to run.
But to make this really correct, I bet that you really want is to subclass QRunnable and (re-)implement it's run method to do the stuff you wan't in QThread, so that thread does it's job, than finished correctly, so you can join on it. Or depending on your goal you might be even better with using QtConcurrent::run(aFunction)


text:
Q: Tools that can help in code checking in Android Is there any good tools or Eclipse Plugins that would scan my Android Project and identify possible 'Memory leaks', susceptible code for 'Force closes' and other general code standards of Java and/or Android.

A: One good tool is the "LINT" Tool Available in Eclipse + Android-SDK.

http://tools.android.com/tips/lint

Another good find was "FindBugs" that locates Java Bugs and suggests enhancements.

http://findbugs.sourceforge.net/
http://findbugs.cs.umd.edu/eclipse/

Is there any other tool that you'd suggest ?

A: This doesn't answer the question but does offer an alternative.
In my opinion, Intellij IDEA is better than Eclipse in almost every way.  Its' code inspectors in combination with Android Lint and Findbugs is powerful.  The way IDEA finds, reports and visualises possible bugs, "code smells" and suggestions for refactoring is superb.  I'm not aware of any IDE that does the job as well.

A: Besides android-lint, which is already available in your installation of the ADT and finds Android specific issues, I recommend both Findbugs and CodePro Analytix for standard Java code checks.

A: A force close is just any uncaught exception in you code, such as a NullPointerException. You can debug these issues as they occur by reading the stack trace output to logcat.
For memory analysis I suggest you start by watching Memory management for Android Apps (a session from Google I/O 2011) and read the companion blog post Memory Analysis for Android Applications. They provide some good suggestions for strategies and tools to debug memory leaks and other issues.


text:
Q: sed/awk copy paste snippet from one place to other place in same file How do i copy some snippet and paste in same file using sed/awk tool?
Example: file name foo.txt has following text i want to copy that and paste below that same text
ABC
DEF
GHI
JKL
MNO
PQR

Final output will be like.
    ABC
    DEF
    GHI
    JKL
    MNO
    PQR

    ABC
    DEF
    GHI
    JKL
    MNO
    PQR

A: OP asked for sed, so here it is!
There are probably many way to achieve it, but here is the one I know:
sed 'H;$G' foo.txt

*

*H: append current file to the hold buffer

*;: separate two expressions

*$: upon end of file

*G: print hold buffer

But wait! there is more!
Don't ever forget that ed Is The Standard Text Editor (took me some time to remember how to use it and it was not brillant I must say).
For the example let's say it's in a file named foo.ed (you could do the same in an interactive session):
$a

.
,t$
$d
wq

Then use it with:
ed foo.txt < foo.ed

One-liner unreadable bashism:
ed foo.txt <<< $'$a\n\n.\n,t$\n$d\nwq'

Translation:

*

*$a: insert at the end of the file everything (a single new line here) till the single dot .

*,t$: copy the whole file content to the end

*$d: delete the last line because I didn't remember how to copy till the line before the end of the file !@#

*wq: write and quit

References:

*

*http://www.gnu.org/software/ed/manual/ed_manual.html

*http://c2.com/cgi/wiki?EdIsTheStandardTextEditor

A: Assuming you want to duplicate a whole file and don't really want to indent the output lines, you'd never use sed or awk for this, just cat and echo:
$ cat file; echo ''; cat file
$ cat file
ABC
DEF
GHI
JKL
MNO
PQR

ABC
DEF
GHI
JKL
MNO
PQR

and if you want to modify the original file, just redirect the output to a tmp file and then mv it to file:
(cat file; echo ''; cat file) > tmp && mv tmp file

A: As Fedorqui points out in his comment, you can run Awk on the same file multiple times.
awk 'NR>1 && FNR==1 {print ""} {print "\t" $0}' foo.txt foo.txt

should produce your desired output.
This can be simplified using bash brace expansion foo.txt{,}.
Also, if using GNU Awk, there's builtin rule called ENDFILE that will allow you act after the last record has been processed in each file:
awk '{print "\t" $0} ENDFILE{print ""}' foo.txt{,}

Alternatively, you could be a hog and read the entire file into memory, then loop through it twice.
awk '{
    a[NR]=$0
} END {
    num=2
    for (i=1; i<=num; i++) {
        for (j=1; j<=NR; j++)
            print "\t"a[j]
        if (i % num != 0)
            print ""
    }
}' foo.txt

You'll notice each line number NR must also be recorded as an index of the array a to preserve the original order in output.


text:
Q: iOS error 'Invalid type in JSON write (FIRTimestamp)' I am trying to map my data to Model.
Where I am using Firestore snapshot listener, to get data.
here, I am getting data and mapping to "User" model that;
            do{
                let user = try User(dictionary: tempUserDic)
                print("\(user.firstName)")
            }
            catch{
                print("error occurred")
            }

Here is my Model:
struct User {
    let firstName: String
//    var lon: Double = 0.0
//    var refresh:Int = 0
//    var createdOn: Timestamp = Timestamp()
}

//Testing Codable
extension User: Codable {
    init(dictionary: [String: Any]) throws {
        self = try JSONDecoder().decode(User.self, from: JSONSerialization.data(withJSONObject: dictionary))
    }
    private enum CodingKeys: String, CodingKey {
        case firstName = "firstName"
    }
}

Correct me if I am wrong.
Crashing because I am getting "Timestamp" in data.
Data getting from listener :
User Dictionary:
[\"firstName\": Ruchira,
 \"lastInteraction\": FIRTimestamp: seconds=1576566738 nanoseconds=846000000>]"

How to map "Timestamp" to Model?
Tried "CodableFirstore" https://github.com/alickbass/CodableFirebase

A: An approach is to create an extension to type Dictionary that coverts a dictionary to any other type, but automatically modifies Date and Timestamp types to writeable JSON strings.
This is the code:
extension Dictionary {

    func decodeTo<T>(_ type: T.Type) -> T? where T: Decodable {

        var dict = self

        // This block will change any Date and Timestamp type to Strings
        dict.filter {
            $0.value is Date || $0.value is Timestamp
        }.forEach {
            if $0.value is Date {
                let date = $0.value as? Date ?? Date()
                dict[$0.key] = date.timestampString as? Value
            } else if $0.value is Timestamp {
                let date = $0.value as? Timestamp ?? Timestamp()
                dict[$0.key] = date.dateValue().timestampString as? Value
            }
        }

        let jsonData = (try? JSONSerialization.data(withJSONObject: dict, options: [])) ?? nil
        if let jsonData {
            return (try? JSONDecoder().decode(type, from: jsonData)) ?? nil
        } else {
            return nil
        }
    }
}

The .timestampString method is also declared in an extension for type Date:
extension Date {

    var timestampString: String {
        Date.timestampFormatter.string(from: self)
    }

    static private var timestampFormatter: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.timeZone = TimeZone(identifier: "UTC")
        return dateFormatter
    }
}

Usage, like in the case of the question:
let user = tempUserDict.decodeTo(User.self)

A: I solved this by converting the FIRTimestamp fields to Double (seconds) so the JSONSerialization could parse it accordingly.
 let items: [T] = documents.compactMap { query in
   var data = query.data() // get a copy of the data to be modified.

   // If any of the fields value is a `FIRTimestamp` we replace it for a `Double`.
   if let index = (data.keys.firstIndex{ data[$0] is FIRTimestamp }) {

     // Convert the field to `Timestamp`
     let timestamp: Timestamp = data[data.keys[index]] as! Timestamp

     // Get the seconds of it and replace it on the `copy` of `data`.
     data[data.keys[index]] = timestamp.seconds

    }

    // This should not complain anymore.
    guard let data = try? JSONSerialization.data(
       withJSONObject: data,
       options: .prettyPrinted
    ) else { return nil }

    // Make sure your decoder setups the decoding strategy to `. secondsSince1970` (see timestamp.seconds documentation).
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .secondsSince1970
    return try? decoder.decode(T.self, from: data)
 }

// Use now your beautiful `items`
return .success(items)


text:
Q: How to read "fsutil usn readjournal C:" output There is a utility that can be run on the Microsoft Windows command line called fsutil. One of the commands that it accepts is fsutil usn readjournal <volume pathname> along with several other arguments. Is there documentation on how to read the data produced by the program? My specific interests are how to interpret and use the File ID and Parent file ID fields. Since File name does not include the full path, it is unclear how one should determine if the file may be of interest based on location.
Example Record
Usn               : 9149751384
File name         : Preferences~RF101ac0ae.TMP
File name length  : 52
Reason            : 0x80000200: File delete | Close
Time stamp        : 7/12/2018 11:04:30
File attributes   : 0x00000020: Archive
File ID           : 0000000000000000000500000000a67b
Parent file ID    : 0000000000000000000500000003fa3c
Source info       : 0x00000000: *NONE*
Security ID       : 0
Major version     : 3
Minor version     : 0
Record length     : 128

A: That output corresponds to the USN_RECORD_V3 data structure. Regarding the ID rows, every object on an NTFS volume has a numeric identifier. The "file ID" line gives you the ID of the file affected by that update; the "parent file ID" is the ID of the directory containing it.
To get a path to the file, you can use another mode of this utility: fsutil file queryFileNameById. It takes a volume path and a file ID (with 0x prepended), and returns a full path. I say "a" path and not "the" path because NTFS allows hardlinks, which give different paths to the same file. Exactly which path is returned in that case is arbitrary. The vast majority of files only have one link/path, though.
Let's do an example. I have this USN record:
Usn               : 46966427728
File name         : settings.dat
File name length  : 24
Reason            : 0x80000001: Data overwrite | Close
Time stamp        : 7/11/2018 21:50:57
File attributes   : 0x00000020: Archive
File ID           : 00000000000000000005000000170d13
Parent file ID    : 0000000000000000001200000019ab0e
Source info       : 0x00000000: *NONE*
Security ID       : 0
Major version     : 3
Minor version     : 0
Record length     : 104

Let's use the file ID to find the path to the file:
fsutil file queryFileNameById C:\ 0x00000000000000000005000000170d13

The result:
A random link name to this file is \\?\C:\Users\Ben\AppData\Local\Packages\Microsoft.Windows.Photos_8wekyb3d8bbwe\Settings\settings.dat

It looks like this file is some sort of configuration storage for the Photos app. In the case of your USN record, the file is probably deleted now, so you'll have to use the parent ID to find where it was. If I query by my file's parent  ID...
fsutil file queryFileNameById C:\ 0x0000000000000000001200000019ab0e

...I get just the path to the folder, not the settings.dat file:
A random link name to this file is \\?\C:\Users\Ben\AppData\Local\Packages\Microsoft.Windows.Photos_8wekyb3d8bbwe\Settings


text:
Q: have to get data from VISIT_Table filter with only date no time SELECT *
FROM VISIT_Table
WHERE
    ID='" + ID + "' AND
    DATE ='" + DateTime.Now.ToString("yyyy-MM-dd") + @"'";

Above is my query I have to get data from VISIT_Table filter with only date no datetime..
In database visit_date stores 2012-10-27 11:10:35 I have to get data with only date no time

A: SELECT CONVERT(VARCHAR(10), Visit_Date, 120) AS [Date],ID FROM PATIENT_VISIT


text:
Q: Replying with "neither" in passive for active sentence For example: They don't allow you to enter the room. How to say that they don't allow me to enter too? What is the shortest way to say it? Is it possible to use neither in such situation? Neither do me?
Is it possible to replay on sentence in an active voice with a passive sentence?

A: There are three possible practical responses in normal conversation, but only two of them are, technically (in a formal sense), grammatical:

Me either.
  Nor me.

First of all, look at the initial statement:

They didn't allow me to enter the room.

There are a couple of long replies that could be made to this:

They didn't allow me to enter the room either.
  Nor did they allow me to enter the room.

When you use a shorter version of a sentence to stand for it's longer version, it's called an elliptical sentence. In other words, pieces of the sentence have been removed, leaving just enough components so that it is still understood.
With the example answers, the elliptical sentences are:

(they didn't allow) Me to enter the room either.
Nor did they allow me to enter the room.

Note 1: In casual conversation, some people do still respond to this with me neither, but the problem, in terms of grammar, is that—in this specific example—if it's an elliptical sentence, then it could only come from an ungrammatical longer sentence:

They didn't allow me to enter the room neither.

Therefore, me neither is (in a purely formal sense) ungrammatical.
However, having said that, such a response is commonly given in informal speech—and it would be understood by anybody who heard it.

Note 2: In the UK, me either is rarely used. Instead, at least in informal speech, it's normally me neither.

A: If I say to you:

They wouldn't let me in the room.

you can reply

Me neither.

or

Nor me.

Me neither is conversational. Nor me would sound a little formal to most speakers of American English.
You could also say

They wouldn't let me in either.

But with either most native speakers in their reply would probably repeat some or all of the first speaker's statement, echoing the negative, wouldn't. A good many however would simply say

Me either.


text:
Q: Android CalenderView - change scroll direction to vertical I'm using a calendarView in my app inside a navigation drawer to select different days and everything works fine except for swiping to the left on the calendarView to get to the next month (swiping to right changes to the previous month correctly), since this is the swipe gesture that closes the drawer.
Is it possible to change the scroll direction of the calendar to vertical instead of horizontal? I want to implement this so users don't solemnly need to rely on the buttons to switch between months.
This is the code from fragment_navigation_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/nav_header_container"
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:background="@color/colorPrimary">

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/ic_profile"
            android:scaleType="fitCenter"
            android:layout_centerInParent="true"
            android:contentDescription="@string/app_icon"/>

    </RelativeLayout>

    <CalendarView
        android:id="@+id/calendarView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </CalendarView>

</LinearLayout>

which looks like this in my app:


text:
Q: Error:this template attempted to load content assembly Ok i recently got visual studio pro just so i could create phone applications in vb.net. Yet when i installed the template i got this error Error:this template attempted to load content assembly. I already have all nuget installed and the error was displaying before i had it so i really need help here. I'm usualy visual studio 2010 ide and trying to load the following temaplte:vb windowsphone application template under silver light. AND SO EVERYONE KNOWS I HAVE TRIED INSTALLING NUGET IT CHANGED NOTHING. Any help would be much appreciated thank you.

A: Check out the link below;
http://www.itorian.com/2012/08/error-this-template-attempted-to-load.html
No the error is not the same. But the error message you provided is only half and cannot know which template/component is giving the error.
Provide the full error to help you better.
Athar


text: Q: How do I install the Irix operating system over a network I just bought an Irix machine off of eBay. It had 2 hard drives. It has some weird variables from the last user. What programs can I use to Net install the irix operating system onto my computer?


text:
Q: Using Pattern Matching in Prolog to Find Submultisets I am new to prolog and I was wondering if anyone could help me with this problem.  The problem:  given the integers 1,2,3,4, and the predicates mult/2, div/2, div/2, minus/2, and minus/2, and eval/2, I need to write a predicate solutions/1 that, when called like this:
?- solutions(L).

it should terminate with the variable L unified to a list of expressions with value 6.  Expressions are of the form:
X, Y, exp/2

But my code is not working.  I have two versions.  The first freezes up SWI-Prolog, not returning any answer after I type a period, and not letting me evaluate anything else afterward:
eval(1,1.0).
eval(2,2.0).
eval(3,3.0).
eval(4,4.0).

eval(mult(X,Y),Z) :-
    eval(X,A),
    eval(Y,B),
    Z is A*B.

eval(div(X,Y),Z) :-
    eval(X,A),
    eval(Y,B),
    Z is A/B.

eval(minus(X,Y),Z) :-
    eval(X,A),
    eval(Y,B),
    Z is A-B.

solutions(L) :-
    setof(X,eval(X,6),L),
    print(L).

The second version just returns false when I type ?- solutions(L).:
solutions(L) :-
    setof([exp,X,Y],eval(exp(X,Y),6),L),
    print(L).

Thank you so much for taking the time to help!

A: The problem is that your code is going in infinite recursion with eval/2 predicate.
You can try this solution:
num(1).
num(2).
num(3).
num(4).

eval(mult(A,B),Z) :-
    num(A),
    num(B),
    Z is A*B.

eval(div(A,B),Z) :-
    num(A),
    num(B),
    Z is A/B.

eval(minus(A,B),Z) :-
    num(A),
    num(B),
    Z is A-B.

test(L) :-
    setof(X,eval(X,6),L),
    print(L).

Which yields:
?- test(L).
[mult(2,3),mult(3,2)]
L = [mult(2, 3), mult(3, 2)].

A: Maybe you're looking for something like
solutions(L) :-
    Ns = [1,2,3,4],
    Ex = [*,/,-],
    findall((X,Y,E),
       (member(X,Ns),member(Y,Ns),member(E,Ex),F=..[E,X,Y],6=:=F),
       L).

that yields
?- solutions(L).
L = [(2, 3,  (*)),  (3, 2,  (*))].

Expressions are usually recursive, that is, arguments could be expressions instead of plain numbers. But then, in my opinion your problem is underspecified, as we need criteria to stop the infinite flow of solutions resulting - for instance - by repeated application of operations that don't change the value. Like multiply or divide by 1.


text:
Q: Aggregation taking too long using spark over hbase (using shc 1.1.1-2.1-s_2.11) I'm ingesting streaming data into hbase. I have pre-splitted the HBase table by Kafka partitions. Using composite rowkey with combination of Kafka partitions, timestamp followed by some other columns to make it unique.
With this approach I'm having really good throughput while inserting the data but I also have to aggregate the data on daily basis, which is terribly slow.
We observed that the number of Spark tasks triggered for groupBy or count is equal to total number of regions in which my table is spread.
Am I doing something wrong here? How can I limit the number of regions for a table in HBase ?
HBase create statement
create 'default:test', {NAME => 'data', VERSIONS => 1, TTL => '3888000'},{SPLITS=> ['10000000000000000000000000000000','20000000000000000000000000000000','30000000000000000000000000000000','40000000000000000000000000000000','50000000000000000000000000000000','60000000000000000000000000000000','70000000000000000000000000000000','80000000000000000000000000000000','90000000000000000000000000000000']}

catalog while inserting
def catalog = s"""{
  |"table":{"namespace":"default", "name": "test", "tableCoder":"Phoenix"},
  |"rowkey":"key",
  |"columns":{
  |"rowkey":{"cf":"rowkey", "col":"key", "type":"string"},
  |"resource_id":{"cf":"data", "col":"resource_id", "type":"string"},
  |"resource_name":{"cf":"data", "col":"resource_name", "type":"string"},
  |"parent_id":{"cf":"data", "col":"parent_id", "type":"string"},
  |"parent_name":{"cf":"data", "col":"parent_name", "type":"string"},
  |"id":{"cf":"data", "col":"id", "type":"string"},
  |"name":{"cf":"data", "col":"name", "type":"string"},
  |"timestamp":{"cf":"data", "col":"timestamp", "type":"string"},
  |"readable_timestamp":{"cf":"data", "col":"readable_timestamp",
    "type":"string"},
  |"value":{"cf":"data", "col":"value", "type":"string"},
  |"partition":{"cf":"data", "col":"partition", "type":"string"}
  |}
|}""".stripMargin

Catalog to read
def catalog = s"""{
    |"table":{"namespace":"default", "name": "test", "tableCoder":"Phoenix"},
    |"rowkey":"partition:timestamp:id:parent_id:resource_id",
    |"columns":{
    |"partition":{"cf":"rowkey", "col":"partition", "type":"string"},
    |"timestamp":{"cf":"rowkey", "col":"timestamp", "type":"string"},
    |"id":{"cf":"rowkey", "col":"id", "type":"string"},
    |"parent_id":{"cf":"rowkey", "col":"parent_id", "type":"string"},
    |"resource_id":{"cf":"rowkey", "col":"resource_id", "type":"string"},
    |"resource_name":{"cf":"data", "col":"resource_name", "type":"string"},
    |"parent_name":{"cf":"data", "col":"parent_name", "type":"string"},
    |"name":{"cf":"data", "col":"name", "type":"string"},
    |"value":{"cf":"data", "col":"value", "type":"string"},
    |"readable_timestamp":{"cf":"data", "col":"readable_timestamp", "type":"string"}
    |}
    |}""".stripMargin

To do range scan I'm using all the partitions and the time range:
val endrow = "1540080000000"
val startrow = "1539993600000"

df.filter(($"partition"==="0" && ($"timestamp" >= startrow && $"timestamp" <= endrow)) ||($"partition"==="1" && ($"timestamp" >= startrow && $"timestamp" <= endrow))||($"partition"==="2" && ($"timestamp" >= startrow && $"timestamp" <= endrow))||($"partition"==="3" && ($"timestamp" >= startrow && $"timestamp" <= endrow))||($"partition"==="4" && ($"timestamp" >= startrow && $"timestamp" <= endrow))||($"partition"==="5" && ($"timestamp" >= startrow && $"timestamp" <= endrow))||($"partition"==="6" && ($"timestamp" >= startrow && $"timestamp" <= endrow))||($"partition"==="7" && ($"timestamp" >= startrow && $"timestamp" <= endrow))||($"partition"==="8" && ($"timestamp" >= startrow && $"timestamp" <= endrow))||($"partition"==="9" && ($"timestamp" >= startrow && $"timestamp" <= endrow))).count

Above filter results in 830 tasks which is equal to number of regions.
Which is taking way too much time. How can I improve it ?


text:
Q: Extracting fields from an emails based on values in a database as training set Ive got 480 emails and each of them consist of one or all of these values :-
[person, degree, working/not working, role]
So for example one of the email looks like this :-
    Hi Amy,

    I wanted to discuss about Bob. I can see that he has a degree in
    Computer Science which he got three years ago but hes still unemployed.
    I dont know whetehr he'll be fit for the role of junior programmer at
    our institute.
    Will get back to you on this.

    Thanks

The corresponding database entry for this email looks like this
Email_123 | Bob | Computer Science | Unemployed | Junior Programmer

Now even though the data hasnt been labelled but we still have somewhat of a database to lookup which values were extracted into the 4 fields from each of the email.
Now my question is that how can I use this corpus of 480 emails to learn and extract these 4 fields using Machine Learning/NLP.
Do I need to manually tag all these 480 emails like..
I wanted to discuss about <person>Bob</person>. I can see that he has a degree in
    <degree>Computer Science</degree> which he got....

Or is there a better way. Something like this (MarI/O - Machine Learning for Video Games) https://www.youtube.com/watch?v=qv6UVOQ0F44&t=149s

A: Assuming that each email has only one value for each field, and that the value is always reproduced verbatim from the email, you can use something like WikiReading.

The problem is that WikiReading was trained on 4.7 million examples, so if you only have 480 that's nowhere near enough to train a good model.
What I would suggest is preprocessing your dataset to automatically add tags like in your example. Something like this, in pseudo-python:
entity = "Junior Programmer"
entity_type = "role"
mail = "...[text of email]..."

ind = mail.index(entity)
tagged = "{front}<{tag}>{ent}</{tag}>{back}".format(
  front=mail[0:ind],
  back=mail[ind+len(entity):],
  tag=entity_type,
  ent=entity)

You'll need to adjust for case issues, multiple matches, and so on.
With tagged data you can use a conventional NER system like a CRF. Here's a tutorial using spaCy in Python.


text:
Q: Change port of Jetbrain Upsource First, i googled about the issue, but couldn't find anything.
Issue:
On installation, i changed the port to 8081. But now its used by another app. So, is there any way to change port of upsource? (Linux)

A: You can run the following from your terminal:
./bin/upsource.sh configure --listen-port 1111 --base-url http://servername:1111/

Substituting "1111" for the port you want to use and 'servername' with the baseurl you have chosen for upsource (in my case this was the name of my machine).
Source: https://www.jetbrains.com/help/upsource/2.5/moving-your-upsource-installation-to-another-server.html

A: This is the correct way.

1. ./bin/upsource.sh stop

2../bin/upsource.sh configure --base-url=http://(server-name).com:(port) --listen-port=(port)

3. ./bin/upsource.sh start

4. Head to http://(server-name).com:(port)

A: I know this question is Linux specific, but if you're running Upsource on Windows... the commands in @Wassim Seifeddine's answer can be modified to the following to accomplish port and/or base-url updates for Upsource as shown below:

*

*[upsource-base-path]/bin/upsource.bat stop

*[upsource-base-path]/bin/upsource.bat configure --base-url=http://(server-name).com:(port) --listen-port=(port)

*[upsource-base-path]/bin/upsource.bat start


text:
Q: MongoDb c# official driver bulk update How can i rewrite the following old code via the new C# MongoDb driver which using IMongoCollection interface :
var bulk = dbCollection.InitializeUnorderedBulkOperation();
foreach (var profile in profiles)
{
   bulk.Find(Query.EQ("_id",profile.ID)).Upsert().Update(Update.Set("isDeleted", true));
}

bulk.Execute();

How to create Update operation with Builder mechanism is clear for me, but how to perform update bulk operation ?

A: MongoDB.Driver has UpdateManyAsync
var filter = Builders<Profile>.Filter.In(x => x.Id, profiles.Select(x => x.Id));
var update = Builders<Profile>.Update.Set(x => x.IsDeleted, true);
await collection.UpdateManyAsync(filter, update);

A: on new Version MongoDB.Driver can be set Flag
var query = Query<Profile>.In(p => p.ID, profiles.Select(x => x.Id));
var update = Update<Profile>.Set(p => p.IsDeleted, true);
Collection.Update(query, update, UpdateFlags.Multi);


text:
Q: Printing out an amount in words (Including decimals) This is the question :
write a program so that the user may enter an amount of money which the program will read back to the user stating the correct magnitudes of thousands, hundreds, and cents.
For example:
Input: R123.99
Output: One hundred and twenty three rands and ninety nine cents.
Assume the input amount will always be in rands and that if the input amount is x, then 10000>x>=0.
this is my code so far :
import javax.swing.*;
import java.util.*;

public class switchEnhanced
{

    public static void main(String[] args){
        boolean corrInput = true;
        String strInput = "";
        String num1 = ""; //0 to 19
        String num2 = ""; //10s to 90s
        String num3 = ""; //100s to 900s
        String num4 = ""; //1000s to 10 000s
        String num5 = ""; //cents 0-9
        String num6 = ""; //cents 10-90s
        int intNum = 0;
        int rands = Integer.parseInt(strInput.split("\\.")[0]);
        int cents = Integer.parseInt(strInput.split("\\.")[1]);

        while (corrInput){
            try{

               strInput = JOptionPane.showInputDialog("Type in an amount : ");
                if (intNum>=0 && intNum <=9999){
                    corrInput = false;
                }
             }
            catch(NumberFormatException ex)
            {
                System.out.println(strInput);
                corrInput = true;
            }
        }

        switch(intNum % 10){
            case 0: num1 = "Zero";break;
            case 1: num1 = "One";break;
            case 2: num1 = "Two";break;
            case 3: num1 = "Three";break;
            case 4: num1 = "Four";break;
            case 5: num1 = "Five";break;
            case 6: num1 = "Six";break;
            case 7: num1 = "Seven";break;
            case 8: num1 = "Eight";break;
            case 9: num1 = "Nine";break;
            default: break;
        }

        switch(intNum){
            case 10: num1 = "Ten";break;
            case 11: num1 = "Eleven";break;
            case 12: num1 = "Twelve";break;
            case 13: num1 = "Thriteen";break;
            case 14: num1 = "Fourteen";break;
            case 15: num1 = "Fifteen";break;
            case 16: num1 = "Sixteen";break;
            case 17: num1 = "Seventeen";break;
            case 18: num1 = "Eighteen";break;
            case 19: num1 = "Nineteen";break;
            default: break;
        }

        switch (intNum/10){
            case 2: num2 = "Twenty";break;
            case 3: num2 = "Thirty";break;
            case 4: num2 = "Fourty";break;
            case 5: num2 = "Fifty";break;
            case 6: num2 = "Sixty";break;
            case 7: num2 = "Seventy";break;
            case 8: num2 = "Eighty";break;
            case 9: num2 = "Ninety";break;
            default: break;
        }

        switch (intNum/100){
            case 1: num3 = "One Hundred";break;
            case 2: num3 = "Two Hundred";break;
            case 3: num3 = "Three Hundred";break;
            case 4: num3 = "Four Hundred";break;
            case 5: num3 = "Five Hundred";break;
            case 6: num3 = "Six Hundred";break;
            case 7: num3 = "Seven Hundred";break;
            case 8: num3 = "Eight Hundred";break;
            case 9: num3 = "Nine Hundred";break;
            default: break;

        }

        switch (intNum/1000){
            case 1: num4 = "One Thousand";break;
            case 2: num4 = "Two Thousand";break;
            case 3: num4 = "Three Thousand";break;
            case 4: num4 = "Four Thousand";break;
            case 5: num4 = "Five Thousand";break;
            case 6: num4 = "Six Thousand";break;
            case 7: num4 = "Seven Thousand";break;
            case 8: num4 = "Eight Thousand";break;
            case 9: num4 = "Nine Thousand";break;
            default: break;

        }

        switch(intNum % 10){
            case 0: num5 = "Zero";break;
            case 1: num5 = "One";break;
            case 2: num5 = "Two";break;
            case 3: num5 = "Three";break;
            case 4: num5 = "Four";break;
            case 5: num5 = "Five";break;
            case 6: num5 = "Six";break;
            case 7: num5 = "Seven";break;
            case 8: num5 = "Eight";break;
            case 9: num5 = "Nine";break;
            default: break;
        }

        switch(intNum){
            case 10: num5 = "Ten";break;
            case 11: num5 = "Eleven";break;
            case 12: num5 = "Twelve";break;
            case 13: num5 = "Thriteen";break;
            case 14: num5 = "Fourteen";break;
            case 15: num5 = "Fifteen";break;
            case 16: num5 = "Sixteen";break;
            case 17: num5 = "Seventeen";break;
            case 18: num5 = "Eighteen";break;
            case 19: num5 = "Nineteen";break;
            default: break;

        }

        switch (intNum/10){
            case 2: num6 = "Twenty";break;
            case 3: num6 = "Thirty";break;
            case 4: num6 = "Fourty";break;
            case 5: num6 = "Fifty";break;
            case 6: num6 = "Sixty";break;
            case 7: num6 = "Seventy";break;
            case 8: num6 = "Eighty";break;
            case 9: num6 = "Ninety";break;
            default: break;

        }

        if(num2.length()== 0){
            System.out.println(num1 + num6);
        }
        else if(num6.length()== 0){
            System.out.println(num1 + num6);
        }
        else
        {
            System.out.println(num4 +" "+ num3 +" "+ num2 +" "+ num1 + "Rand" +" "+ num6 +" "+ num5 + "Cents");
        }
        return;
    }
}

It has a logical error, but i cant for the life of me get around it printing out decimals, please help me

A: Although you have added part of the code in your question I felt it's difficult to handle that kind of approach to resolve your problem.
So I have come up with following code to fulfill your requirement check whether it's fulfill all your requirement. Note that I have only added the decimal to String conversion method. You can use this in your code as you wish.
Note that I have added following methods in my class.
The getString method will return word representation from 0 to 19
The getTeen method used to get word representation for 10,30,40 ... 90
The getWholeWord method used to get word representation of whole numbers
The getDecimalValue method used to get word representation of decimal numbers.
You can go through the below code. I have added inline comments on the code.
public class MyDecimalToString {

public static String getString(int number){
    switch(number){
    case 0:
        return "Zero";
    case 1:
        return"One";
    case 2:
        return"Two";
    case 3:
        return"Three";
    case 4:
        return"Four";
    case 5:
        return"Five";
    case 6:
        return"Six";
    case 7:
        return"Seven";
    case 8:
        return"Eight";
    case 9:
        return"Nine";
    case 10:
        return "Ten";
    case 11:
        return "Eleven";
    case 12:
        return "Twelve";
    case 13:
        return "Thriteen";
    case 14:
        return "Fourteen";
    case 15:
        return "Fifteen";
    case 16:
        return "Sixteen";
    case 17:
        return "Seventeen";
    case 18:
        return "Eighteen";
    case 19:
        return "Nineteen";
    }
    return "";
}

public static String getTeen(int num){

    switch (num) {
    case 2:
        return "Twenty";
    case 3:
        return "Thirty";
    case 4:
        return "Fourty";
    case 5:
        return "Fifty";
    case 6:
        return "Sixty";
    case 7:
        return "Seventy";
    case 8:
        return "Eighty";
    case 9:
        return "Ninety";
    }
    return "";

}

//This method will provide whole number string representation
public static String getWholeWord( int number){

    String output="";
    int input=0;

    String inputNumberString=String.valueOf(number);

    int lastNum=Integer.valueOf(inputNumberString.substring(inputNumberString.length()-1,inputNumberString.length()));
    int numberBeforeLast=(number>9?(Integer.valueOf(inputNumberString.substring(inputNumberString.length()-2,inputNumberString.length()-1))):0);

    if(number>=1000){
        input=number/1000;
        output=getWholeWord(input)+" Thousand ";
    }
    input=number%1000;
    if(input>=100){
        int tempNum=input/100;
        output+=getString(tempNum)+" Hundread ";
    }

    if(numberBeforeLast>0){
        int tempNum=input;
        if(numberBeforeLast==1){
            tempNum=Integer.valueOf(String.valueOf(numberBeforeLast)+lastNum);
            output+=getString(tempNum);
            lastNum=0;
            numberBeforeLast=1;
        }else{
            output+=getTeen(numberBeforeLast)+" ";
        }
    }

    if(lastNum>0){
        output+=getString(lastNum)+" ";
    }else if(numberBeforeLast==0&&number<100){
        output+=getString(lastNum)+" ";
    }
    return output;
}

//This method will return decimal value String representation
public static String getDecimalValue(String decimal){
    String output="";

    //check whether the decimal string contains fractions
    if(decimal.contains(".")){

        //Identify the fraction and non fraction parts in decimal
        String partBeforeDecimalPoint=decimal.split("\\.")[0];
        String partAfterDecimalPoint=decimal.split("\\.")[1];

        if(partBeforeDecimalPoint.length()>0)
            output=getWholeWord(Integer.parseInt(partBeforeDecimalPoint));

        if(partAfterDecimalPoint.length()>0)
            output+= ((output.length()>0?" and ":"")+getWholeWord(Integer.parseInt(partAfterDecimalPoint))+"cents");

    }else{
        output=getWholeWord(Integer.parseInt(decimal));
    }
    return output;
}

public static void main(String[] args) {

    System.out.println(getDecimalValue("12.20"));
    System.out.println(getDecimalValue("2100.99"));
    System.out.println(getDecimalValue("4500.67"));
    System.out.println(getDecimalValue("23450"));
    System.out.println(getDecimalValue("15"));

}
}

These are the output of the sample numbers.
Twelve and Twenty cents
Two  Thousand One Hundread  and Ninety Nine cents
Four  Thousand Five Hundread  and Sixty Seven cents
Twenty Three  Thousand Four Hundread Fifty
Fifteen

A: you are missing this
intNum = Integer.parseInt(strInput);

paste it after JOptionPane.showInputDialog method.
your switch cases don't look correct either. if intNum is 1234
then you will get
num1 = "Four"
num2 = ""
num3 = ""
num4 = "One Thousand"
num5 = "Four"
num6 = ""

probably not what you want.


text:
Q: ODS functionality in R Is there any functionality in R which is just like that of ODS functionality in SAS?

A: As Joris mentioned, some more details on your end will help us help you. In the mean time, here are some links to the functions / resources listed above to get you started:

*

*Flat files - look at ?write.table. You can easily write out comma, tab, or other arbitrary delimited files

*Images - look at ?jpeg. There are equivalent functions for bmp, png, and tiff

*HTML output - CRAN package R2HTML and xtable

*PDFs - single or multipage PDFs can be generated with ?pdf

*PDF via LaTeX - look at ?Sweave. This is not for the faint of heart if you don't understand LaTex. Also look at lyx for an alternative though I have no experience there. brew is another templating approach that looks promising as well.

*Word or word like documents - look at package odfWeave or r2wd or R2PPT
In general, take a look at the ReproducibleResearch task view on CRAN for other alternatives and more details about the above.


text:
Q: Parallel data processing in Python I have an architecture which is basically a queue with url addresses and some classes to process the content of those url addresses. At the moment the code works good, but it is slow to sequentially pull a url out of the queue, send it to the correspondent class, download the url content and finally process it.
It would be faster and make proper use of resources if for example it could read n urls out of the queue and then shoot n processes or threads to handle the downloading and processing.
I would appreciate if you could help me with these:

*

*What packages could be used to solve this problem ?

*What other approach can you think of ?

A: You might want to look into the Python Multiprocessing library. With multiprocessing.pool, you can give it a function and an array, and it will call the function with each value of the array in parallel, using as many or as few processes as you specify.

A: If C-calls are slow, like downloading, database requests, other IO - You can use just threading.Thread
If python code is slow, like frameworks, your logic, not accelerated parsers - You need to use multiprocessing Pool or Process. Also it speedups python code, but it is less tread-save and need to deep understanding how it works in complex code (locks, semaphores).


text:
Q: how to insert different comma separated values into different coloumns in mysql I am taking two comma separated values from the database from different coloumn(supplierrouteallocation:1000,1200 and routesymbol:10xx,12xx) and i want to insert this value into the another table into the different column for example like this
route    symbol

1000     10xx

1100     11xx

but i tried its not working can anyone helpme .thanks
my code
$routes = explode(",",$supplierrouteallocation);
$symbol = explode(",",$routesymbol);

$count=count($routes,$symbol);
for($i=0;$i<$count;$i++)
{

$sql_insertroute="INSERT INTO `fms`.`routestable` (
    `id` ,

`route`
`routesymbol`
)
VALUES (NULL ,'$routes[$i]','$symbol[$i]')
";

mysql_query($sql_insertroute);

}

A: You've got various mistakes :

*

*count() only accepts a single array

*you're missing a coma in your request : ('id', 'route'[,] 'routesymbol')
Here's a piece of code which should work for you :
// get data
$routes = explode(",",$supplierrouteallocation);
$symbols = explode(",",$routesymbol);

// prepare the request
$sql_insertroute = "INSERT INTO `fms`.`routestable` (`id`, `route`, `routesymbol`) VALUES ";

// create an insert line per data couple
$vals = array();
$n = max(count($routes), count($symbols));
for($i=0;$i<$n;$i++) {
    $route = isset($routes[$i]) ? "'".$routes[$i]."'" : "NULL";
    $symbol = isset($symbols[$i]) ? "'".$symbols[$i]."'" : "NULL";
    array_push($vals, "(NULL, $route, $symbol)");
}

// join those lines with comas, and add'em to the request
$sql_insertroute .= implode(', ', $vals);

A: Try this
$sql_insertroute="INSERT INTO `fms`.`routestable` (`id`,`route`,`routesymbol`) VALUES (NULL,'".$routes[$i]."','".$symbol[$i]."')";


text:
Q: How to use purescript-css to set CSS margin property to auto? I am converting a CSS file to purescript-css and in the CSS file there is the line margin:auto . I have looked at the margin function in the CSS.Geometry module of the purescript-css library and I cannot see how to use it to set the margin property to auto. Can anyone help?
Sincerely,
Eric M.


text:
Q: How to redirect from url parameters in wordpress I am creating a download page on my wordpress site.
I want to pass in a url like http://www.mypersonaldomain.com/download?url=http://link.to/the.pdf
I would like it to wait 3 seconds or so, thanking them for downloading.
I have tried some php and meta tags and neither seemed to work well in wordpress.
<meta http-equiv="refresh" content="3; URL=<%out.print(request.getParameter("url"))%>">

and using a php insert plugin
[insert_php]
$url= $_GET['url'];
header("refresh:3;url=$url" );
[/insert_php]

A: //Condition Start $url = 'http://www.mypersonaldomain.com/download?url=http//link.to/the.pdf'wp_redirect( $url);exit;/ Condition End