text:
Q: jquery fade in fade out priority I have recently posted about a hover effect with hover.
It now works ok, but I was wondering if there is a way to prioritise the effect. For example, if the user goes through a sequence of image rollovers quickly it takes a while for the animation to catch up. I don't mind the animations continuing, but I would like the item that is currently being hovered over to fadein immediately.
Here is my code at the moment:
<!DOCTYPE html>

<title>Robs Test</title>

hello

there

rob

Is there something I can do to make the div that's being hovered over prioristise over the others? So I don't have to wait till the animation completes.
Cheers
Rob

A: You can use stop function in jQuery to make it better. It will stop the animation in progress.
function over(event){
    var over_id = '#box_over_' + $(this).attr('id').replace('over_','');

    $(over_id).stop(true, true).fadeIn(400);
    $(over_id).css("display","normal");

}
function out(event) {
    var over_id = '#box_over_' + $(this).attr('id').replace('over_','');

    $(over_id).stop(true, true).fadeOut(400);

}

A: I would only trigger the animations (especially if they are long) if the user hovers over the image for set threshold amount of time (not on every rollover).
See related post on implementing controlled hover.

A: Related to what @SliverNinja linked to, specifically for your scenario:
function over(event) {
    var $this = $(this);
    $this.data('hoverTimer', setTimeout(function(){
        timer = null;
        var over_id = '#box_over_' + $this.attr('id').replace('over_', '');

        $(over_id).fadeIn(400);
        $(over_id).css("display", "normal");
    }, 200));
}

function out(event) {
    var timer = $(this).data('hoverTimer');

    if (timer !== null) {
        clearTimeout(timer);
    }
    var over_id = '#box_over_' + $(this).attr('id').replace('over_', '');

    $(over_id).fadeOut(400);
}

Here's the fiddle: http://jsfiddle.net/9RR93/

A: If you want to go whole ham, you can build your own priority queue system for objects using jquery animations. Then whenever a new animation is started, you can check the queue to see if there is an existing animation that needs to be stopped (if its priority is lower), or if the new animation should not start (due to a higher priority animation already running in the queue). Just wrote this in the last 10 mins so, check for bugs lol
Animations = {
    active : [],
    remove(anim){
        this.active.splice(this.active.indexOf(anim),1);
    },
    test(){
        this.$testObj1 = $('
hi1
');
        this.$testObj2 = $('
hi2
');
        this.$testObj3 = $('
hi3
');
        $('html').append(this.$testObj1).append(this.$testObj2).append(this.$testObj3);
        let testAnim1 = new Animation(
            'one',
            this.$testObj1,
            {top:100},
            1000,
            1 );
        let testAnim2 = new Animation(
            'two',
            this.$testObj2,
            {top:200},
            1000,
            2 );
        let testAnim3 = new Animation(
            'three',
            this.$testObj3,
            {top:300},
            1000,
            3 );
        setTimeout(function(){testAnim3.Animate();},1000) // lowest priority
        setTimeout(function(){testAnim2.Animate();},3000)
        setTimeout(function(){testAnim1.Animate();},2000) // highest priority
        setTimeout(function(){testAnim2.Animate();},6000)
    }
}
class Animation {
    constructor(name,$el,animationList,duration,priority,callback=null){
        this.name = name;
        this.$el = $el;
        this.animationList = animationList;
        this.priority = priority;
        this.duration = duration;
        this.callback = callback;
    }

    Animate(){
        let toRemove = [];
        console.log('animating : '+this.name);
        Animations.active.filter(x => x.priority > this.priority).forEach(x => {
            console.log('toRemPush :'+x.name);
            toRemove.push(x)
        });
        toRemove.forEach(x => {
            console.log('stopping and removing '+x.name+', priority '+x.priority+', due to '+this.name+' with priority '+this.priority);
            x.$el.stop();
            Animations.remove(x);
        });
        if (Animations.active.filter(x => x.priority < this.priority).length > 0){
            console.log('fail to start '+this.name+' due to higher priority anims running.');
            return;
        }
        this.$el.animate(
            this.animationList,
            this.duration,
            function(e){
                Animations.remove(this);
                if (this.callback != null && this.callback instanceof Function) {
                    this.callback(e);
                }
            });

       Animations.active.push(this);
    }
}


text:
Q: PHP Email: To, CC I have a PHP script that automatically send outs an email.  I have it working great, but when I try to add a CC, it doesn't work.  Below is my code for the email to:
$email_to = "$theData2"; // Who the email is to

$headers = "From: ".$email_from;

$ok = @mail($email_to, $email_subject, $email_message, $headers);

I have tried the following to get CC to work, but I haven't had any luck.
$email_cc = "example@info.com";
$headers .= "CC: ".$email_cc;

and also have tried this:
$headers .= "CC: sombodyelse@noplace.com";

I can't get it to email to both the: to & cc.
Any help would be greatly appreciated. Thanks!

A: You forgot your newline.
$headers .= "\r\nCc: ".$email_cc;

A: Try ending your header entries with "\r\n":
$headers .= 'From: <webmaster@example.com>' . "\r\n";
$headers .= 'Cc: myboss@example.com' . "\r\n";

A: Have you tried with "Cc" and not "CC" ? And do not forget the "\n" at the end.

A: Don't use PHPs mail() function directly. Use a wrapper class such as SwiftMailer or PHPMailer. They give you far more flexibility and are safer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implement polling with setInterval inside a Bull processor (NestJS) I'm using NestJs and Bull library to implement a queue. The queue should get a job and then perform a polling to external endpoint. When the desired response is back I want to return it and complete the job.
The problem is the job is marked as completed after the first iteration of the setInterval and returns with undefined instead of waiting for the actual response.
Controller -
@Post("scan")
 async scanSite(@Body() url: ScanSiteDto) {
  try {
   const { scan_id: scanId } = await someService.scanSite(url);
   const job = await this.someQueue.add("scanUrl", {scanId});
  } catch (error) {
    if (error instanceof HttpException) {
     throw new HttpException(error.message, error.getStatus());
    }
   }
  }

Processor -
@Process("scan")
 async handleScanUrl(job: Job) {
  const { scanId } = job.data;
  const getData = async () => {
   try {
    const { data } = await axios.post(
    URL, body, config
    );
    return data;
   } catch (error) {
      console.log(error);
     }
    };

    let intervalId;

    const intervalCb = async () => {
     console.log("fetching...");
     const data = await getData();
     if (data.status === "finished") {
      clearInterval(intervalId);
      return data;
     }
    };

    intervalId = setInterval(intervalCb, 10000);

    const result = intervalCb();
    return result;
    }

    @OnQueueCompleted()
    onCompleted(job: Job) {
     console.log(`From onCompleted: ${job.returnvalue}`);
    }

So handleScanUrl run once, then onCompleted is logging with undefined as the returned value, then handleScanUrl is continue running but the onCompleted value is not updated.


text:
Q: RestSharp examples don't work in latest version I'm trying to use RestSharp for the first time, but none of the examples I have found work with the current version. For example, the Getting Started example results in the following error:

'RestSharp.RestClient' does not contain a definition for 'Execute' and no extension method 'Execute' accepting a first argument of type 'RestSharp.RestClient' could be found (are you missing a using directive or an assembly reference?)

Does anyone know where I can find working examples using RestSharp 103.x?

A: According to GitHub issue Execute method is not available on some platforms. You may have to use different RestSharp DLL or use ExecuteAsync method instead.


text:
Q: why PHPMailer taking too much time to send email and also once it sent email , i got mail in spam i want to send email using user's entered email address to my email address using PHPMailer and without SMTP. But it takes too much time to send email and once it sent email i got mail in spam instead of inbox.
Below is my complete code-
<?php
session_start();
require_once 'class.phpmailer.php';
$mail = new PHPMailer;

$mail->From = $_POST['email'];
$mail->FromName ='Contacted By : '.$_POST['fname'];

$mail->addAddress("dev5.veomit@gmail.com");

$mail->addReplyTo($_POST['email'], "Reply");

$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = "Name : ".$_POST['fname'].'
Email Address : '.$_POST['email'].'
Message : '.$_POST['msg'];
$mail->AltBody = "This is the plain text version of the email content";

if(!$mail->send())
{
    echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
    $_SESSION['sucess-email']='You Have Contacted Successfully.';
    header("Location: https://m-expressions.com/test/voy/");
}
 ?>

Please help me solve this problem and thanks in advance.

A: First of all you are using a very old version of PHPMailer; Update to the latest version.
While you say it's slow, you don't say how slow - 1 second? 30 seconds? 10 minutes? You are sending using the default mail() transport, which means you are submitting to a local mail server - which may be misconfigured or slow, but that's outside PHPMailer's area of responsibility.
You are forging the "from" address which (if your mail server allows you to do it at all), will result in failing SPF checks, which will usually put you into the spam folder. Do this instead:
$mail->setFrom('me@example.com', 'My Name');
$mail->addAddress('me@example.com');
$mail->addReplyTo($_POST['email']);

That is, send from yourself, to yourself, but using a reply-to of the submitter. This way replies to the message will go to the submitter, but you're not forging the from address.
I suggest you start again using the contact form example provided with PHPMailer.


text:
Q: Regular Expression with "_" only inbetween I want Regulare expression which allow only _ in between strings only.Not Allow space at any place.
I had try ^[a-z]+[_]+[a-z0-9]+(?!_)$ but in this case _ is compulsory.I want it optional.I want out out like : user_user12 or user12

A: ^[a-z][a-z0-9]*(?:(?<!\d)_[a-z0-9]+)?$

You can group it and make it optional

A: You can simply use \w (numbers, letters, and underscores):
^\w+$

https://regex101.com/r/tM3jL2/2
As you have mentioned earlier that it cannot start with a digit, something like this should work (also disallows repeated underscores):
^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)*$

https://regex101.com/r/sE6tW1/2


text:
Q: Prove the series $\sum_{n=1}^\infty (n(f(\frac{1}{n}) - f(-\frac{1}{n})) - 2f'(0)) $ converges Prove the series $\sum_{n=1}^\infty (n(f(\frac{1}{n}) - f(-\frac{1}{n})) - 2f'(0)) $ converges where $f$ is defined on $[-1,1]$ and $f''(x)$ is continuous.
I already have a solution for this but I am not quite following it.
It uses the Taylor expansion about $0$ to get:
[Note: this is the start of their solution not mine]
$f(x) = f(x) +f'(0)\frac{x}{1} + f''(0)\frac{x^2}{2} + f'''(t)\frac{x^3}{6}$
$f(-x) = f(x) - f'(0)\frac{x}{1} + f''(0)\frac{x^2}{2} - f'''(s)\frac{x^3}{6}$
For some $s,t \in [-1,1]$.
Here is my issue: I am not clear on the $s,t$ used in the third derivative. We know the second derivative is continuous, maybe the statement should be that the third derivative is continuous?

A: You do not know that $f''$ is differentiable, and so cannot speak of $f'''$; hence the highest degree Taylor expansion is to degree 2:

$f(x) = f(0) +f'(0)x +\frac{f''(s)}{2}x^2$ for some $s$ between $0$ and $x$.

Hence, there are $s_n, t_n \in \left[\frac{-1}{n},\frac{1}{n}\right]$ such that

$n \left(f\left(\frac{1}{n}\right) -f\left(\frac{-1}{n}\right)\right) -2 f'(0)$
$= n \left(f(0) +\frac{f'(0)}{n} +\frac{f''(s_n)}{2n^2} -f(0) +\frac{f'(0)}{n} -\frac{f''(t_n)}{2n^2}\right) -2f'(0)$
$= \frac{f''(s_n)-f''(t_n)}{2n}$

It is the sum of the above terms which one wishes to show convergent. However, I am not sure whether this is always the case, for instance if $f''(x) = \frac{x}{|x|\log |x|}$ and $s_n \approx -t_n \approx \frac{1}{n}$. Unfortunately I do not have enough reputation to post this as a comment instead of an answer.

A: $f(x)=f(0)+f'(0)x+\frac {f''(t)x^{2}} {2}$ and
$f(-x)=f(0)-f'(0)x+\frac {f''(s)x^{2}} {2}$. So $n(f(\frac 1 n) -f(-\frac 1 n))-2f'(0)$ is bounded by a constant times $\frac 1 {n^{2}}$ by MVT applied to the second derivative provided third derivative exists and is bounded . I think there is a typo in the question and second derivative is not enough.


text:
Q: Secure dnsmasq dns daemon with whitelist I'm using dnsmasq on a server (bound to wan IP) and would like to add an acl/whitelist for ip ranges/ip address allowed to resolve dns using my server.
I can't seem to find anything from Google, is there an option to whitelist/block non allowed addresses from resolving using my server?
Please don't suggest using iptables or other firewall solutions.

A: The only solution I know is through iptables.
It is easiest to do this with ipset: create a list of allowed IPs,
    ipset create good_ips hash:net

add your ips to the list,
     ipset add good_ips 8.8.8.8
     ipset add good_ips 192.168.155.0/24

Then you can block all IPs not in the list, trying to access your DNS server, as follows:
      iptables -A INPUT -p udp  --dport 53 -m set  --match-set !  good_ips src -j DROP

This can be made permanent with:
      ipset save > /etc/ipset.conf
      systemctl enable ipset

(the last command is for systemd services, which is by now most of Linuxes; if you are not on such a system, please adjust it accordingly).


text:
Q: Hyperledger Fabric Illegal argument exception error I am using Java SDK of Hyperledger Fabric 1.4.2, I implemented a function that writes on the Hyperledger. For that, I am using: 2 peers, 1 orderer, 1 channel. I tried to run my app but I got this error:
Caused by: java.lang.IllegalArgumentException: The proposal responses have 0 inconsistent groups with 1 that are invalid. Expected all to be consistent and none to be invalid.

A: You need your chaincode to be deterministic. I guess that you are sending the transaction to 2 peers and each computes a different chaincode result.
Please edit your question with:

*

*The endorsement policy you have

*What your chaincode is doing


text:
Q: c# wpf - ListView.ScrollIntoView(LastItem) does not work properly like some other people here i have a ListView (updated via binding in a GridView).
I want to keep the last inserted Item in the View. So i tried
LView.ScrollIntoView(LView.Items[LView.Items.Count - 1]);

This is working almost fine. Altough the first item which would have to be scrolled into view is only shown like 80% of its whole row (depending on how high i define the whole ListView, i almost got 100%).
The real problem is that the following items which should get scrolled into view are not shown. It is also noticable at the Scrollbar itself which is not at the bottom.
Last Item is not shown
Here is the code of my MainWindow.
public partial class MainWindow : Window
{
    private InterfaceCtrl ICtrl;
    private ListView LView;
    public MainWindow()
    {
        InitializeComponent();

        this.ICtrl = new InterfaceCtrl();
        this.ICtrl.ProgressCollection.CollectionChanged += this.CollectionChanged;

        Grid MainGrid = new Grid();
        this.Content = MainGrid;

        GridView gv = new GridView();
        Binding StartTimeStampBinding = new Binding() { Path = new PropertyPath("StartTS"), Mode = BindingMode.OneWay, StringFormat = "dd.MM.yyyy - HH:mm:ss.fff" };
        GridViewColumn gvTCStartTS = new GridViewColumn() { Header = "Time", Width = 150.00, DisplayMemberBinding = StartTimeStampBinding };
        gv.Columns.Add(gvTCStartTS);

        LView = new ListView() { Height = 192, Width = 250, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, View = gv, ItemsSource = this.ICtrl.ProgressCollection };

        MainGrid.Children.Add(LView);

        ICtrl.StartMyThread();
    }

    private void CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new System.Action(delegate ()
        {
            if (LView != null && LView.Items.Count > 0)
            {
                LView.UpdateLayout();
                //LView.ScrollIntoView(LView.Items[LView.Items.Count - 1]);

                LView.SelectedIndex = LView.Items.Count;
                LView.ScrollIntoView(LView.SelectedItem);
            }

        }));
    }

}

Thank you.

EDIT:
It seemed to be a timing problem, although all the wanted data was in the LView at the right time i tried a workaround with a Textbox bound to the Timestamp.
        TextBox tb = new TextBox(); // { Width = 250, Height = 28, Margin= new Thickness(10,100,1,0)};
        tb.SetBinding( TextBox.TextProperty , new Binding("LastMsgTimestamp") { Source = this.ICtrl, Mode = BindingMode.OneWay, StringFormat = "dd.MM.yyyy - HH:mm:ss.fff" });

        tb.TextChanged += this.UpdateScrollbar;
        tb.Visibility = Visibility.Hidden;

It seems to me like there is a timing issue within the binding to the LView and the fired Event of the ObservableCollection. This also includes the PropertyChanged of the ObservableCollection.
I tried the events TargetUpdated and SoruceUpdated directly within LView but those didn't came up at all.

A: You could try to call any of the ScrollToBottom() or ScrollToVerticalOffset() methods of the ListView's internal ScrollViewer element:
private void CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new System.Action(delegate ()
    {
        if (LView != null && LView.Items.Count > 0)
        {
            LView.UpdateLayout();
            ScrollViewer sv = GetChildOfType<ScrollViewer>(LView);
            if (sv != null)
                sv.ScrollToBottom();

            LView.SelectedIndex = LView.Items.Count;
            LView.ScrollIntoView(LView.SelectedItem);
        }

    }));
}

private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == null)
        return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null)
            return result;
    }
    return null;
}

A: I have made the following sample. You could try to call ScrollToBottom in inner ScrollViewer as @mm8 points out. Nevertheless when saw the answer I was already making my sample, so here it is:
Codebehind
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ListViewScroll
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<string> Names { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            Names = new ObservableCollection<string>();
            ListView.ItemsSource = Names;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Names.Add("Some Name" + ++someInt);
            // Get the border of the listview (first child of a listview)
            var border = VisualTreeHelper.GetChild(ListView, 0) as Decorator;

            // Get scrollviewer
            var scrollViewer = border.Child as ScrollViewer;
            scrollViewer.ScrollToBottom();
        }

        private static int someInt;
    }
}

XAML
<Window x:Class="ListViewScroll.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <ListView Grid.Row="0" Name="ListView"/>

        <Button Content="Add" FontSize="20" Grid.Row="1"
                Click="ButtonBase_OnClick"/>
    </Grid>
</Window>

In this case I am handling the scrolling in the button click event but you may change this to fit your requirements

It works, I have tested.
Hope this helps


text:
Q: how to insert into multiple fields in same db I am looking to insert a single selection into a field for multiple users.  I have the following code, when the selection is made and submit is entered.  I do not get an error, I get the next page with the message posted 5 times, which is how many users are not it the weekpicks table. But nothing is inserted into the DB.

<?
// This code is to use to place info into the MySQL

$sTeam1 = $_POST['sTeam1'];

// (WHERE username FROM authorize WHERE username not in ( SELECT username FROM weekpicks WHERE whatweek='$totalnoOfWeek' )" .

//$nMemberID = (integer) Query

$sql_events = mysql_query("SELECT username FROM authorize WHERE username not in ( SELECT username FROM weekpicks WHERE whatweek='$totalnoOfWeek' )") or die(mysql_error());

while ($row = mysql_fetch_array($sql_events)) {
$username = $row["username"];

("INSERT INTO weekpicks SET " . "username = '" . ($username) . "'," . "date_create = NOW(), " . "whatweek = '" . ($totalnoOfWeek) . "'," . "team = '" . addslashes($sTeam1) . "'" . 'INSERT');

echo "

Your pick of " . ($sTeam1) . ", for week " . ($totalnoOfWeek) . ", has been added.

Return to main page

            ";
}
?>

A: You are creating the string for insert but you are not running it.
Fixing your code it'd be:
while ($row = mysql_fetch_array($sql_events)) {
$username = $row["username"];
mysql_query("INSERT INTO weekpicks SET " . "username = '" . ($username) . "'," . "date_create = NOW(), " . "whatweek = '" . ($totalnoOfWeek) . "'," . "team = '" . addslashes($sTeam1) . "'");

//echo ...
}

Fixing the string syntax you could do this, which looks nicer. Also using mysql_real_escape_string() instead of addslashes(), since addslashes is not as safe as mysql's native function for php.
$sTeam1 = mysql_real_escape_string($sTeam1);
mysql_query("INSERT INTO weekpicks SET username = '$username', date_create = NOW(), whatweek = '$totalnoOfWeek', team = '$sTeam1');

Another thing I must tell you:
Stop using mysql_*, use mysqli_* instead.
mysql_ was removed from PHP7 and deprecated after PHP 5.5
It's not as safe as mysqli_, so consider improving your code to the new model.
Follow this guide in order to change your code properly.


text:
Q: Laravel ManyToMany retrieving data I'm new to Laravel and breaking my head trying to work with relationships.
I have 2 tables:
members
groups
And a pivot table: member_group
A member can belong to many groups, a group can have many members.
When I edit a member, I create checkboxes for the groups.
I need to mark the ones that the member already has as 'checked'
My edit method:
 public function edit($id)
{
    $cities = City::orderBy('city_name')->pluck('city_name', 'city_id');
    $member = Member::findOrFail($id);
    $groups = Group::all();

    return view('members.edit', compact('member', 'cities', 'groups'));
}

In my edit.blade:
@foreach($groups as $group)
 <?php $exists = $member->groups()->where('groups.group_id', $member->group_id); ?>
 @if($exists)
 <input type="checkbox" name="groups[]" value="{{ $group->group_id }}" checked> {{ $group->group_name }}
 @else
 <input type="checkbox" name="groups[]" value="{{ $group->group_id }}"> {{ $group->group_name }}
 @endif

....
All the checkboxes are checked, although the member does not belong to all the groups.
Looking at this post: Stackoverflow post I tried almost everything they offer there, only got errors. The only one that works is this one:
$exists = $member->groups->contains($group->group_id);
Don't know about wastefulness or not, it's the only one that works.

A: I think, in your blade $exists = $member->groups()->where('groups.group_id', $member->group_id); you should use group.group_id instead of groups.group_id and also use first() method.
$exists = $member->groups()->where('group.group_id', $member->group_id)->first();

Update:
Can you try this ?
$member = Member::findOrFail($id)->with(['groups'=>function($query){
    $query->selectRaw('groups.group_id');
}])->first();

And in blade:
$exists = $member->groups()->whereIn('groups.group_id', $member->groups)->first();


text:
Q: Which specs of JSF used PARTIAL_STATE_SAVING_METHOD? Source code of MyFaces (branch 1.1.8) has usage of context parameter PARTIAL_STATE_SAVING_METHOD in NavigationHandlerImpl.java .
Also NavigationHandlerImpl.java has comment //Specs 10.1.3: default server saving on 82 line.

*

*Which of specs they talking about and where i can download it? Can't find specs for JSF 1.1.

*Why this context parameter disappeared from next implementations?

This is PARTIAL_STATE_SAVING behaviour or STATE_SAVING_METHOD?
Variable declaration on line 66 confuse a bit... (stateSavingMethod)

A: The code you mention belongs to the very early attempts of PSS technique added in JSF 2. There is no relationship with the spec. Please update to a recent version of Apache MyFaces (2.1, 2.2)


text:
Q: File is open and doesn't load in R I'm trying to load an xlsx list, but a file is open and doesn't load in R.
Code:
dados_pp_master[[i]] <- data.frame(read_excel(arquivo_caracter[i], sheet = "PP Master",skip = 1, .name_repair = "minimal")

Log:
Error: Evaluation error: zip file 'V:/file/~$Schedule_3.xlsx' cannot be opened.

Is there any way to load an open xlsx file?

A: the ~$ at beginning of your file path implies that you are only working with a cached version of the changes? I'm pretty sure you cannot open this specific file with Excel itself, simply because it is not a "normal" excel file. The error message in that context makes a lot of sense then.


text:
Q: Using rlang's sym inside a function and getting error I have the following function:
library(tidyverse)
library(dplyr)
library(rlang)

custom_filter <- function(
  df,
  pos_filter_1 = NULL,
  ct_filter_1,
  filter_1
){
  pos_filter_1 <- paste0("df$", pos_filter_1)

  position_filter_1 <- if (!is.null(pos_filter_1)) (match.fun(filter_1)(!!rlang::sym(pos_filter_1), ct_filter_1)) else TRUE

  fin_df <- df %>%
    dplyr::filter(position_filter_1)

  return(fin_df)
}

However, when I try to use it on a dataframe, I get the error Error in !rlang::sym(pos_filter_1) : invalid argument type. Here is an example in which I try to filter on rows in which the column qb_count is less than or equal to 5:
df <- tibble(x1 = letters[1:9],
             qb_count = 1:9,
             rb_count = 10:18)

custom_filter(df, 'qb_count', 5, "<=")

What am I missing? This works fine if I do it outside of the function. Appreciate any help!

A: We may create the if/else as
custom_filter <- function(
  df,
  pos_filter_1 = NULL,
  ct_filter_1,
  filter_1
){

if(is.null(pos_filter_1)) {
 df

} else {
  df %>%

    dplyr::filter(match.fun(filter_1)(!! rlang::ensym(pos_filter_1),
         ct_filter_1) )

  }
  }

-testing
>   custom_filter(df, NULL, 5, "<=")
# A tibble: 9 × 3
  x1    qb_count rb_count
  <chr>    <int>    <int>
1 a            1       10
2 b            2       11
3 c            3       12
4 d            4       13
5 e            5       14
6 f            6       15
7 g            7       16
8 h            8       17
9 i            9       18
> custom_filter(df, 'qb_count', 5, "<=")
# A tibble: 5 × 3
  x1    qb_count rb_count
  <chr>    <int>    <int>
1 a            1       10
2 b            2       11
3 c            3       12
4 d            4       13
5 e            5       14

Or an easier option without having to check with if/else is wrapping the code in if_any/if_all (it should work with one or more columns) and using any_vars (if the column is not present, it wouldn't evaluate)
custom_filter <- function(
  df,
  pos_filter_1 = NULL,
  ct_filter_1,
  filter_1
  )
  {

  df %>%
    dplyr::filter(if_any(any_of(pos_filter_1),
          ~ match.fun(filter_1)(.x,
                ct_filter_1) ))

  }

-testing
>   custom_filter(df, NULL, 5, "<=")
# A tibble: 9 × 3
  x1    qb_count rb_count
  <chr>    <int>    <int>
1 a            1       10
2 b            2       11
3 c            3       12
4 d            4       13
5 e            5       14
6 f            6       15
7 g            7       16
8 h            8       17
9 i            9       18

>   custom_filter(df, 'qb_count', 5, "<=")
# A tibble: 5 × 3
  x1    qb_count rb_count
  <chr>    <int>    <int>
1 a            1       10
2 b            2       11
3 c            3       12
4 d            4       13
5 e            5       14


text: Q: Embedded Python Via Yocto I have come across while doing code to raspberrypi 3+ with Yocto. The Python code is absolutely unreliable. I can write Python3 script that runs beautifully Even when there is a Bug. No error messages it just runs over. It makes debugging Python quite hard. Any advice is appreciated


text:
Q: Symfony form get user id In order to filter the available options on one section of my web application, I would like to get the user object at the form object. I found some information about possible ways to do that (using sfContext, for instance) but some users discouraged this approach.
What is a possible manner to achieve my purpose?

A: The best way is to add some logic to BaseForm so you can use self::getValidUser(); without ever using sfContext, which is indeed generally not recommended.
Check this awesome blog post for more infos : http://prendreuncafe.com/blog/post/2010/02/17/User-Dependant-Forms-with-Symfony


text:
Q: How to write a Streaming Structured Stream into Hive directly? I want to achieve something like this :
df.writeStream
.saveAsTable("dbname.tablename")
.format("parquet")
.option("path", "/user/hive/warehouse/abc/")
.option("checkpointLocation", "/checkpoint_path")
.outputMode("append")
.start()

I am open to suggestions. I know Kafka Connect could be one of the options but how to achieve this using Spark. A possible workaround may be what I am looking for.
Thanks in Advance !!

A: Spark Structured Streaming does not support writing the result of a streaming query to a Hive table directly. You must write to paths.
For 2.4 they say try foreachBatch, but I have not tried it.


text:
Q: Ported code having issues, can't figure out how this should work Okay, so I ported this bit of code from a javascript file to Lua. It's a solution to the Bin Packing problem. Basically, this is a given a target rectangle size "init(x,y)", and then is given a table with blocks to fill said rectangle, "fit(blocks)". However when I run this I get the error "attempt to index local 'root' (a number value)". What is going wrong here?
I also don't fully understand how this code is working, someone helped me along with the porting process. When I pass a table "blocks" into the fit function, is it adding the attributes of block.fit.x and block.fit.y?
Any help is appreciated.
Edit: Fixed the error by changing "." to ":" when calling a method.
--ported from https://github.com/jakesgordon/bin-packing

local _M = {}

mt = {
  init = function(t, x, y)       --takes in dimensions of target rect.
    t.root = { x = 0, y = 0, x = x, y = y }
  end,

  fit = function(t, blocks)     --passes table "blocks"
    local n, node, block
    for k, block in pairs(blocks) do
      if node == t.findNode(t.root, block.x, block.y) then
        block.fit = t.splitNode(node, block.x, block.y)
      end
    end
  end,

  findNode = function(t, root, x, y)
    if root.used then                 --if root.used then
      return t.findNode(root.right, x, y) or t.findNode(root.down, x, y)
      elseif (x <= root.x) and (y <= root.y) then
        return root
      else
        return nil
    end
  end,

  splitNode = function(t, node, x, y)
    node.used = true
    node.down = { x = node.x,   y = node.y + y, x = node.x,   y = node.y - y }
    node.right = { x = node.x + x, y = node.y,   x = node.x - x, y = y      }
    return node;
  end,
}

setmetatable(_M, mt)

-- Let's do the object-like magic
mt.__index = function(t, k)
  if nil ~= mt[k] then
    return mt[k]
  else
    return t[k]
  end
end

mt.__call = function(t, ...)
  local new_instance = {}
  setmetatable(new_instance, mt)
  new_instance:init(...)
  return new_instance
end

return _M

A: I don't know if this will help, but here is how I would have ported the code over to Lua.
local Packer = {}

Packer.__index = Packer

function Packer:findNode (root, w, h)
  if root.used then
    return self:findNode(root.right, w, h) or self:findNode(root.down, w, h)
  elseif w <= root.w and h <= root.h then
    return root
  else
    return nil
  end
end

function Packer:fit (blocks)
  local node
  for _, block in pairs(blocks) do
    node = self:findNode(self.root, block.w, block.h)
    if node then
      block.fit = self:splitNode(node, block.w, block.h)
    end
  end
end

function Packer.init (w, h)
  local packer = {}
  packer.root = {x = 0, y = 0, w = w, h = h}
  return setmetatable(packer, Packer)
end

function Packer:splitNode (node, w, h)
  node.used = true
  node.down  = {x = node.x,     y = node.y + h, w = node.w,     h = node.h - h}
  node.right = {x = node.x + w, y = node.y,     w = node.w - w, h = h         }
  return node
end

return Packer

Just place it in a file like packer.lua and import it into your main.lua with local Packer = require "packer"


text:
Q: When using alias in NGiNX is the content of the file called loaded on the RAM? When I load a static file via alias does it load the whole file into the RAM and then sends it to the user or is it stream directly to the user?
I am wandering because I have a server with 250MB of RAM and I was wandering what would happen if I use alias in NGiNX to get a static file that was 250MB or more.

A: It is streamed directly to the user. People are running servers with 1 GB of ram and serving files with gigabytes in size for hundreds of users simultaneously.


text:
Q: Mysql / export query result in csv file I have mysql script which select needed data via LEFT JOIN and save result in csv file. But the problem is column names are missed in result file. What i doing wrong ?
SELECT
a.*, b.pr_name
INTO OUTFILE 'johnoggyresult3.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM
    `fileb` AS b
LEFT JOIN
    `filea` AS a ON b.pr_hand_size = a.user_hand_size
ORDER BY
     a.user_id

A: Just add columns names with SELECT. Something like this should work:
SELECT *

INTO OUTFILE 'johnoggyresult3.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

FROM (
SELECT 'column1', 'column2'
UNION ALL
(SELECT
a.column1, b.pr_name
FROM
    `fileb` AS b
LEFT JOIN
    `filea` AS a ON b.pr_hand_size = a.user_hand_size
ORDER BY
     a.user_id) AS q
)

Please note that dumping to CSV is done at the end, after result was fetched and sorted and after headers were attached to dataset. You also need to sort data first before adding row with headers or otherwise headers would be sorted too and could land somewhere in the middle of dataset instead of top like intended.


text:
Q: Convert word list into array I've tried to see if there were any scripts to convert a list of words into an array and I can't seem to find one.
Anyone know where I can find one?
Input:
Dog
Cat
Hamster

Gets converted to
["Dog", "Cat", "Hamster"]

Noo.. this isn't what I mean. I have a txt file with a bunch of words on each line and I was wondering if there was something out there already created that can convert each word into an array.

A: Just use split on the string.
For example:
var textarea = document.getElementById('list');
var arr = [];
textarea.addEventListener('input', function () {
    arr = this.value.split('\n');
    console.log(arr);
}, false);

Demo

A: If the string is actually "Dog\nCat\nHamster" then just do
"Dog\nCat\nHamster".split('\n');//returns ["Dog", "Cat", "Hamster"]

For a TextArea try this
myTextArea.value.split('\n'); // it will return desired output.

Where myTextArea is the TextArea you can get using getElement.

A: I think the best solution for a textarea input is using the match() function of javascript like this:
var words = []
$('textarea').on('blur', function(){
    words = $(this).val().match(/\w+/g)
    alert(words)
})

here a fiddle of it working.
This doesn't need for the words to be in different lines.


text:
Q: Reduce spacing inside cell, vertical and horizontal positioning of figure & defining some text in preamble I want to make a template document (with custom margins, font sizes, header, footer etc...).
I have specified only footer on first page and header on all other pages, margins, text width, text height, header height, page borders.. that's all as I want.
I have marked with numbers in following pictures things I want to change.

*

*I want multiline text like represented, but I want to reduce line spacing. Code:
%%begin page borders
\SetBgOpacity{100.0}    %% Select opacity
\SetBgScale{1}          %% Select scale factor of logo
\SetBgAngle{0}          %% Select rotation of logo
\SetBgColor{black}      %% Select color
\SetBgContents{
\begin{tikzpicture}[overlay,remember picture]
\node[anchor=north] at ($(current page.north west)+(1.5cm,-1cm)$)
{\rotatebox{90}{\makecell[r]{\scriptsize\selectfont Reproduction or any
use not conformity with the intended\\

\scriptsize\selectfont application is not permissible.}}};
\node[anchor=south] at ($(current page.south west)+(1.5cm,1cm)$)
{\rotatebox{90}{\makecell[l]{\scriptsize\selectfont Nachdruck oder
Verwendung, die nicht der beabsichtigten\\

\scriptsize\selectfont Anwendung entspricht, ist nicht zulässig.}}};

\end{tikzpicture}
}
%%end page borders

*I didn't finish my table on the left, but I know how to add more rows it's not a problem. My question is how to fix row height or how to remove or reduce additional text spacing inside cell? I dont want to resize table because I want my width to be the same.

*How to position figure vertically and horizontally centered inside cell? Is there any option like [anchor=center]?

*On first page footer and all other pages header I have same attribute in header and footer for example Project. Can I define in preamble for example: project=My first project in LaTeX; and then in header and footer in specific cell when i write project, my output will be My first project in LaTeX.
Should I implement KOMA-scripts, is there any advantages in my case?
With KOMA-scripts can I specify exactly which font size I want to use for example \fontsize{5} Some random text. Iam asking this because of easier changing font size inside tables. :)
my complete code:
%%begin preamble
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[demo]{graphicx}
\usepackage{hyperref}
\usepackage{array}
\usepackage{lastpage}
\usepackage{xcolor}
\usepackage{fancyhdr}
\usepackage{tikz}
\usepackage{background}
\usepackage{url}
%%\usepackage{showframe}
\usepackage{lipsum}
\usepackage{makecell}
\usepackage[export]{adjustbox}
\usepackage{graphbox}
\usepackage{booktabs}
\usepackage{multirow}
\usepackage{bigstrut}

\usetikzlibrary{calc}
\usetikzlibrary{positioning}

\usepackage{geometry}
\geometry{paper=a4paper}
%%odabir veličine papira
\geometry{bindingoffset=1.5cm,hmargin={1.5cm,1.5cm},vmargin={1cm,1cm}}
%%podešavanje margina
\geometry{includehead=true,headheight=3.5cm,headsep=1cm}
%%podešavanje headinga
\geometry{includefoot=false}
%%podešavanje footinga

\setlength{\parindent}{0.95cm}      %%paragraf uvodni razmak

\pagestyle{fancy}
\renewcommand{\headrulewidth}{0pt}  %%delete default header line

\newcommand{\thenextpage}{\number\numexpr\thepage+1\relax}

%%begin page borders
\SetBgOpacity{100.0}    %% Select opacity
\SetBgScale{1}          %% Select scale factor of logo
\SetBgAngle{0}          %% Select rotation of logo
\SetBgColor{black}      %% Select color
\SetBgContents{
\begin{tikzpicture}[overlay,remember picture]
\draw [line width=1pt,rounded corners=0pt]
($ (current page.north west) + (2.5cm,-1cm) $)
rectangle
($ (current page.south east) + (-1cm,1cm) $);

\draw [line width=1.5pt]
($ (current page.north west) + (2.5cm,-14.85cm) $) -- ($ (current page.north
west) + (1cm,-14.85cm) $);

\node[anchor=north] at ($(current page.north west)+(1.5cm,-1cm)$)
{\rotatebox{90}{\makecell[r]{\scriptsize\selectfont Reproduction or any use
not conformity with the intended\\

\scriptsize\selectfont application is not permissible.}}};
\node[anchor=north] at ($(current page.south west)+(1.5cm,1cm)$)
{\rotatebox{90}{\makecell[l]{\scriptsize\selectfont Nachdruck oder
Verwendung, die nicht der beabsichtigten\\

\scriptsize\selectfont Anwendung entspricht, ist nicht zulässig.}}};

\end{tikzpicture}
}
%%end page borders

%%begin firstpage footer
\fancypagestyle{firstpage}{%
\fancyhead[CE,CO,LE,LO,RE,RO]{} %% clear out all headers
\fancyfoot[CE,CO,LE,LO,RE,RO]{} %% clear out all footers
\fancyhf{}                      %% clear default for head and foot
\fancyfoot[C]{%
    \begin{tikzpicture}[remember picture,overlay]
    \node[anchor=south west,inner sep=0pt] at ($(current page.south west)+ (2.5cm,1cm)$) {
        \begin{tabular}{@{}p{5.45cm}@{}|@{}p{3.5cm}@{}|@{}p{6cm}@{}|@{}p{1.5cm}@{}@{}p{1cm}@{}}
        \hline
        \scriptsize Projekt:                                 & \scriptsize Vertrag Nr.:                             & \scriptsize Dokument Nr.:                            & \scriptsize Seite:                                   & \textbf{\thepage} \bigstrut\\
        \cline{4-5}    \centering\textbf{\footnotesize Project} &                                          & \centering\textbf{\footnotesize Document number}       & \scriptsize Nächste Seite:                           & \textbf{\footnotesize \thenextpage} \bigstrut\\
        \hline
        \scriptsize Titel:                                   & \scriptsize Format:                                  & \scriptsize Rahmen:                                  & \scriptsize Gesamte Seite:                              & \textbf{\footnotesize \pageref*{LastPage}} \bigstrut[t]\\
        \centering\textbf{\footnotesize Title} & \centering\textbf{\footnotesize Format}                              & \centering\textbf{\footnotesize 1:1}                             &                                          &  \bigstrut[b]\\
        \end{tabular}%
    };
\end{tikzpicture}
}
}
%%end firstpage footer

%%begin default header for all pages; except first page style
\fancyhead[CE,CO,LE,LO,RE,RO]{} %% clear out all headers
\fancyfoot[CE,CO,LE,LO,RE,RO]{} %% clear out all footers
\fancyhf{}                      %% clear default for head and foot
\fancyhead[C]{%
\begin{tikzpicture}[remember picture,overlay]
\node[anchor=north west,inner sep=0pt] at ($(current page.north west)+(2.5cm,-1cm)$) {
    \begin{tabular}{@{}p{4cm}@{}|@{}p{6.45cm}@{}|@{}p{6cm}@{}@{}p{1cm}@{}}
    \multirow{4}[6]{*}{\includegraphics[valign=m,scale=0.25]{\cenlogo.png}}                 & \scriptsize Projekt:                                 & \multicolumn{1}{l|}{\scriptsize Dokument Nr.:}       & \scriptsize Rev.: \bigstrut[t]\\
    & \centering\textbf{\footnotesize Project} & \multicolumn{1}{l|}{\textbf{\footnotesize Document number}} &  \textbf{\footnotesize A} \bigstrut[b]\\
    \cline{2-4}                                             & \scriptsize Titel:                                   & \scriptsize Seite:                                   & \textbf{\footnotesize \thepage} \bigstrut\\
    \cline{3-4}                                             & \centering\textbf{\footnotesize Title} & \scriptsize Seitenzahl:                              & \textbf{\footnotesize \pageref*{LastPage}} \bigstrut\\
    \hline
    \end{tabular}%
};
\end{tikzpicture}
}

%%end default header for all pages; except first page style

%%end preamble
\begin{document}
%%titlepage begin

\thispagestyle{firstpage}       %%\fancypagestyle{firstpage}

%%begin podešavanje margina, headinga i footinga za početnu stranicu
\newgeometry{bindingoffset=1.5cm,hmargin={1.5cm,1.5cm},vmargin={1cm,1cm},
            includehead=false,
            includefoot=true,footskip=2cm
}
%%end podešavanje margina, headinga i footinga za početnu stranicu

\vspace*{6cm}                   %%6cm vertical offset
\begin{center}
    \Huge Some random text\\
    \large Some random text\\~\\
    \Huge Some random text\\
    \large Some random text
\end{center}
\vspace*{\fill}                 %%fill page with empty space

%%titlepage end

\newpage
\restoregeometry                %%restore to default header for all pages; except first page style
\section{Section title}
\lipsum[1-8]

\newpage

\section{Section title}
\lipsum[1-8]

\newpage

\section{Section title}
\lipsum[1-8]

\end{document}

Thank you in advance!
Best regards


text:
Q: Pattern in regexp I have a pattern like:
string [number|number]

I want validate with RegExp in Java.
Case valid: "blablabla blabla blabla [12|1234]"
Any other would be invalid.
I don't realise how to do it.

A: You can try with following regex:
^[a-zA-Z ]+\[\d+\|\d+\]$


text:
Q: How to enforce constraints in mysql  > CREATE TABLE student(
-> student_id INT(2) NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> first_name VARCHAR(10),
-> last_name VARCHAR(10)
-> );

 > CREATE TABLE course(
-> course_id CHAR(5) NOT NULL PRIMARY KEY,
-> course_name VARCHAR(50),
-> student_id INT(2) NOT NULL,
-> CONSTRAINT student_student_id_fk
-> FOREIGN KEY (student_id)
-> REFERENCES student(student_id)
-> );

Thats how i created two tables namely student and course. Then i entered data in the student table. But when i enter some invalid data in the course table, it doesn't gives me any error.
For example:
       VALUES('A1','SUB 1',34);
gets the entry in the course table even if there is no primary key '34' in the student table.
Also, i can delete records in the student table, even if there is referential integrity.
So, how can enforce the constraints?

A: The easiest way to do this is to change your storage engine to InnoDB which supports the constraints.
For old MyISAM tables, you will have to use triggers on BOTH sides to enforce an FK relationship
Some links for self-help

*

*http://dev.mysql.com/tech-resources/articles/mysql-enforcing-foreign-keys.html

*http://forge.mysql.com/wiki/Triggers
Create your tables like this
 > CREATE TABLE student(
-> student_id INT(2) NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> first_name VARCHAR(10),
-> last_name VARCHAR(10)
-> ) ENGINE = INNODB;

 > CREATE TABLE course(
-> course_id CHAR(5) NOT NULL PRIMARY KEY,
-> course_name VARCHAR(50),
-> student_id INT(2) NOT NULL,
-> CONSTRAINT student_student_id_fk
-> FOREIGN KEY (student_id)
-> REFERENCES student(student_id)
-> ) ENGINE = INNODB;

A: For someone having the same problem, if you already created your table using MyISAM, you can change it to InnoDB using.
ALTER TABLE table_name ENGINE=InnoDB;


text:
Q: I should be able to undo my downvote if it the post was changed during the grace period
Possible Duplicate:
Why can't I change my vote if the  post has been edited during the initial 5mn grace period?

I downvoted this post when it only said

You can fire a submit with the help of javascript.

and the answer improved significantly after he edited it, and I want to undo my downvote.
Unfortunately there is no record of him editing it because he fixed it within the 5 minute grace period, and so it won't let me undo my downvote.
I'm going to edit his post just so I can undo the downvote, but I think this should be fixed.


text:
Q: How to reimplement accidents under Veins? I want to know how accidents are implemented under Veins 2.0 & in general (with the use of TraciMobility module) ?
I checked the last code version and seems that the mecanism behind accidents simulations is the same.
What i noted, responsible code is the following:
//in TraCIMobility::initialize() method

if (accidentCount > 0) {
        simtime_t accidentStart = par("accidentStart");
        startAccidentMsg = new cMessage("scheduledAccident");
        stopAccidentMsg = new cMessage("scheduledAccidentResolved");
        scheduleAt(simTime() + accidentStart, startAccidentMsg);
}

//in TraCIMobility::handleSelfMsg() method

if (msg == startAccidentMsg) {
        commandSetSpeed(0);
        simtime_t accidentDuration = par("accidentDuration");
        scheduleAt(simTime() + accidentDuration, stopAccidentMsg);
        accidentCount--;
}

So, if i understand correctly, this mecanism set only the current speed of vehicle to 0 but don't order it to stop moving and staying at the current position ?!
Suppose that i want to simulate accident by ordering vehicles to directly stop at their current positions ? how can i achieve it ? by using the stop Traci command ?
Thanks,

A: Setting a vehicle's speed via Command 0xc4 0x40 takes effect immediately and remains in effect until set to a different speed or reset (by passing a value of -1).
You can find more details in the SUMO documentation of its TraCI API.

A: Finally,
The implementation of accidents under Veins 2.0 (i guess that is the same for upper version) is as i sayed previously, by setting speed to 0 (with the use of Traci command/variable : Change Vehicle State(0xc4) /speed (0x40)).
If someone want to implement accidents in a differents manners, for exemple by stopping a car at position X under road Y, you have to reimplement accident by using Traci command/variable: Change Vehicle State(0xc4) /stop (0x12), this command takes as arguments position X and road Y.
Good luck,


text:
Q: EKEventStoreChangedNotification gets called several times I am using the EKEventStore in my app. I grab the default store and register for the EKEventStoreChangedNotification to be notified when changes are made to the calendar. However, when a change is made, the sender for the notification gets called several (5-10) times, sometimes with up to 15 seconds in between each call. This messes up my code and makes things much more difficult to work with. Is there anything I can do about this?
Thanks
iOS7 EDIT: It seems like as of the release of iOS7, this problem has disappeared. Now, regardless of the change made to the CalendarStore, only one EKEventStoreChangedNotification gets sent.

A: This is a result of exactly how the notifications are dispatched and what each is actually notifying about. In my experience, you can expect to receive at least one notification for a change to an item (event, reminder, etc.) and at least one more for the resultant change to the containing calendar for that item.
Without seeing your code and knowing what changes are being made, I can't be too specific about an answer; however, in general, you have two options.

*

*Observe the changes more closely - maybe you can safely ignore some notifications if they concern events that don't pertain to your app, or if you've already handled a change for a particular item.

*Coalesce multiple changes into a single batch of handler code. Basically, when you receive the notification, instead of kicking off your response right away, start a timer that will run the response in a second or two. Then, if another notification comes in before the timer fires, you can cancel the timer and reset it. This way, you can batch up multiple notifications that come in a short time window and only respond to them once (when the timer eventually fires).

The latter solution is my preferred answer, and might look something like (temporarily ignoring threading concerns):
@property (strong) NSTimer *handlerTimer;

- (void)handleNotification:(NSNotification *)note {
    // This is the function that gets called on EKEventStoreChangedNotifications
    [self.handlerTimer invalidate];
    self.handlerTimer = [NSTimer timerWithTimeInterval:2.0
                                                target:self
                                              selector:@selector(respond)
                                              userInfo:nil
                                               repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:self.handlerTimer
                              forMode:NSDefaultRunLoopMode];
}

- (void)respond {
    [self.handlerTimer invalidate];
    NSLog(@"Here's where you actually respond to the event changes");
}

A: I had this issue as well. After some debugging I realised that I was causing the additional EKEventStoreChangedNotification calls (for example, by creating or removing EKReminders). The EKEventStoreChangedNotification eventually gets triggered when I do an estore.commit().
I fixed this by declaring global variable like so:
// the estore.commit in another function causes a new EKEventStoreChangedNotification. In such cases I will set the ignoreEKEventStoreChangedNotification to true so that I DON'T trigger AGAIN some of the other actions.
var ignoreEKEventStoreChangedNotification = false

And then doing this in AppDelegate.swift where I listen to EKEventStoreChangedNotification:
nc.addObserver(forName: NSNotification.Name(rawValue: "EKEventStoreChangedNotification"), object: estore, queue: updateQueue) {
            notification in

        if ignoreEKEventStoreChangedNotification {
            ignoreEKEventStoreChangedNotification = false
            return
        }

        // Rest of your code here.

}

In the function where I make changes to the estore I do this:
//
// lots of changes to estore here...
//
ignoreEKEventStoreChangedNotification = true        // the estore.commit causes a new EKEventStoreChangedNotification because I made changes. Ignore this EKEventStoreChangedNotification - I know that changes happened, I caused them!
try estore.commit()

It's not pretty with the global variable (especially if you're into functional programming) but it works.


text:
Q: Problems setting div content alignment I want to add an info bar to a page. It contains three divs horizontally aligned and all content is currently floating left within them.
I'm trying to make the content of the center div align center and the right-hand div align to the right, but nothing I try seems to be working.
I've tried adding text-align:center to #delivery and text-align:right to #quickshop and I also tried float:right on #quickshop but they have no effect at all.
HTML/CSS:

#info-bar {
    height: 46px;
}
#container {
    margin: 0 auto;
    width: 82%;
}
.info {
    float: left;
    width: 37.5%;
    margin: 0;
    padding: 9px 0;
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
}
#quickquotes.info {
    width: 28.5%;
}
#quickshop.info {
    width: 34%;
}
#container i {
    font-size: 34px;
    color: #a6d120;
    display: inline-block;
    vertical-align: middle;
}

#container i:before {
    position: relative;
    top: 0px;
}
.icon-quote:before { content: url("http://placehold.it/35x27"); }
.icon-delivery:before { content: url("http://placehold.it/35x27"); }
.icon-quickshop:before { content: url("http://placehold.it/35x27"); }

#container .text-area {
    display: inline-block;
    text-align: left;
    margin-left: 0px;
    color: #1e3e57;
    letter-spacing: 0.07em;
    font-weight: bolder;
    text-transform: uppercase;
    font-size: 0.8em;
}

        Quick Quote Fast Response

        Free UK Delivery on Orders Over £100

        Quick Shop Search Product Codes

I've set up a fiddle here so you can see a real-world example of the problem: https://jsfiddle.net/qafru72o/2/
Where on earth am I going wrong here?

A: Remove text-align:left; from #container .text-area and then add justify-content to each individual div.

#info-bar{
    height: 46px;
}
#container{
    margin:0 auto;
    width:82%;
}
.info{
    float:left;
    width:37.5%;
    margin:0;
    padding: 9px 0;
    display:flex;
    flex-wrap: nowrap;
    align-items: center;
}
#quickquotes.info{
    width:28.5%;
    justify-content: flex-start;
}
#quickshop.info{
    width:34%;
    justify-content: flex-end;
}
#delivery.info{
    justify-content: center;
}
#container i {
    font-size: 34px;
    color: #a6d120;
    display: inline-block;
    vertical-align: middle;
}
#container i:before {
    position:relative;
    top:0px;
}
.icon-quote:before     {content: url("http://placehold.it/35x27");}
.icon-delivery:before  {content: url("http://placehold.it/35x27");}
.icon-quickshop:before {content: url("http://placehold.it/35x27");}

#container .text-area {
    display: inline-block;
    margin-left: 0px;
    color:#1e3e57;
    letter-spacing:0.07em;
    font-weight:bolder;
    text-transform:uppercase;
    font-size:0.8em;
}

        Quick Quote Fast Response

        Free UK Delivery on Orders Over £100

        Quick Shop Search Product Codes

is this what you need?


text:
Q: How can I compare two string values in SQL? The problem statement is as mentioned below:
When max_pos> 4 and max_neg is >1
then find out the name of rollercoaster
where intensity_level  is greater than  excitement_level.
Here, the intensity_level and excitement_level are string values like high, very high etc.  How can I compare them?

A: You could use CASE expression to map value for your intensity_level and excitement_level, then compare them
SELECT *
FROM table_name
WHERE
    max_pos> 4
    AND max_neg >1
    AND
    (
        CASE
            WHEN intensity_level = 'high' THEN 0
            WHEN intensity_level = 'very high' THEN 1
            WHEN intensity_level = 'ultra high' THEN 2
        END
        >
        CASE
            WHEN excitement_level = 'high' THEN 0
            WHEN excitement_level = 'very high' THEN 1
            WHEN excitement_level = 'ultra high' THEN 2
        END
    );

A: You can create a table that contains intensity_level and excitement_level for each rollercoaster as integers and an ID that links them to your main table

A: try using DECODE. DECODE high, very high values with a number and alias and then select all from this result set, then compare the aliases

A: Here My solution using the function
Just assign a integer value to the string and then compare the integer value.
CREATE function Weight(tag VARCHAR(200))
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE v INT;
IF tag='High' THEN
SET v=1;
END IF;
IF tag='Very High' THEN
SET v=2;
END IF;
RETURN v;
END;|

Then use the query
Select *
From tablename
Where max_pos> 4
AND max_neg is >1
AND Weight(intensity_level)>Weight(excitement_level);

The Weight function above maybe not work in SQL, I used MySQL so change accordingly.


text:
Q: The reason of starting a line with colon ":" in zsh_history file I'm using the zsh history plugin, which adds the timestamp of the command I entered. The raw file of the .zsh_history text file looks like below:
: 1582469132:0;jupyterlab
: 1582469132:0;jupyter notebook
: 1582469132:0;jupyterlab
: 1582469132:0;jupyter lab
: 1582469132:0;jupyter notebook
: 1582469132:0;ls

I just don't understand the reason for using this format that why every line item starts with a colon :?
I'm pretty sure this plugin is not the only one using this format. I've seen SWIFT messages using this format and some other file which I couldn't remember the name.

A: I'm not positive, but I believe the leading colon allows you to execute the history file as a script.
: is a do-nothing command: it ignores its arguments then completes with an exit status of 0. In this case, the argument is the string <timestamp>:0; the semicolon is a command terminator.
You can try it out at the prompt:
% : 1235:0;echo hello
hello

Thus, executing this file as a script would have the same affect as executing
jupyterlab
jupyter notebook
jupyterlab
jupyter lab
jupyter notebook
ls

It's unlikely you would want to execute an arbitrary history file as a script, but a file containing a specially crafted history could be useful.


text:
Q: Writing Wrapper for FileUpload in Spring boot : File not Present Use Case
I need to write a wrapper for a FileUpload API, which takes Files from UI, and upload those to remote API. What I have chalked out so far:
Made a Controller which takes File and Content body as Request part, then I try to upload them to remote API, code snippets follow:
Controller Endpoint
ResponseEntity uploadFiles(@RequestPart("files") MultipartFile[] files, @RequestPart("someData") Metadata fileMetadata)

File Upload Code
       byte[][] fileArray = Arrays.stream(files).map(multipartFile -> {
            try {
                return multipartFile.getBytes();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }).toArray(byte[][]::new);
        //add file
        LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        configuration.getDocumentCategory());
        params.add(DocStorageConstants.FILE, fileArray);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<FileUploadResponse> responseEntity = restTemplate.postForEntity(configuration.getUploadEndpoint(), requestEntity, FileUploadResponse.class);

The remote API returns response as if Files never reached this API, what I need to do to avoid this? I might try writing file to a temporary file and then upload that file to remote endpoint, not sure if that is a clean approach. Thanks in advance for any suggestions!
[Update]: The cURL that I am trying to form is below:
curl --location --request POST 'http://<host>:<port>/file-endpoint' \
--header 'X-Api-Client:<api-key>' \
--header 'x-service-id: <service-id>' \
--form 'file=@"/aggregate.csv"' \
--form 'uploadRequest="{\"bn\":\"NFA\",\"dc\":\"generalDocs\",
\"tags\":[\"test\", \"test2\"]
}"'

A: Following snippet worked
Arrays.stream(files).forEach(multipartFile -> params.add(DocStorageConstants.FILE, multipartFile.getResource()));


text:
Q: Geometric intuition/picture behind tensor product I am looking for a way to understand tensor product spaces intuitively. I understand both the basis-dependent and the algebraic basis-free definitions. What I am struggling with is interpreting what something of the form
$$v \otimes w, \quad v \in V, w \in W$$
means geometrically, where $V$ and $W$ are vector spaces.
For example, in $\mathbb{R}^3$ it is very easy to explain and visualize what any vector or basis looks like. For an arbitrary $x \in \mathbb{R}^3$ we can decompose it into
$$x = a_1 e_1 + a_2 e_2 + a_3e_3$$
and this geometrically makes clear sense, we are simply breaking down the vector into its component parts. In other words, if $x$ denotes the position of some particle we can say it is $a_i$ distance in the $i$th direction ($e_i)$.
However, in the case of tensor products, does a similar geometric interpretation hold? How does one exactly interpret an arbitrary vector $v \otimes w$? To make the question simpler, take $V = \mathbb{R}^2$ (with basis $\{e_i^1\}$) and $W = \mathbb{R}^3$ (with basis $\{e_i^2\})$. Then
$$\begin{align}v \otimes w = &a_1 e^1_1\otimes e_1^2 + a_2 e^1_2\otimes e_1^2 + a_3 e^1_1\otimes e_2^2 + \\&a_4 e^1_2\otimes e_2^2 + a_5 e^1_1\otimes e_3^2 + a_6 e^1_2\otimes e_3^2 \end{align}$$
The only picture I am able to have in mind is in the context of quantum mechanics. If the two vector spaces represent different observable quantities, then I interpret the tensor product as taking into account two things at once. But this is unsatisfying to me in the general mathematical setting, especially geometrically. Does such an interpretation even exist?


text:
Q: Highlight inserted,deleted elements/text - Python Docx I want to highlight the text or elements which are inserted or deleted, after combine the two version of the Docx file.
Here there are just returning the the values. I tried following code. It is highlighting full paragraph.
def get_accepted_text(p):
    xml = p._t.xml
    if "w:del" in xml or "w:ins" in xml:
        for run in p.runs:
            run.font.highlight_color = WD_COLOR_INDEX.PINK

But I need, highlight the text.
Note: Here there are returning the the values

A: at line for run in p.runs: you're setting highlight for all runs which is not something you want. the snippet below finds all runs (including the tracked ones) and checks if they are contained within the tracking containers w:ins and w:del. Once you find these, it's easy to apply custom formatting on the list of changed runs.
import docx
from docx.text.run import Run
from docx.enum.text import WD_COLOR_INDEX

doc = docx.Document('t1.docx')
ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"

def iter_changed_runs(doc):
    for p in doc.paragraphs:
        for r in p._p.xpath(f'//w:r'):
            parent = r.getparent()
            if parent.tag in (f'{ns}ins', f'{ns}del'):
                yield Run(r, p)

delta_runs = list(iter_changed_runs(doc))

# change color
for r in delta_runs:
    r.font.highlight_color =  WD_COLOR_INDEX.YELLOW
doc.save('t2.docx')

this is the screenshot of the t2.docx generated from the initial text of the document t1.docx written without using the tracking function and then modified with the track changes turned on.


text:
Q: Installing openssh on centos I am trying to install sshpass on centos, as I want to install MapR on our systems.
I am following guidelines given here:
http://doc.mapr.com/display/MapR/Quick+Installation+Guide
I get following issue:
sudo yum install sshpass
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
 * base: centos.excellmedia.net
 * extras: centos.excellmedia.net
 * updates: centos.excellmedia.net
Setting up Install Process
No package sshpass available.
Error: Nothing to do

If somebody can help me to understand where to get sshpass from it will be great.
Thanks in advance

A: The package that contains the openssh server on CentOS as far as I know is not called sshpass but openssh-server so run
 yum install openssh-server

A: The better way would be to setup the ssh keys for passwordless login. Setup the private and public keys and copy them over to the other nodes. See this tutorial SSH Passwordless Login Using SSH Keygen in 5 Easy Steps

A: BTW sshpass is available in epel repos by that name itself. You should probably add the epel repo to your yum configuration.
[root@rh-1 ~]# yum whatprovides */sshpass
Loaded plugins: product-id, security, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
centos                                                                                | 3.7 kB     00:00
epel/metalink                                                                                | 8.4 kB     00:00
epel                                                                                | 4.4 kB     00:00
epel/primary_db                                                                                | 6.3 MB     00:03
maprecosystem                                                                                |  951 B     00:00
maprecosystem/primary                                                                                |  12 kB     00:00
maprecosystem                                                                                74/74
maprtech                                                                                |  951 B     00:00
centos/filelists_db                                                                                | 5.9 MB     00:15
epel/filelists_db                                                                                | 9.0 MB     00:07
maprecosystem/filelists                                                                                | 333 kB     00:00
maprtech/filelists                                                                                |  16 kB     00:00
sshpass-1.05-1.el6.x86_64 : Non-interactive SSH authentication utility
Repo        : epel
Matched from:
Filename    : /usr/bin/sshpass

A: Don't find sshpass package in default Centos repositories. You must be installed epel-release repository then install sshpass package.
For installing epel-release on your centos run below command.
yum install epel-release


text:
Q: automated backup issue with directory I run my own backup class. In it I have a maintenance function that checks if the user is an admin, checks if the user is on the homepage, then scans the backup dir to see if the site has not been backed up in a day by checking the file created timestamp. If the condition exists where the files, or lack thereof are over a day old, it initiates a backup and notifies the user.
This was working fine before I ported it to a class (not sure if I messed anything up along the way). For debugging purposes I added a few echos .etc.
The problem is that the maintenance script does not do anything if the dir is empty (meaning there needs to be a backup or if $latest_filename is not set). All my debugging has led me to believe that the latter variable is always evaluating to set even if the dir is empty.
    if ($frontpage && checkAdmin()) {
        $path = $this->dir_sql;
        $latest_ctime = 0;
        $latest_filename = '';
        $d = dir($path);
        while (false !== ($entry = $d->read())) {
            $filepath = "{$path}/{$entry}";
            // could do also other checks than just checking whether the entry is a file
            if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
                $latest_ctime = filectime($filepath);
                $latest_filename = $entry;
                echo $latest_filename;
                echo $latest_ctime;
            }
        }
        // check if latest backup is over a day old
        // if it is create a new backup and run the regular
        // maintenance scripts below
        if (is_file($latest_filename) && date('d', filectime($latest_filename)) == date('d')) {
            self::doBackup();
        } elseif(!isset($latest_filename)) {
            self::doBackup();
        }
    }

Edit/update:
I just added
if (isDirEmpty($this->dir_sql)) {
                self::doBackup();
            }

before the if, and removed the elseif at the bottom, which did the trick, but still weird.

A: Please read the documentation regarding isset:
It's purpose is to check if the variable set or not. Not to see whether the file is exists or not.

Determine if a variable is set and is not NULL.

This is why your code doesn't work. Because, your $latest_filename variable is always SET because you already set it initially, by using this code: $latest_filename = '';


text:
Q: How to download image from Python CGI I want to download image from Python CGI.
For example, I post img's base64 to CGI, and CGI output image.
I write this code.
Please advise me.
Python cgi side code
import cgi
import base64

query = cgi.FieldStorage()
img_list = query.getvalue("image").split(',')
contentType = img_list[0] #data:image/jpeg;base64
base_64 = img_list[1]

print("Content-type: image/jpeg")
print(base64.b64decode(base_64))

A: Have a try:
print("Content-Type: application/octet-stream")

This means that it is raw bytes and can not be interpreted as anything useful by the browser.
The browser should then open a download dialog.


text:
Q: Javassist: To replace a statement in a function Using javassist, I was able to change the entire method content by using setBody().
Is there a way to just replace just a statement in the method instead.
Please find the code below:
ctClass.instrument(new ExprEditor() {
        @Override
        public void edit(FieldAccess fieldAccess)
                throws CannotCompileException {
            //System.out.println(fieldAccess.getFieldName());
        if (fieldAccess.getFieldName().equals("out")) {

            fieldAccess.replace(" { System.out.println(\"Manipulating.. \"); $_ = $proceed($$); } ");
            }
        }
    }

My intent is to "replace" a System.out.println(" "); in the main java program dynamically.
When I try to do this(above method), I see that this approach just adds a line to the beginning of the method, just before the System.out.println it was supposed to replace. The previous System.out.printlnstatement still exists in my code.
Am I doing something wrong here? It would be great if I could get some pointers.


text:
Q: SharePoint 2010 Expand recurrences CAML Query exceeding list view threshold Trying to get event items from a list, I issue a CAML query that only returns a small number of items (about 17). When I set the List View Threshold at 10000 everything works fine, but when I set the LVT at 5000, I get a "Exceeded List View Threshold set by the administrator" error.
My CAML query is pretty simple:
<Where>
<And>
    <DateRangesOverlap>
        <FieldRef Name="EventDate" />
        <FieldRef Name="EndDate" />
        <FieldRef Name="RecurrenceID" />
        <Value Type="DateTime">
            <Now />
        </Value>
    </DateRangesOverlap>
    <And>
        <BeginsWith>
            <FieldRef Name="Place" />
            <Value Type="Text">Boston</Value>
        </BeginsWith>
        <Or>
            <Eq>
                <FieldRef Name="Status" />
                <Value Type="Text">Status1</Value>
            </Eq>
            <Eq>
                <FieldRef Name="Status" />
                <Value Type="Text">Status2</Value>
            </Eq>
        </Or>
    </And>
</And>

Can anyone explain why this may be happening? Is is because when expanding recurrences SP actually runs a separate query that result in the LVT being exceeded? Any suggestions to restructure the query would be great, but I do need to look at all occurrences of recurring events (not just the master items).

A: In case anyone is interested, I've managed to play around with the Query and find out how to avoid hitting the threshold.
What I did was simply change the order of the query elements so that my indexed fields were listed first and the DateRangesOverlap node was listed last. Here is the result that works:
    <Where>
<And>
    <BeginsWith>
        <FieldRef Name="Place" />
        <Value Type="Text">Boston</Value>
    </BeginsWith>
    <And>
        <Or>
            <Eq>
                <FieldRef Name="Status" />
                <Value Type="Text">Status1</Value>
            </Eq>
            <Eq>
                <FieldRef Name="Status" />
                <Value Type="Text">Status2</Value>
            </Eq>
        </Or>
        <DateRangesOverlap>
            <FieldRef Name="EventDate" />
            <FieldRef Name="EndDate" />
            <FieldRef Name="RecurrenceID" />
            <Value Type="DateTime">
                <Now />
            </Value>
        </DateRangesOverlap>
    </And>
</And>
</Where>


text:
Q: problem with resizing partition I', trying to resize my partition to the maximum space available, I tried different tools and got the same result.
The latest one is growpart.
The problem is that all the process seems to work, and the partition size is changed, however when I type df -h, I get the following result:
Filesystem      Size  Used Avail Use% Mounted on
/dev/mmcblk0p2  3.1G  1.2G  1.9G  39% /
devtmpfs        360M     0  360M   0% /dev
tmpfs           489M     0  489M   0% /dev/shm
tmpfs           489M   20M  470M   4% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           489M     0  489M   0% /sys/fs/cgroup
/dev/mmcblk0p1   40M   16M   25M  40% /boot
tmpfs            98M     0   98M   0% /run/user/1000
tmpfs            98M     0   98M   0% /run/user/0

and when I type fdisk -l i get the following:
Disk /dev/mmcblk0: 7.4 GiB, 7948206080 bytes, 15523840 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x66dc81bc

Device         Boot  Start      End  Sectors  Size Id Type
/dev/mmcblk0p1       49152   131071    81920   40M 83 Linux
/dev/mmcblk0p2      131072 15523806 15392735  7.3G 83 Linux

the growpart command result is:
CHANGED: partition=2 start=131072 old: size=7486114 end=7617186 new: size=15392735,end=15523807

of course, I did a reboot, and still didn't help.
any idea what's going wrong?
I'm stuck for 4 days in this part.
P.S. this process must be done in a script for our product porpuses.
Thanks for the helpers

A: Did you resize the filesystem? I don't think command line partitioning tools do this step automatically.
To resize a the filesystem to fill the partition:
resize2fs /dev/YOUR_DEVICE

A: It is impossible to resize a mounted partition. You will have to boot from a LiveUSB or LiveCD, not from the disk you're trying to resize.
Search the Internet for "Gparted Live", ( https://gparted.org/livecd.php ) and you'll find a distribution for your hardware. Using gparted to move/resize partitions takes care of the resiz2fs. I have successfully resized partitions on two systems with gparted.


text:
Q: How to "derive" and interpret this data generating process for a high-dimensional VEC Model? I am currently trying to understand the following paper by Smeekes & Wijler (2021) who are proposing an automated estimation procedure for models with a large number of potentially cointegrated variables.
I would say I have graduate level textbook knowledge on VAR models and VEC representations. However, I do not fully understand why they specify their data generation process the following way:
Let $z_t = (y_t,x_t')$ be described by:
$$z_t=\mu + \tau t + \zeta_t$$
with the stochastic component given by:
$$\Delta \zeta_t = AB'\zeta_{t-1}+\sum_{j=1}^{p}\Phi_j \Delta \zeta_{t-j} + \epsilon_t$$
The model can be rewritten into a VECM form by substituting the first equation into the second:
$$\Delta z_t= AB'(z_{t-1}-\mu -\tau (t-1))+\tau^*+\sum_{j=1}^{p}\Phi_j \Delta z_{t-j} + \epsilon_t$$
where $\tau^* = (I-\sum_{j=1}^{p}\Phi_j)\tau$
Now, my main problem is basically the understanding and interpretation of equation 1 and its link to equation 2 as I have never seen such a representation. To be more specific, it obviously does not look like a VAR, I do not understand why index t appears to be a variable in this model and lastly, why equation 2 (which is actually the standard VEC representation I used to know) is dependent on this "stochastic component" zeta.
I already did my own textbook research, including Hamilton, but could not find any satisfying answer yet. I would also be happy about any literature hints.
Thanks in advance!


text:
Q: Post to friends wall using iOS Facebook SDK
Possible Duplicate:
Facebook API: Post on friend wall

I'm trying to post the message on a friends wall. But it doesn't work with my below code,
 NSMutableDictionary* params = [NSMutableDictionary dictionary];
 [params setObject:@"Some text" forKey:@"user_message_prompt"];
 [params setObject:@"another text" forKey:@"action_links"];

 [facebook requestWithGraphPath:@"****FB ID here *****/feed" andParams:params andHttpMethod:@"POST" andDelegate:self];

I tried many ways to figure it out, but couldn't find the solution. Please let me know what I did wrong in my code. I need a quick help to resolve.

A: This is how I push messages to a friends Facebook wall:
In your .h file:
#import "FBConnect.h"
#import "FBRequest.h"
#import "FBLoginButton.h"

....

Facebook* _facebook;
NSArray* _permissions;

...

@property (readonly) Facebook *facebook;

In your .m file:
@synthesize facebook = _facebook;

In viewDidLoad:
_permissions =  [[NSArray arrayWithObjects:@"user_photos",@"user_videos",@"publish_stream",@"offline_access",@"user_checkins",@"friends_checkins",@"email",@"user_location" , @"read_stream", @"read_friendlist",nil] retain];
_facebook = [[Facebook alloc] initWithAppId:kAppId];

SBJSON *jsonWriter = [[SBJSON new] autorelease];
static NSString* kAppId = @"your app key";

NSDictionary* actionLinks = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"your title",@"text",@"http://itunes.apple.com/us/app/facts!/id434894484?l=de&ls=1&mt=8",@"href", nil], nil];

NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];
NSDictionary* attachment = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @"Title of the post", @"name",
                                    @"Caption of the post", @"caption",
                                    @"Some description", @"description",
                                    nil];

NSString *attachmentStr = [jsonWriter stringWithObject:attachment];

NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       kAppId, @"api_key",
                                       @"Share on Facebook",  @"user_message_prompt",
                                       actionLinksStr, @"action_links",
                                       attachmentStr, @"attachment",
                                       @"your friends id", @"to",
                                       nil];

[_facebook dialog: @"stream.publish" andParams:params andDelegate:self];

One thing has to be clear. You can only post to a friends wall when he is really in your friendlist, otherwise it will not work. I tested the code on my profile and it works!


text:
Q: How to exclusively style parent or child when hovering over either of them? I have some very simple HTML that looks like

    Child

I want to style the parent when hovering over the parent and I want to style the child when hovering over the child. I never want both to be styled at the same time.
I tried various combinations of :hover and :not() selectors in SCSS. Googling didn't bring me far; most solutions I found just tell me how to style the parent when hovering over the child, which is the opposite of what I want.
I found this and this workaround, both from 2013, but I was wondering whether there is a better, more modern way to do this.

A: If you only intend to support modern, evergreen browsers that support :has, then you can style #parent based on the following conditions:

*

*is hovered

*does not have a hovered child

That translates to a selector of such: #parent:hover:not(:has(#child:hover)).
In the example below, the #parent is red only when it is hovered and not its child:

#parent:hover:not(:has(#child:hover)) {
  background: red;
}

#child:hover {
  background: green;
}

  Child


text:
Q: Build a digital elevation model (DEM) while controlling number of mountains and their proximity My goal is to get a 2d-array (i.e. a matrix) of floats which can be visualized as a digital elevation model (i.e. a contour plot) with smooth contours as shown on the figure below provided that I am able to control how many white mountains are generated and their distance to each other every time I run the script.
The white mountains represent the clusters of cells in the CSV file containing values greater than 0.9 as shown on the color scale.  On the figure we see two mountains divided by areas with values lower than 0.9.

Here is my full code with detailed comments where I use convolutional filters to create such an image:
import numpy as np
import pandas as pd
from scipy import signal
import plotly
import plotly.graph_objs as go

def rndmtx():
    """Generate random 2d-array as a digital elevation model."""

    nx = 100
    ny = 100
    dem1 = np.random.rand(nx, ny)
    # Save array to csv file befor Gaussian filter.
    # Comment the next two lines if reading from the csv file.
    dafr = pd.DataFrame(dem1)
    dafr.to_csv('G_dem1.csv', header=False, index=False)

    # Uncomment the next two lines to read from csv file.
    # dafr = pd.read_csv('G_dem1.csv', header=None)
    # dem1 = dafr.values

    # Apply the first Gaussian filter.
    sizex = 5  # The less sizex and sizey the more highlands.
    sizey = 5  # The more sizex and sizey the more water.
    x, y = np.mgrid[-sizex:sizex+1, -sizey:sizey+1]
    scale = 0.33  # The more scale the bigger the difference in elevation.
    g = np.exp(-scale*(x**2/sizex+y**2/sizey))
    filter1 = g/g.sum()  # Normalise the Gaussian function.

    dem_smooth = signal.convolve(dem1, filter1, mode='valid')
    # Rescale so it lies between 0 and 1.
    dem_smooth = ((dem_smooth - dem_smooth.min())
                  / (dem_smooth.max() - dem_smooth.min()))

    # Apply the second Gaussian filter to make the boundaries smoother.
    sizex = 5
    sizey = 5
    x, y = np.mgrid[-sizex:sizex+1, -sizey:sizey+1]
    g = np.exp(-0.33*(x**2/sizex+y**2/sizey))
    filter2 = g/g.sum()

    dem_smooth1 = signal.convolve(dem_smooth, filter2, mode='valid')
    dem_smooth1 = ((dem_smooth1 - dem_smooth1.min())
                   / (dem_smooth1.max() - dem_smooth1.min()))

    return dem_smooth1

# Get the raw random array of the digital elevation model
#   and assign it to the variable.
contour_xy = rndmtx()

# Save the array into CSV file in the working directory.
df = pd.DataFrame(contour_xy)
df.to_csv('last_data.csv', header=False, index=False)

data = [
    go.Contour(
        z=contour_xy,
        colorscale=[
            [0, 'rgb(0, 161, 233)'], [0.28, 'rgb(0, 161, 233)'],
            [0.28, 'rgb(29, 210, 108)'], [0.50, 'rgb(29, 210, 108)'],
            [0.50, 'rgb(141, 232, 130)'], [0.65, 'rgb(141, 232, 130)'],
            [0.65, 'rgb(254, 254, 152)'], [0.75, 'rgb(254, 254, 152)'],
            [0.75, 'rgb(192, 182, 122)'], [0.82, 'rgb(192, 182, 122)'],
            [0.82, 'rgb(142, 110, 92)'], [0.88, 'rgb(142, 110, 92)'],
            [0.88, 'rgb(171, 147, 142)'], [0.93, 'rgb(171, 147, 142)'],
            [0.93, 'rgb(227, 219, 217)'], [0.97, 'rgb(227, 219, 217)'],
            [0.97, 'rgb(255, 255, 255)'], [1, 'rgb(255, 255, 255)']
        ],
    ),
]

layout = go.Layout(
    yaxis=dict(
        autorange='reversed'
    )
)

figure = go.Figure(data=data, layout=layout)
plotly.offline.plot(figure, filename='dem.html')

Every time I run the script I get a unique random array of numbers.
How to control over the number and proximity of white mountains to be generated?
For example, now I want 10 white mountains to be placed on the plot, then I want only 2 mountains, and so on.
Currently, I use a Brute Force algorithm that eventually build the plot with the desired number of mountains, but I am not able to set specific coordinates of mountains to control the distance between them.
Generous answers and pointing out the right direction are highly appreciated. Enjoy playing with the code!

A: One of the clunky solutions is to populate some clusters of cells in the CSV file before Gaussian filters by values higher than 0.9, for example, all ones, as shown on the figure below.
This is just a CSV file opened in Excel with applied Color Scale feature. On the left is the random matrix. On the right you can see that I try to set four mountains of equal size 6x4 cells, all containing a value "1".

After applying convolutional filters, I get the following result:

which is not good because I got only two mountains and two brown highlands. In addition, there are a lot of water. I want as less water as possible.
I do not mind rewriting the script from scratch if you can point out other techniques.
UPDATE
Thanks to the community, I finally came to a stable solution:
build Scatter plot, then convert it into the Contour.
See question Convert Scatter to Contour, every dot turns into a highland


text:
Q: jQuery Accordion Tab - Link to site, not page content I've currently have 5 tabs on my jQuery Accordion.  Clicking on them causes the content to appear like one would expect.  However I would also like to include links to external site.  To keep the style the same I would like to have them look like the accordion as well.  I could have the content contain a link saying click here, but I would rather have it just be an external link.  I was able to use the UI Widget and add the style from the accordion to make it match, however I have encountered two issues.  The first is that the UI-Widget tab doesn't do the mouse over effect like the accordion tabs.  The second is that the text in the UI-Widget tab will not align with the other tabs (also looking at it being the same when text size is increased in the browser.)

Apple

A: One way would be to attach a separate click event to the link element:
$("#linkId").click(function() {
    window.location.href = "http://apple.com/";
});

This way, the rest of the functionality stays the same and you get an external link. See jsFiddle for more.
UPDATE
If you don't want the default accordion behavior for this link, you can turn off all other click events that can affect it. Something like:
$("#linkId").parentsUntil("#accordion").off("click");

See jsFiddle.


text:
Q: Semisimple regular elements of the Lie algebra $\mathfrak{sl}_n(\mathbb{C})$ I want to prove that the semisimple regular elements of $\mathfrak{sl}_n(\mathbb{C})$ are the traceless elements with $n$ distinct eigenvalues.
Here, I take 'regular' to mean that $\dim Z_\mathfrak{g}(x) = \operatorname{rk} \mathfrak{g}$.
In one direction, $n$ distinct eigenvalues implies $x$ is semisimple and thus so too is $\operatorname{ad}_x$, and it also necessarily implies that the geometric multiplicity of 0 for $x$ is as small as possible, i.e. $x$ is regular.
In the other direction, I am lost.
The wikipedia entry deals with regular elements of Lie groups, not Lie algebras, as indicated by the phrase

However if there are equal eigenvalues, then the centralizer is the product of the general linear groups of the eigenspaces of $M$, and has strictly larger dimension, so that $M$ is not regular.

This is not true for the centraliser $Z_\mathfrak{g}(x) = \{ y \in \mathfrak{g} : \operatorname{ad}_x(y) = 0\}$: the centraliser has no relation (as far as I can tell) to the eigenspaces of $x$ itself.
Where am I going wrong?

A: A semisimple element $x$ in $\mathfrak{sl}_n(\mathbb C)$ is of the form $x=G x' G^{-1}$ for some $G\in{\rm GL}_n(\mathbb C)$ and $x'=diag(\lambda_1,...,\lambda_n)$. The centralizer of $x$ is the set of matrices $y\in\mathfrak{sl}_n(\mathbb C)$ with $[x,y]=0$, i.e. writing $y=G y' G^{-1}$, $[x',y']=0$. The matrix entries of this equation are
$$
[x',y']_{ij}=y'_{ij}(\lambda_i-\lambda_j)=0.
$$
Thus the element is regular (meaning that the centralizer has dimension $n-1=rank(\mathfrak{sl}_n(\mathbb C))$) if and only if the $\lambda_i$'s are all distinct (otherwise the centralizer is larger).


text:
Q: Get number of occurrences of certain attribute in a related table in an aggregation in django I'm creating an extensible analytics app for django, the idea is to have a table with the events you wish to track and a table that connects events, to a certain date and a certain user.
Here is my main model:
class Events_Tracked(models.Model):
    data_point = models.ForeignKey('Data_Points', related_name='data_point')
    event_date = models.DateTimeField(default=datetime.datetime.now())
    user = models.ForeignKey('Users', related_name= 'user_tracked')

My problem now is to create a django query that can group the events tracked by month, and return the number of tracked events (rows) where data_point__id is the id I specify.
Preety sure I could do:
Events_Tracked.objects.values('event_date__month').annotate(Count('data_point')).filter(data_point__id=1)

But that would be limited to the count of a single data point, I need a query that can return a count row for each of the data points I want to track.
EDIT: Another very important query I need to build is for each month, get the number of users who had events tracked, whose data_point id is in a list of id's.


text:
Q: how to get some text when using svg tags How can i get some text between svg tags?
I am using this piece of code and i want some text inside the blue area:

Here should be some text
<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
<path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke:  none; fill:#05aed9;"></path>
</svg>

And here is my fiddle: https://jsfiddle.net/ucLkwh65/1/

A: If you add a HTML tag within the container then you can set the positioning to absolute and display the text:

Lorem Ipsum Dolor Sit

<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
    <path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke: none; fill:#05aed9;"></path>
  </svg>

Then add the CSS:
.innertext {
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
}

This will create the following effect:

svg {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
}
svg.one {
  padding-top: 20px;
}
.container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  vertical-align: middle;
  overflow: hidden;
}
.innertext {
  position: absolute;
  z-index: 1;
  left: 0;
  top: 0;
}
body {
   margin: 0;
    padding: 0;
    border: 0;
  }

  <svg class="one" viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:#1e90ff;"></path>
  </svg>

Lorem Ipsum Dolor Sit

<svg viewBox="1 1 500 500" preserveAspectRatio="yMinYMin meet">
    <path d="M0,100 C150,200 350,1 500,100 L500,00 L0,1 Z" style="stroke: none; fill:#05aed9;"></path>
  </svg>


text:
Q: Query to find all the empty tables in db2 DECLARE @sql NVARCHAR(MAX)
SELECT @sql = ISNULL(@sql + 'UNION ALL', '') + '
SELECT ''' + TABLE_SCHEMA + '.' + TABLE_NAME + '.' + COLUMN_NAME + ''' AS col FROM ' + TABLE_SCHEMA + '.' + TABLE_NAME + ' HAVING COUNT(' + COLUMN_NAME + ') = 0
'
FROM INFORMATION_SCHEMA.COLUMNS
EXEC (@SQL)
The above code works well in sql Server but doesnt work in db2. can somebody help me in this

A: I'm going to take a guess and say that your declaration is wrong. It's hard to say for sure without more info in the question but your declaration should probably look like so:
DECLARE @sql VARIABLE NVARCHAR(MAX)


text:
Q: Why does reading from Hive fail with "java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found"? I use Spark v1.6.1 and Hive v1.2.x with Python v2.7
For Hive, I have some tables (ORC files) stored in HDFS and some stored in S3. If we are trying to join 2 tables, where one is in HDFS and the other is in S3, a java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found is thrown.
For example this works when querying against a HIVE table in HDFS.
df1 = sqlContext.sql('select * from hdfs_db.tbl1')

This works when querying against a HIVE table in S3.
df2 = sqlContext.sql('select * from s3_db.tbl2')

This code below throws the above RuntimeException.
sql = """
select *
from hdfs_db.tbl1 a
 join s3_db.tbl2 b on a.id = b.id
"""
df3 = sqlContext.sql(sql)

We are migrating from HDFS to S3, and so that's why there is a difference of storage backing HIVE tables (basically, ORC files in HDFS and S3). One interesting thing is that if we use DBeaver or the beeline clients to connect to Hive and issue the joined query, it works. I can also use sqlalchemy to issue the joined query and get result. This problem only shows on Spark's sqlContext.
More information on execution and environment: This code is executed in Jupyter notebook on an edge node (that already has spark, hadoop, hive, tez, etc... setup/configured). The Python environment is managed by conda for Python v2.7. Jupyter is started with pyspark as follows.
IPYTHON_OPTS="notebook --port 7005 --notebook-dir='~/' --ip='*' --no-browser" \
 pyspark \
 --queue default \
 --master yarn-client

When I go to the Spark Application UI under Environment, the following Classpath Entries has the following.

*

*/usr/hdp/2.4.2.0-258/spark/lib/datanucleus-api-jdo-3.2.6.jar

*/usr/hdp/2.4.2.0-258/spark/lib/datanucleus-core-3.2.10.jar

*/usr/hdp/2.4.2.0-258/spark/lib/datanucleus-rdbms-3.2.9.jar

*/usr/hdp/2.4.2.0-258/spark/lib/spark-assembly-1.6.1.2.4.2.0-258-hadoop2.7.1.2.4.2.0-258.jar

*/usr/hdp/current/hadoop-client/conf/

*/usr/hdp/current/spark-historyserver/conf/

The sun.boot.class.path has the following value: /usr/jdk64/jdk1.8.0_60/jre/lib/resources.jar:/usr/jdk64/jdk1.8.0_60/jre/lib/rt.jar:/usr/jdk64/jdk1.8.0_60/jre/lib/sunrsasign.jar:/usr/jdk64/jdk1.8.0_60/jre/lib/jsse.jar:/usr/jdk64/jdk1.8.0_60/jre/lib/jce.jar:/usr/jdk64/jdk1.8.0_60/jre/lib/charsets.jar:/usr/jdk64/jdk1.8.0_60/jre/lib/jfr.jar:/usr/jdk64/jdk1.8.0_60/jre/classes.
The spark.executorEnv.PYTHONPATH has the following value: /usr/hdp/2.4.2.0-258/spark/python/lib/py4j-0.9-src.zip:/usr/hdp/2.4.2.0-258/spark/python/:<CPS>{{PWD}}/pyspark.zip<CPS>{{PWD}}/py4j-0.9-src.zip.
The Hadoop distribution is via CDH: Hadoop 2.7.1.2.4.2.0-258

A: Quoting the Steve Loughran (who given his track record in Spark development seems to be the source of truth about the topic of accessing S3 file systems) from SPARK-15965 No FileSystem for scheme: s3n or s3a spark-2.0.0 and spark-1.6.1:

This is being fixed with tests in my work in SPARK-7481; the manual
workaround is
Spark 1.6+
This needs my patch a rebuild of spark assembly. However, once that patch is in, trying to use the assembly without the AWS JARs will stop spark from starting —unless you move up to Hadoop 2.7.3

There are also some other sources where you can find workarounds:

*

*https://issues.apache.org/jira/browse/SPARK-7442

*https://community.mapr.com/thread/9635

*How to access s3a:// files from Apache Spark?

*https://community.hortonworks.com/articles/36339/spark-s3a-filesystem-client-from-hdp-to-access-s3.html

*https://community.hortonworks.com/articles/25523/hdp-240-and-spark-160-connecting-to-aws-s3-buckets.html
I've got no environment (and experience) to give the above a shot so after you give the above a try please report back to have a better understanding of the current situation regarding S3 support in Spark. Thanks.