text:
Q: Open WPF form when clicking WPF hyperlink I want to open a new WPF form when I click in a WPF hyperlink. I've seen a lot of examples that only opens web url, but I want to open a new WPF form.

A: You could just handle the click event:
<Hyperlink Click="Hyperlink_Click">Link</Hyperlink>

private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
    Dialogue diag = new Dialogue();
    diag.Show();
}

You could also go crazy with XAML:
<Hyperlink>
    <Hyperlink.Style>
        <Style TargetType="{x:Type Hyperlink}">
            <Style.Triggers>
                <EventTrigger RoutedEvent="Hyperlink.Click">
                    <BeginStoryboard>
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility">
                                <Storyboard.Target>
                                    <local:Dialogue />
                                </Storyboard.Target>
                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}"/>
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </Hyperlink.Style>
    <Hyperlink.Inlines>
        <Run Text="Open Dialogue"/>
    </Hyperlink.Inlines>
</Hyperlink>

This however is very problematic since once the dialogue is closed it cannot be reopened, that means when you click the hypelink again an exception will be thrown.

Using interactivity you could do this without such problems (needs a reference to the Blend SDK though):
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

<Hyperlink>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <t:CreateDialogAction Type="{x:Type local:Dialogue}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <Hyperlink.Inlines>
        <Run Text="Open Dialogue"/>
    </Hyperlink.Inlines>
</Hyperlink>

The action for this:
public class CreateDialogAction : TriggerAction<Hyperlink>
{
    public Type Type { get; set; }

    protected override void Invoke(object parameter)
    {
        if (Type != null && Type.IsSubclassOf(typeof(Window)) && Type.GetConstructor(Type.EmptyTypes) != null)
        {
            Window window = Type.GetConstructor(Type.EmptyTypes).Invoke(null) as Window;
            window.Show();
        }
    }
}

A: And using MVVM you can do in your View
<Hyperlink NavigateUri="{Binding MyUri}"
           Command="{Binding OpenHyperlinkCommand}">Link text
</Hyperlink>

and in your ViewModel
private ICommand _openHyperlinkCommand;
public ICommand OpenHyperlinkCommand {
    get
    {
        if (_openHyperlinkCommand == null)
            _openHyperlinkCommand = new RelayCommand<object>(p => ExecuteHyperlink());
        return _openHyperlinkCommand;
    }
}

private void ExecuteHyperlink() {
    //do stuff here
}

A: You can achive this like this:
<Label Height="25" Margin="26,27,116,0" Name="label1" VerticalAlignment="Top">
    <Hyperlink Click="Hyperlink_Click">Click Me</Hyperlink>
</Label>

and handle it like this:
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
    Window2 form2 = new Window2();
    form2.Show();
}

A: XAML :
<TextBlock Height="23" HorizontalAlignment="Left" Margin="254,130,0,0" Name="textBlock1" VerticalAlignment="Top">
        <Hyperlink Click="Hyperlink_Click">Clique Aqui</Hyperlink>
        </TextBlock>

CodeBehind :
private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            MainWindow m = new MainWindow();
            m.Show();
        }

this?


text:
Q: Is there a way to see which groups/users have access to an RSA key container? I used aspnet_regiis to create an RSA key container (machine container).
I want to secure it and I know I can use the -pa and -pr commands to specify access.  But is there a way to see which accounts/groups have access to it?
My concern is I created a container that is basically an open book that anyone can access on this machine and get the private key.

A: Machine Keys are stored in: %ProgramData%\Microsoft\Crypto\RSA\MachineKeys
They have normal file permissions, you can view as you'd like. Be careful changing permissions, they're easy to screw up.

redpajama_set_name: RedPajamaStackExchange


text:
Q: django user authentication incorporated with models and views I still cant seem to put a simple program together.  I am thinking of a simple program where my coworkers and I could propose a bet with each other. (example:  I bet the detriot Lions dont win another game this season)  If someone is feeling up to the task of taking that bet they can just hit an accept button.  I want the user to be logged in and upon submitting the bet_name and bet_desc of the bet, their username, bet_name, bet_desc, and timestamp is saved to a table.  Then a relationship table would save the bet id, win, tie, created_user_id, accepted_user_id, accepted_timestamp, and cancelled.  Then userprofile table to keep their username, wins, losses, ties, bets_made, and bets_accepted.
models.py
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class UserProfiles(models.Model):
    username = models.OneToOneField(User)
    wins = models.PositiveIntegerField(default=0)
    losses = models.PositiveIntegerField(default=0)
    ties = models.PositiveIntegerField(default=0)
    bets_made = models.PositiveIntegerField(default=0)
    bets_accepted = models.PositiveIntegerField(default=0)

    def __str__(self):
         return "%s's profile" % self.username

class Bets2(models.Model):
    bet_name = models.CharField(max_length=30)
    bet_desc = models.CharField(max_length=300)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    created_user = models.OneToOneField(UserProfiles, primary_key=True)
    accepted_user = models.PositiveIntegerField(default=0)
    accepted_timestamp = models.DateTimeField(auto_now=True)
    win = models.BooleanField(default=True)
    tie = models.BooleanField(default=True)
    cancelled = models.BooleanField(default=True)

    def __str__(self):
        return "%s's profile" % self.bet_name

As far as forms.py and views this is all i have so far:
forms.py
from django import forms
from django.core.exceptions import ValidationError

from .models import Bets2, UserProfiles

class BetForm(forms.ModelForm):
    class Meta:
        model = Bets2
        fields = ['bet_name', 'bet_desc',]

        def clean_name(self):
            bet_name = self.cleaned_data.get('bet_name')
        #write code here
            return name

        def clean_bet(self):
            bet_desc = self.cleaned_data.get('bet_desc')
        #write code here
            return bet

views.py
from django.shortcuts import render
from django.conf import settings

from .forms import BetForm
from .models import Bets2, UserProfiles

def home(request):
    title = "2015 Boardbets"
    queryset = Bets2.objects.all().order_by('timestamp')
    queryuser = UserProfiles.objects.all()
    context = {
    "title": title,
    "queryset" : queryset,
    "queryuser" : queryuser,
    }
    return render(request, "home.html", context)

def boardbet(request):
    form = BetForm(request.POST or None)
    bet_variables = Bets2.objects.all()
    context = {
    "form" : form,
    "bet_variables" : bet_variables,
    }
    if form.is_valid():
        form.save()

    return render(request, "bets.html", context)

This is where i get stumped, i dont know how to incorporate the other two models into the view so that all three tables get created and also how to reference them in the template.
Edit: changed it to one model for Bets


text:
Q: Releasing class members used in different synchronization contexts I am learning about the singleton design pattern with Chapter 29 of Professional C++, Second Edition1.
It illustrates a singleton implementation of a Logger class that covers thread-safety requirements:
Header
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <mutex>
// Definition of a multithread safe singleton logger class
class Logger
{
    public:
        static const std::string kLogLevelDebug;
        static const std::string kLogLevelInfo;
        static const std::string kLogLevelError;
        // Returns a reference to the singleton Logger object
        static Logger& instance();
        // Logs a single message at the given log level
        void log(const std::string& inMessage,
                 const std::string& inLogLevel);
        // Logs a vector of messages at the given log level
        void log(const std::vector<std::string>& inMessages,
                 const std::string& inLogLevel);
    protected:
        // Static variable for the one-and-only instance
        static Logger* pInstance;
        // Constant for the filename
        static const char* const kLogFileName;
        // Data member for the output stream
        std::ofstream mOutputStream;
        // Embedded class to make sure the single Logger
        // instance gets deleted on program shutdown.
        friend class Cleanup;
        class Cleanup
        {
           public:
           ~Cleanup();
        };
        // Logs message. The thread should own a lock on sMutex
        // before calling this function.
        void logHelper(const std::string& inMessage,
                  const std::string& inLogLevel);
    private:
        Logger();
        virtual ~Logger();
        Logger(const Logger&);
        Logger& operator=(const Logger&);
        static std::mutex sMutex;
};

Implementation
#include <stdexcept>
#include "Logger.h"
using namespace std;

const string Logger::kLogLevelDebug = "DEBUG";
const string Logger::kLogLevelInfo = "INFO";
const string Logger::kLogLevelError = "ERROR";
const char* const Logger::kLogFileName = "log.out";
Logger* Logger::pInstance = nullptr;
mutex Logger::sMutex;

Logger& Logger::instance()
{
    static Cleanup cleanup;
    lock_guard<mutex> guard(sMutex);
    if (pInstance == nullptr)
        pInstance = new Logger();
    return *pInstance;
}
Logger::Cleanup::~Cleanup()
{
    lock_guard<mutex> guard(Logger::sMutex);
    delete Logger::pInstance;
    Logger::pInstance = nullptr;
}
Logger::~Logger()
{
    mOutputStream.close();
}
Logger::Logger()
{
    mOutputStream.open(kLogFileName, ios_base::app);
    if (!mOutputStream.good()) {
        throw runtime_error("Unable to initialize the Logger!");
    }
}
void Logger::log(const string& inMessage, const string& inLogLevel)
{
    lock_guard<mutex> guard(sMutex);
    logHelper(inMessage, inLogLevel);
}
void Logger::log(const vector<string>& inMessages, const string& inLogLevel)
{
    lock_guard<mutex> guard(sMutex);
    for (size_t i = 0; i < inMessages.size(); i++) {
        logHelper(inMessages[i], inLogLevel);
    }
}
void Logger::logHelper(const std::string& inMessage,
    const std::string& inLogLevel)
{
    mOutputStream << inLogLevel << ": " << inMessage << endl;
}

It goes on to explain why the friend class Cleanup is introduced:

The Cleanup class is there to make sure the single Logger instance
  gets deleted properly on program shutdown. This is necessary because
  this implementation is dynamically allocating the Logger instance by
  using the new operator in a block of code protected with a mutex. A
  static instance of the Cleanup class will be created the first time
  the instance() method is called. When the program terminates, the C++
  runtime will destroy this static Cleanup instance, which will trigger
  the deletion of the Logger object and a call to the Logger destructor
  to close the file.

I find it very confusing that it states "This is necessary because...", as if there were no other alternative.
My questions:
1) Is it really necessary? Wouldn't it be enough to just have all the handling in the destructor?, like:
Logger::~Logger()
{
    {
        lock_guard<mutex> guard(Logger::sMutex);
        delete Logger::pInstance;
        Logger::pInstance = nullptr;
    }
    mOutputStream.close();
}

2) If the answer to 1) is "yes, it is indeed necessary!", I would like to know why.
1Professional C++, Second Edition by Marc Gregoire , Nicholas A. Solter , Scott J. Kleper Publisher: Wrox Published: October 2011

A: Yes, this is needed in this case.  Since the book used new and handed out a pointer there is no object that will go out of scope that will cause the destructor to fire.  The only way to do so is to call delete somewhere on that pointer.  Instead of requiring you to do that the Cleanup class was created to do that.
All of this though can be avoided if you use a Meyers Singleton.  That uses a static variable of the singleton type and returns a pointer/reference to that.  That will automatically be destroyed at the end of the program unlike the book version.  A Meyers Singleton looks like:
class Singleton {
public:
    static Singleton* Instance() { static Singleton s; return &s; }
    Singleton(const Singleton&) = delete;
    void operator=(const Singleton&) = delete;
private:
    Singleton() = default;
};


text:
Q: Distinct values of a column from a very large table I have a very large table with 1 billion rows and 12 columns, which are int, double, varchar. I need to know the distinct values for each volume.
SELECT COUNT(distinct a.id) as num_dist_id
 FROM my_large_table as a

SELECT distinct a.id
 FROM my_large_table as a

It is very slow.
Are there better ways to do that ?
---------------- update --------------------
the table has columns :
 id   id_1   id_2  id_3  id_4  id_5  id_6  id_7  id_8  id_9  id_10  id_11

SELECT distinct a.id , a.id_1 , a.id_2, a.id_3, a.id_4, a.id_5, a.id_6 ...
 FROM my_large_table as a
 ORDER BY a.id, a.id_1, a.id_2

Can speed up the query ?
Thanks !

A: Create an indexed view for each column that you want to query this way. Realize, that DISTINCT is equivalent to a GROUP BY on all columns. The view would look like this:
SELECT MyCol, COUNT_BIG(*) Count FROM T GROUP BY MyCol

Now create an index on it. In Enterprise edition this index will automatically speed up your original query. In Standard Edition you need to query this view directly with NOEXPAND.
The query will then execute as a trivial index scan. It can read the exact results you want off of an index. Doesn't get any faster.


text:
Q: Can you boot into recovery mode on an older iMac running a newer version of OS X (10.8)? I'm running OS X 10.8 on an iMac which is from 2008, and I can't seem to boot into recovery mode. Command-r doesn't do anything- the computer simply boots normally every time. Although OS X 10.8 certainly does support recovery mode, I'm wondering if the problem might be that I'm using an iMac that was built before the feature was added to OS x (it was added with 10.7 Lion in 2011, my iMac is from 2008). Is it possible that the hardware is preventing me from booting into recovery mode, or is it solely a feature of the operating system, and should work on older iMacs as well?

A: I believe the issue is that recovery mode was introduced in 2011, you are indeed correct.
If you have access to another Mac you could create a bootable macOS installer and boot from that


text:
Q: C# charts doesn't display decimal numbers in values I want to display values from database that are double, but when any of them have decimal numbers in charts it's treated like a integer number. For example if there's a value 902863,1 in database it's displayed as 9028631.
Here is code for displaying data on chart.
for (int i = 0, j = 0; i < ds.Tables[0].Rows.Count; i++)
{
    tmp_int = (int)ds.Tables[0].Rows[i][0];
    tmp_datetime1 = (DateTime)ds.Tables[0].Rows[i][1];
    tmp_str = datetime_to_string(tmp_datetime1);
    tmp_double = Convert.ToDouble(ds.Tables[0].Rows[i][2]);

    listOfValues.Add(tmp_double);

    listOfDifferences = calculateDifference(listOfValues);

    if (j <= i - 1)
    {
        ds.Tables[1].Rows.Add(tmp_int, tmp_str, listOfDifferences[j]);
        j++;
    }
}

And here is setting up chart
for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
{
    this.Chart1.Series[0].Points.AddXY(ds.Tables[1].Rows[i][1].ToString().Substring(11,5), ds.Tables[1].Rows[i][2]);
    this.Chart1.Series[1].Points.AddXY(ds.Tables[1].Rows[i][1], ds.Tables[1].Rows[i][2]);
}
this.Chart1.Titles.Add("Monday - " + date.ToString().Substring(0,10));
this.Chart1.Visible = true;
this.Chart1.Series[0].ToolTip = "#VALX - #VALY";
this.Chart1.Series[0].YValueType = System.Web.UI.DataVisualization.Charting.ChartValueType.Double;
this.Chart1.Series[1].YValueType = System.Web.UI.DataVisualization.Charting.ChartValueType.Double;
this.Chart1.ChartAreas[0].AxisX.Interval = 8;
this.Chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
this.Chart1.Series[0].Color = System.Drawing.Color.FromArgb(128, 0, 191, 255); //alpha r g b
this.Chart1.Series[1].Color = System.Drawing.Color.FromArgb(255, 0, 0, 255); //alpha r g b


text:
Q: scp files from yesterday I want to copy files from a remote Server to a local server. The problem is: I only want to copy the files from yesterday.
The remote server is writing logfiles and at 23:59 the logrotation is compressing it to a file [name]_[date].log.gz. At 6:00 in the morning a cronjob on the local server needs to copy the file previously created from the remote server. Does anyone know how to do this?
Regards,
Alex

A: You can use a script like this
for i in `find /interface/outbound/Web -type f -ctime -1`
do
scp $i user@$destination_server:/destination_directory/
done

in particular the command find as the following features for example:
find . -ctime -1 # which are created less than 1 day ago from currrent folder.
find . -ctime +2 # finds files which are created older than 2 days from currrent folder.

where ctime is the creation time. It's also possible to use the modification time mtime in this way:
find . -mtime 0   # find files modified between now and 1 day ago
find . -mtime -1  # find files modified less than 1 day ago
find . -mtime 1   # find files modified between 24 and 48 hours ago
find . -mtime +1  # find files modified more than 48 hours ago

More information in man find
Edit:
To have the same behaviour from remote to local you can use something like:
latest_file=`ssh user@destination_server find /pathtoDir -type f -ctime -1`
/usr/bin/scp user@destination_server:$latest_file /local_dir
echo SCP Completed.

At this moment I haven't a Unix environment to make some tests.


text:
Q: Get value from a Json string I have a Json sting like
var Result= [{"CompanyID":32,"Roles":["Admin"]}]

I need to get the value of CompanyID from this.
I tried something like
var obj = JObject.Parse(Result);
int Id=obj["CompanyID"];

but it throwing some error "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."
can anyone help
thanks in advance for help .

A: The actual problem is that you are trying to parse this to JObject when you actually have an array of objects. You can first parse it to an array, then index the array to select the only object, and select your CompanyID key then grab the value as an int
var Result = "[{\"CompanyID\":32,\"Roles\":[\"Admin\"]}]";
// Parse your Result to an Array
var jArray = JArray.Parse(Result);
// Index the Array and select your CompanyID
var obj = jArray[0]["CompanyID"].Value<int>();

Alternatively, you can also map the JSON to a concrete type if it's a structure you will work with often. This is more beneficial as you will have compile time checking - in the event of making a spelling mistake or capitalization error when selecting one of the keys.
class Program
{
    static void Main(string[] args)
    {
        var Result = "[{\"CompanyID\":32,\"Roles\":[\"Admin\"]}]";
        var cList = JsonConvert.DeserializeObject<List<Company>>(Result);

        var obj = cList.First().CompanyID;
    }
}

public class Company
{
    public int CompanyID { get; set; }
    public List<string> Roles { get; set; }
}


text:
Q: Broken inline datePicker as InputView for TextField Swift iOS 14 I use new inline Date Picker that is available from iOS 13.4 as inputView for Text Field(before I used wheels). However, it looks broken as the height of inputView is constant: How it looks
I have tried changing the frame and disable AutoResizingMaskIntoConstraints. It didn't help. The way it should work is like a default inline datePicker. How dataPicker should look like
To sum up, I need to increase the height of custom InputView for UITextField.

A: I Guess it was limited by default height of inputView.
Just change the Size of it then works.
// You can change value as you want. I think same with screen width is better for me.
let scrWidth = UIScreen.main.bounds.width
textfield.inputView?.frame.size = CGSize(width: scrWidth, height: scrWidth)
// Changing CGRect also can work
textfieldinputView?.frame = CGRect(x: 0, y: 0, width: scrWidth , height: scrWidth)

Result like this
Interesting, when I tested on SE1, it showed up as normal without using above method, and the inputView size was 320*353.3
inputView on SE1
But the height of other devices larger than it will limited to some value (IDK what is the reference.)
The limitation here was 355.666667, and the size would be 414*355.6667
inputView on 11 Pro Max
So that's why I guess dataPicker just get cropped when scaled up.

A: let scrWidth = UIScreen.main.bounds.width
textField.inputView?.frame.size = CGSize(width: scrWidth, height: scrWidth + 50)
datePicker.frame = CGRect(x: 0, y: 0, width: scrWidth , height: scrWidth + 50)


text:
Q: Android Intent for Image received in Whatsapp First of all: I am no Android Developer and need some help for a technical feasbility for an app.
I would like to get notified when a picture has been received e.g. in Whatsapp. I've already found out that it is generally possible, when the image is made with the camera and saved inside the media store. (http://developer.android.com/reference/android/hardware/Camera.html#ACTION_NEW_PICTURE).
At least on Whatsapp for iOS I can disable the feature, that sent and received photos will automatically be transferred to the media store (on iOS it is called Image Library). And if deactivating that is possible on Android, too, I need to

*

*get notified when a new image has been received in Whatsapp itself.

*and I should also be able to access that photo, event when it is stored in Whatsapp's directory.

Is that possible? Or only when an image is saved into the media store?


text:
Q: Only sort the NA's at the end of a vector R Is it possible to sort a vector where the order for non-missing/non-NA values is maintained, but the NA's in the vector are sorted to the end?
For example could I turn this vector
vector<-c("Dog", "Cat", NA, "Tiger", NA, "Bear")

into this
vector<-c("Dog","Cat","Tiger","Bear", NA, NA)

A: You can remove NA value using na.omit and subset till the length of vector to get NA at end.
na.omit(vector)[1:length(vector)]
#[1] "Dog"   "Cat"   "Tiger" "Bear"  NA      NA

A: Just order the vector using factor with appropriate levels=.
vector[order(factor(vector, levels=vector))]
# [1] "Dog"   "Cat"   "Tiger" "Bear"  NA      NA

A: Another option could be:
sort(factor(vector, levels = vector), na.last = TRUE)

[1] Dog   Cat   Tiger Bear  <NA>  <NA>

If some strings could be duplicated:
sort(factor(vector, levels = unique(vector)), na.last = TRUE)

A: Could also do:
vector[order(is.na(vector))]

# [1] "Dog"   "Cat"   "Tiger" "Bear"  NA      NA

TRUE (equals 1) is higher than FALSE (equals 0), so NA's are moved to the end while all TRUE cases to the beginning, without taking into account the real strings.
Works as well with duplicated strings, for example:
vector <- c("Dog", "Dog", "Cat", NA, "Tiger", NA, "Bear")

vector[order(is.na(vector))]

# [1] "Dog"   "Dog"   "Cat"   "Tiger" "Bear"  NA      NA


text:
Q: Tips on creating a Netflix-style scrolling menu in CSS/PHP? Working on a website which will allow members to catalog, shelve and review books. Right now, the main screen shows images of the book covers, plus basic info about the book. The books fill the screen and then wrap to the next line.
What I want to do is have a "Netflix-style" interface. i.e. First row=contemporary romance, second row=westerns, third row=vampires/werewolves, etc. And the row displays the first few books in that category, with arrows to scroll right and left to be shown other books.
Wondering if there are any examples of anything like this out there?  Here is the site. Be advised these are romance-style books, so the book covers shown may be "racy" although not indecent or pornographic.

A: The trick is to create a "container" element with position: relative; (to allow absolute positioning inside of it) and overflow: hidden; to hide the track.
Inside of this, place a "track" element with position: absolute; and width: 2000px; or however crazy wide it needs to be.
Inside the track, your book elements should be placed with float: left; and an appropriate margin-right value.
Two absolutely-positioned elements should act as the left and right sliders. A javascript setInterval can check whether the mouse is hovering over them every 10 milliseconds or so. If it is, change the left css property of the "track" element to slide it left or right.
I created a jsFiddle to illustrate this. Obviously, more complex code could be added to check whether the track has reached the edge, but you get the gist of it.


text:
Q: Widgets wrapped in QScrollArea do not use up available size Enter: the base code. Creates 25 QPushButtons wrapped in a QWidget with a QVBoxLayout, which (the QWidget) is itself the only child of a top-QVBoxLayout that handles widget placement in our top scroll_area_test-QWidget. The second QWidget wrapping may sound redundant, but will come in handy later.
#include <QVBoxLayout>
#include <QScrollArea>
#include <QWidget>
#include <QPushButton>
#include <QApplication>

/*
 * This declaration actually lives in its own header file,
 * but for simplicity's sake this code includes it here directly.
 */
class scroll_area_test : public QWidget {
  Q_OBJECT

  public:
    scroll_area_test ();
};

scroll_area_test::scroll_area_test () {
  QVBoxLayout *top_layout = new QVBoxLayout (this);

  QWidget *contents = new QWidget (this);
  top_layout->addWidget (contents);

  QVBoxLayout* inner_layout = new QVBoxLayout (contents);

  for (size_t i = 0; i < 25; ++i) {
    QPushButton *tmp_button = new QPushButton (this);
    inner_layout->addWidget (tmp_button);
  }
}

int main (int argc, char **argv) {
  QApplication app (argc, argv);

  scroll_area_test widget;
  widget.show();

  return (app.exec ());
}

This works fine. It produces a window with 25 buttons stashed on top of each other. Given that my display resolution is high enough, I can see the full window. Everything's dandy.

But wait, what if the user's resolution was lower than my own? The window would be too big to fit on their screens! Alas, there is a solution for these kinds of situations. Enter: QScrollArea.
scroll_area_test::scroll_area_test () {
  QVBoxLayout *top_layout = new QVBoxLayout (this);

  QScrollArea *scrolling_area = new QScrollArea (this);
  scrolling_area->setWidgetResizable (true);
  scrolling_area->setFocusPolicy (Qt::NoFocus);
  top_layout->addWidget (scrolling_area);

  QWidget *contents = new QWidget (this);
  //contents->setSizePolicy (QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);

  QVBoxLayout* inner_layout = new QVBoxLayout (contents);
  //inner_layout->setSizeConstraint (QLayout::SetMinimumSize);

  for (size_t i = 0; i < 25; ++i) {
    QPushButton *tmp_button = new QPushButton (this);
    inner_layout->addWidget (tmp_button);
  }

  scrolling_area->setWidget (contents);
}

I would expect this to not change the layout on my system, since there is ample space to show all widgets.
However, that's the new output:

What am I doing wrong? I want the scroll area to resize to its child's size automatically (hence setWidgetResizable (true)), bounded by the maximum window size. This does not seem to be the case here. The containing widget's size is not correctly taken into account and the scroll area thus is a.) smaller in height than it should be and b.) larger in width than it should be, both compared to the look without wrapping the QWidget in QScrollArea.
I've already played around with size constraints and policies (shown by commented-out code), but these did not change anything visually.
N.B.: I experienced this problem in a much more complicated situation, but was able to abstract it to this example.

A: You need to set size policy for your QScrollArea object.
Set the policy fixed both horizontally and vertically, as said below.
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
scrolling_area->setSizePolicy(sizePolicy);


text:
Q: Set/Reset jQuery Datepicker Date Range I have a dropdown with a few options and based on what is selected I need two datepickers (start date & end date) to have a specific date range. In the example below, if options 1 or 3 are selected, the end date can be any date in the future. If option 2 is selected, the date range should be 30 days.
In the jsFiddle below, both datepickers work as they should no matter which option you select first. My issue is that if you select option 1 or 3 first, then select option 2, it does not change the date range to only be 30 days. Flip flop it, select option 2 first and initially it works fine but change the dropdown to either option 1 or 3 and it keeps the 30 day date range as if option 2 was still selected.
How do I reset the date ranges every time a selection is made so that they are correct based on what is selected?
This jsFiddle shows currently how it is working: http://jsfiddle.net/p3J28/
And here is the code, copied/pasted from the jsFiddle.

    Select an Option:
    <select id="select1">
        <option value="" disabled="disabled" selected="selected">Select an option</option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
    </select>

    Start Date:
    <input type="text" id="startdatepicker" />

    End Date:
    <input type="text" id="enddatepicker" />

Also, I'm sure there is a much easier/better way of doing this so feel free to offer any suggestions as they are greatly appreciated.
Updated jsFiddle http://jsfiddle.net/6AKrg/
I was able to make a little progress but still do not have this working correctly. My issue now is only after Option 2 has been selected does it not reset the date ranges. The date range is correct if you select either Option 1 or Option 3 first and adjusts the date range as it should if you then select Option 2. After selecting Option 2, the date range does not get reset if you switch back to either Option 1 or Option 3. Anyone have any ideas?

A: I believe I finally figured this one out. When a different dropdown option is selected, the date ranges are being reset correctly.
Working jsFiddle: http://jsfiddle.net/KXqHc/
Here is the majority of the jQuery:

$(function() {
    $('#startdatepicker, #enddatepicker').datepicker({
        beforeShow: customRange,
        dateFormat: "mm/dd/yy",
        firstDay: 1,
        changeFirstDay: false
    });
});

function customRange(input) {
    var min = null, // Set this to your absolute minimum date
    dateMin = min,
    dateMax = null,
    dayRange = 30; // Restrict the number of days for the date range

    if ($('#select1').val() === '2') {
        if (input.id === "startdatepicker") {
            if ($("#enddatepicker").datepicker("getDate") != null) {
                dateMax = $("#enddatepicker").datepicker("getDate");
                dateMin = $("#enddatepicker").datepicker("getDate");
                dateMin.setDate(dateMin.getDate() - dayRange);
                if (dateMin < min) { dateMin = min; }
            } else {  }
        } else if (input.id === "enddatepicker") {
            dateMin = $("#startdatepicker").datepicker('getDate');
            dateMax = new Date(dateMin.getFullYear(), dateMin.getMonth(),
            dateMin.getDate() + 30);
            if ($('#startdatepicker').datepicker('getDate') != null) {
                var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(),
                    dateMin.getDate() + dayRange);
                if (rangeMax < dateMax) { dateMax = rangeMax; }
            }
        }
    } else if ($('#select1').val() != '2') {
        if (input.id === "startdatepicker") {
            if ($('#enddatepicker').datepicker('getDate') != null) {
                dateMin = null;
            } else {  }
        } else if (input.id === "enddatepicker") {
            dateMin = $('#startdatepicker').datepicker('getDate');
            dateMax = null;
            if ($('#startdatepicker').datepicker('getDate') != null) {
                dateMax = null;
            }
        }
    }
    return {
        minDate: dateMin,
        maxDate: dateMax
    };
}

Also, thanks to this post by @RussCam about datepicker restricting range with 2 input textboxes which can be found here as it provided a great start. Had to make a few changes to account for the dropdown control I have, but very helpful.

A: Refreshing (http://api.jqueryui.com/datepicker/#method-refresh) at the end of change should do the trick http://jsfiddle.net/p3J28/1/
$('#select1').change(function() {
    $('#startdatepicker, #enddatepicker').val("");
    if ($('#select1').val() == '2') {
        $('#startdatepicker, #enddatepicker').datepicker({
            showButtonPanel: true,
            closeText: 'Clear',
            dateFormat: "mm/dd/yy",
            onSelect: function(selected) {
                if (this.id == 'startdatepicker') {
                    var dateMin = $(this).datepicker('getDate');
                    var dateMax = $(this).datepicker('getDate');
                    dateMax.setDate(dateMin.getDate() + 5);
                    $('#enddatepicker').datepicker('option', { minDate: dateMin, maxDate: dateMax });
                } else if (this.id == 'enddatepicker') {
                    var dateMin = $(this).datepicker('getDate');
                    var dateMax = $(this).datepicker('getDate');
                    dateMin.setDate(dateMax.getDate() - 5);
                    $('#startdatepicker').datepicker('option', { minDate: dateMin, maxDate: dateMax });
                }
            }
        });
    } else {
        $('#startdatepicker, #enddatepicker').datepicker({
            showButtonPanel: true,
            closeText: 'Clear',
            dateFormat: "mm/dd/yy",
            onSelect: function(selected) {
                if (this.id == 'startdatepicker') {
                    $('#enddatepicker').datepicker('option', 'minDate', selected);
                } else if (this.id == 'enddatepicker') {
                    $('#startdatepicker').datepicker('option', 'maxDate', selected);
                }
            }
        });

    }

    $('#startdatepicker, #enddatepicker').datepicker('refresh');
});


text:
Q: How to get permission name value from array eloquent laravel I'm sorry if my english a bit weird, please ask me if you don't understand about my question.
So, I want a logic like this. When I tried with simple array like below, it works.
    $a = array('car', 'bicycle', 'plane');
    $b = array('car', 'boat', 'truck');
    foreach ($a as $c)
    {
        if (in_array($c,$b))
        {
            echo "" . $c . "";
            echo "\r\n";
        } else
        {
            echo $c;
            echo "\r\n";
        }
    }

But when I try to apply it in an array laravel eloqeunt it looks like I can't get the value from the array. I want to matching the array (permission name) from the database. I would like to show all permission name from 'permission' table then if 'permission name' that already apllied to a 'role' I want it display as checked. Here's my code :
    $roles = Role::where('id', '=', 2)->with(['permissions'])->get();
    $permissions = Permission::all();
    foreach ($roles as $role)
    {
        foreach ($permissions as $permission)
        {
            $roleper = array($role['permissions']);
            $pername = array($permissions);
            if (in_array($pername,$roleper))
            {
                echo "" . $permission['name'] . "";
                echo "\r\n";
            } else {
                echo $permission['name'];
                echo "\r\n";
            }

        }
    }

When I return the $roleper here's the result :
[[{"id":1,"name":"Add Color","guard_name":"web","created_at":"2020-08-10 02:49:25","updated_at":"2020-08-10 02:49:25","pivot":{"role_id":2,"permission_id":1}},{"id":2,"name":"Edit Color","guard_name":"web","created_at":"2020-08-10 02:50:49","updated_at":"2020-08-10 02:50:49","pivot":{"role_id":2,"permission_id":2}},{"id":3,"name":"Delete Color","guard_name":"web","created_at":"2020-08-10 02:50:57","updated_at":"2020-08-10 02:50:57","pivot":{"role_id":2,"permission_id":3}}]]

When I return the $pername here's the result :
[[{"id":1,"name":"Add Color","guard_name":"web","created_at":"2020-08-10 02:49:25","updated_at":"2020-08-10 02:49:25"},{"id":2,"name":"Edit Color","guard_name":"web","created_at":"2020-08-10 02:50:49","updated_at":"2020-08-10 02:50:49"},{"id":3,"name":"Delete Color","guard_name":"web","created_at":"2020-08-10 02:50:57","updated_at":"2020-08-10 02:50:57"},{"id":4,"name":"Add Material","guard_name":"web","created_at":"2020-08-10 03:11:16","updated_at":"2020-08-10 03:11:16"},{"id":5,"name":"Edit Material","guard_name":"web","created_at":"2020-08-10 03:11:25","updated_at":"2020-08-10 03:11:25"},{"id":6,"name":"Delete Material","guard_name":"web","created_at":"2020-08-10 03:11:36","updated_at":"2020-08-10 03:11:36"},{"id":7,"name":"Add Brand","guard_name":"web","created_at":"2020-08-10 03:11:48","updated_at":"2020-08-10 03:11:48"},{"id":8,"name":"Edit Brand","guard_name":"web","created_at":"2020-08-10 03:11:54","updated_at":"2020-08-10 03:11:54"},{"id":9,"name":"Delete Brand","guard_name":"web","created_at":"2020-08-10 03:12:00","updated_at":"2020-08-10 03:12:00"},{"id":10,"name":"Add Product","guard_name":"web","created_at":"2020-08-10 03:12:09","updated_at":"2020-08-10 03:12:09"},{"id":11,"name":"Edit Product","guard_name":"web","created_at":"2020-08-10 03:12:17","updated_at":"2020-08-10 03:12:17"},{"id":12,"name":"Delete Product","guard_name":"web","created_at":"2020-08-10 03:12:23","updated_at":"2020-08-10 03:12:23"}]]

A: You can use builtin methods array_intersect, array_diff to get common and different elements between 2 arrays
$permissions = Permission::all()->pluck('name')->toArray();
foreach ($roles as $role)
{
    $rolePermissions = $role['permissions']->pluck('name')->toArray();
    $maches = array_intersect($permissions, $rolePermissions);
    $differences = array_diff($permissions, $rolePermissions);
    //... loop $matches and $differences
}


text:
Q: Swift: returning and passing optional values in a method I was implementing UITableView in Swift and comparing it to Objective-C counterpart.
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

From Swift I'm returning an unwrapped optional. If i know I'm returning a non nil optional then why is the return type an optional at all? I'm also passing in uitableview as an unwrapped optional. The same wisdom applies.
It makes sense if I'm returning an optional and using a question mark to say i don't know if I'm returning a value or nil.. But I don't understand this specific case

A: It's just a matter of interfacing with the Objective-C APIs. Any object reference might be nil, and Swift needs to express that fact, so an Optional is needed. But by using an implicitly unwrapped Optional, Swift frees you from any concern over the fact that it's an Optional at all; you can just treat it as thing wrapped by the Optional, and let Swift worry about crossing the bridge for you.
Let's take the separate cases separately:
The Returned Value
You might pass nil here, because any object reference could be nil. So the return value is typed as an unwrapped optional. In reality, you just pass the table view cell object.
The Incoming Table View
It might be nil, because any object reference could be nil, but in fact you know it won't be. It is unwrapped implicitly for you, so in reality you can just use it as a table view.

A: Imagine you're not implementing this method but instead calling it on a class that was defined in Objective-C.  The Objective-C class could return nil so the protocol definition has to reflect that.  Even though in Swift you could guarantee that your method will never return nil, you can't have a different return type while still conforming to the protocol.
If you're writing your own protocol just in the context of Swift, then you can definitely drop the optional for added safety.


text:
Q: How to make a GRPC api call from javascript I have an external 3rd party GRPC server running which I want to query it in my javascript code.
I was wondering if there is way to do it, just like we query REST api through node-fetch or axios ?
How do I make this api call through javascript
grpcurl \
    -plaintext \
    -d '{"attribute":"XX"}' \
    localhost:14190 \
    X.Y.Z/Something

A: The Hello world client example for @grpc/grpc-js demonstrates how to make requests in general using the library. The specific components of the grpcurl invocation in the question correspond to the code in that example as follows:

*

*The X.Y.Z/Something service name corresponds with the name of the class that is instantiated to create the client object (Greeter, in that example).

*The localhost:14190 argument corresponds to the address passed as the first argument to the Greeter constructor.

*The -plaintext option corresponds to the grpc.credentials.createInsecure() object passed as the second argument to the Greeter constructor.

*The -d '{"attribute":"XX"}' argument corresponds to the object passed as the first argument to the client.sayHello method in the example.


text:
Q: Removing NSDate's with same day from NSArray I'm trying to come up with the best / cleanest way to do this.
Basically I have an array of NSDates, and I'm trying to get the UITableView Delegate methods (numberOfSectionsInTableView) to return the number of dates in the array that aren't the same.
So here's another example:
My array:
NSDate *1 (Monday 1st Jan)
NSDate *2 (Monday 1st Jan)
NSDate *3 (Tuesday 2nd Jan)
NSDate *4 (Wednesday 3rd Jan)
NSDate *5 (Wednesday 3rd Jan)

The array I would like:
NSDate *1 (Monday 1st Jan)
NSDate *2 (Tuesday 2nd Jan)
NSDate *3 (Wednesday 3rd Jan)

A: Probably the easiest solution is to pass you dates array in a set and then again into an array, but you loose sorting.

By definition NSSet can contain only one instance of equal instances.
NSSet *set = [NSSet setWithArray: datesArray];

By calling isEqual to one of each elements is guaranteed that you can't have duplicated dates. isEqual in a NSDate calls isEqualToDate that considers equality only if the instances represent the same date.
Then:
NSArray * newdates = set.allObjects

Is worth to mention that on NSArray you can also use KVC to make a distinct union:
NSArray * uniqueDates = [datesArray valueForKeyPath:@"@distinctUnionOfObjects.self"];


text:
Q: Any finger scanning sample tutorial iPhone sdk I have been seeing many apps on appstore concerning finger scan. I would like to get a tutorial how it works or if any free/paid sdk available. The goal behind is to use finger scanning as login instead the person has to login every time with a username/password.
Many thanks. :)

A: It is not possible. You can't get the user fingerprint through the iPhone screen.
In fact, the apps you mentioned are fake (and even scams if they try to make users believe they can indeed scan their fingerprint).

A: All of these apps are just for entertainment. None of them is actually scanning your finger, the screen isn't that good. I think that they do it by adding some gesture recognizer and waiting for a tap. And then one of many random fingerprints will just appear on the screen. If you check it a few times you will see that your finger will have different fingerprints.
So don't even try to use that for authentication. As an option: remember username/password in NSUserDefaults and connect immediately with it when the app Launches


text:
Q: BlazeDS, Flex, and Java - Can I treat a RemoteObject like an instance of the Java class? I'm sorry if this question is a bit obvious, but I'm new to BlazeDS and can't seem to find an answer. I'm running Java on a BlazeDS server with a Flex front-end. I'd like to be able to instantiate my Java class only once, then have the Flex use the setters and getters to play with the data in the Java class (in a sense, treating the RemoteObject as if it were an instance of the class). As far as I've read this seems to be the way BlazeDS works, but every time I call any Java method from Flex, it calls Java constructors again, resetting anything input by the setter methods. Is there a way to have the server hold the instance of the Java class between method calls? Thanks!

A: You seem to have a misunderstanding of how this is works.
Objects in the Flex client and Objects on your server are completely independent.  In normal circumstances, The Flash Player/A Flex App only talks to the remote service using either a WebSerice, HTTPService, or RemoteObject.  RemoteObject supports AMF and Flash Remoting with BlazeDS, LiveCycle Data Services, ColdFusion, and a ton of other server side software.
When you make remote calls to the server, that request is no different than a standard web page call.  It exists in "isolation" and knows nothing about any other call.  In traditional HTML development we use session cookies to keep track of server sessions in a 'stateless' client.  The same can be true for Flex calls.  If your server sets cookies on the client; then the Flash Player will include those cookies in each request; matching up the service call to a server side session.
Whether an object is created with each call depends on what your remote call does.
The benefit that AMF / RemoteObject offers is that it can easily translate server side objects (Java Classes) to client side objects (ActionSCript classes).  This is primarily used for passing of data between the two different entities.  Usually people make Value Objects/Data Transfer Objects for this; but the classes can have the same exact functionality.  It is not like the same object exists in both Flex and Java.
Does that help?


text:
Q: How to work with objects in JavaScript? How to work with object, if I want...
var object = { 'title': value };

alert( object[ /* Whatever */ ] ); // Should return 'title' NOT value

Thanks.

A: Use a for...in loop to enumerate an object's keys, like this:
for(var key in object) {
  alert(key);  //to get the key's value, use object[key]
}

To be safe, in case someone messed with the object prototype, use .hasOwnProperty() like this:
for(var key in object) {
  if(object.hasOwnProperty(key)) {
    alert(key);
  }
}


text:
Q: Proof of method to determine whether or not equally-sized axis-aligned disjoint cubes overlap each other when rendered. Consider two opaque equally-sized axis-aligned disjoint cubes somewhere in three dimensional Euclidean space. Additionally there is a point in that space outside of the cubes that represents a camera that renders this scene to a two dimensional screen using ray casting. (The exact geometry, location and orientation of the screen in space isn't really relevant here. We just assume that the camera is a point where rays start to or end from all directions.) Let's call one of these cubes the red cube and the other one the blue cube. The goal is to find out whether or not the red cube occludes (fully or partially) the blue cube on the rendered image. Here is a screenshot taken in Minecraft to illustrate such a scene.

In this scene the red cube partially occludes the blue cube. I claim that the following method to determine whether or not the red cube occludes (fully or partially) the blue cube works in general: If any ray, starting from the blue cube's vertices (corners) and ending at the camera, hits the red cube, then the red cube occludes (fully or partially) the blue cube, otherwise the red cube doesn't occludes the blue cube at all.
I'm looking for a mathematical proof that this method works in general. Are there any publications that prove this? If not, can someone prove this?
I have some ideas that could be useful for the proof.

*

*All cubes have the same size, thus cubes closer to the camera will appear larger.

*All cubes are equally oriented (are axis-aligned), which is important for the following arguments.

*The screen projections of parallel finite straight lines don't intersect at a single point only. (Parallel infinite straight lines may intersect at a single point only, e.g. railroad track at horizon.)

*The perspective forbids certain intersections in the screen projection for equally oriented cubes.

Additional context: Unfortunately it's not possible to use the method of performing eight ray casts (one for each cube vertex) as occlusion culling algorithm. The following picture shows that even if all eight ray casts hit another cube, the blue cube in question can still be partially visible.

However, the above described method could possibly be used to obtain a full set of cubes that are relevant for an exact occlusion culling algorithm applied afterwards. All other cubes in the scene that are not hit by a ray can be ignored. Thus it can be used as a premature optimization.

A: Suppose the the red cube occludes the blue cube. We are asked to show there must intersect the edges of the blue cube such that the line segment between the camera and the point hits the red cube.
Let $O$ be the camera, $R$ the red cube, $B$ the blue cube. $R$ occludes $B$ means there is a point $b$ on one of the faces of $B$, say $F_B$, such that the line segment $\overline{Ob}$ hits $R$.  Let $P$ be the plane of $F_B$. Let $I$ be the central projection of $R$ from $O$ to $P$.
There are two cases.

*

*$I$ intersects the edges in $F_B$.
Then any of the intersection points is what we wanted.

*$I$ does not intersect the edges of $F_B$. We will show this case cannot happen.
Since $R$ and $P$ are convex, so is $I$. Since any line segment between $b\in I$ and a point on $P$ outside $F_B$ must intersect the edges of $F_B$, $I$ cannot contain any point on $P$ outside $F_B$. So $I$ is strictly inside $F_B$.
$\quad$
Let $F_R$ be a face of $R$ that is parallel to $F_B$. Then the central projection of $F_R\subset R$ from $O$ to $P$ is strictly inside $F_B$, too. That is not possible, since $F_R$ and $F_B$ are equally-sized but any central projection of a $2$D shape to a parallel plane that is further away from the center of projection must be bigger than itself.

More generally, the same algorithm is correct still for two  polyhedrons in $3$D Euclidean spaces that differ only by a translation. The polyhedrons can be concave and self-intersecting. The same proof applies, except that we will replace arguments about the convexity of $I$ with similar argument about the connectedness of $I$.


text:
Q: Symmetric matrices and orthogonality
I'm struggling to make any progress with this question. I have defined C as the standard n-dimensional identity matrix. As A is semidefinite, I believe the diagonal matrix D must have positive values? How can I show this? Further, how does this help answer the original question?

A: By the finite-dimensional spectral theorem there exists an orthogonal matrix $C$ (i.e. $C^-1 = C^T$ such that $C^TAC = D = diag(d_1,\ldots, d_n)$ is a diagonal matrix. Let $e_k \in \mathbb{R}^n$ denote the vector, which $k$-th coordinate is $1$ and all others are $0$. Then
$$d_k = e_k^T D e_k = e_k^T C^T A Ce_k = (Ce_k)^T A (Ce_k) \geq 0.$$
Hence, all entries of $D$ are $\geq 0$. This means we can consider the square root $\sqrt{d_k}$ of $d_k$ and define $E := diag(\sqrt{d_1},\ldots, \sqrt{d_k})$. It follows that
$$E^2 = diag(\sqrt{d_1},\ldots, \sqrt{d_k}) \cdot  diag(\sqrt{d_1},\ldots, \sqrt{d_k}) =  diag(d_1,\ldots, d_k) = D = C^T A C.$$
Using that $C^T = C^{-1}$, we see that
$$A = CE \cdot EC^T = CEC^T \cdot CEC^T.$$
Now, if we define $B = CEC^T$, then
$$B^T = (CEC^T)^T = (C^T)^T E^T C^T = CEC^T = B$$
and $A = B^2$.

A:
I have defined C as the standard n-dimensional identity matrix.

Don't do that; choose the real unitary (orthogonal) $C$ that diagonalizes $A$.  That is, let $C$ be a matrix whose columns are an orthonormal eigenbasis of $A$, so that $C^T = C^{-1}$ and $D = C^TAC$.  Note that $A = CDC^T$.

As A is semidefinite, I believe the diagonal matrix D must have positive values? How can I show this?

Let $v = Ce_i$, where $e_1,\dots,e_n$ are the standard basis vectors. Compute $v^TAv$, noting that $A = CDC^T$.

Further, how does this help answer the original question?

Try to find a matrix $E$ so that $E^2 = D$, then define $B = C^TEC$.  In particular, make your choice of $E$ diagonal, with positive entries on the diagonal.


text:
Q: Csound 6 fails to initialize PortAudio directly, but works via file somehow I haven't used csound in quite some years; after installing the latest non-RC version (6.03.2) on Windows 7 I was unpleasantly surprised that I get no audio from it anymore. Oddly enough I can render to file and CsoundQt then can automatically play the redendered file ok, also through PortAudio. For the sake of fixing an example input I'm using 01C01_db_vs_linear.csd from the demos, although the choice of this file doesn't really matter for the outcome. Here's what I get when I just hit play (or Ctrl+R) in CsoundQt:
STARTING FILE
Creating options
Creating orchestra
Creating score
rtaudio: PortAudio module enabled ...
using blocking interface
Elapsed time at end of orchestra compile: real: 0.003s, CPU: 0.003s
sorting score ...
    ... done
Elapsed time at end of score sort: real: 0.003s, CPU: 0.003s
--Csound version 6.03.2 (double samples) May 12 2014
midi channel 1 using instr 1
midi channel 2 using instr 2
midi channel 3 using instr 1
midi channel 4 using instr 1
midi channel 5 using instr 1
midi channel 6 using instr 1
midi channel 7 using instr 1
midi channel 8 using instr 1
midi channel 9 using instr 1
midi channel 10 using instr 1
midi channel 11 using instr 1
midi channel 12 using instr 1
midi channel 13 using instr 1
midi channel 14 using instr 1
midi channel 15 using instr 1
midi channel 16 using instr 1
graphics suppressed, ascii substituted
0dBFS level = 1.0
orch now loaded
audio buffered in 4096 sample-frame blocks
PortAudio V19-devel (built Apr 21 2014 11:58:26)
   0: adc0 (ASIO4ALL v2)
PortAudio: failed to obtain device info.
Failed to initialise real time audio input

And I get no audio out. And here is what happens if I use the 'render to file' (Alt+F):
STARTING FILE
Creating options
Creating orchestra
Creating score
rtaudio: PortAudio module enabled ...
using callback interface
Elapsed time at end of orchestra compile: real: 0.004s, CPU: 0.004s
sorting score ...
    ... done
Elapsed time at end of score sort: real: 0.004s, CPU: 0.004s
--Csound version 6.03.2 (double samples) May 12 2014
midi channel 1 using instr 1
midi channel 2 using instr 2
midi channel 3 using instr 1
midi channel 4 using instr 1
midi channel 5 using instr 1
midi channel 6 using instr 1
midi channel 7 using instr 1
midi channel 8 using instr 1
midi channel 9 using instr 1
midi channel 10 using instr 1
midi channel 11 using instr 1
midi channel 12 using instr 1
midi channel 13 using instr 1
midi channel 14 using instr 1
midi channel 15 using instr 1
midi channel 16 using instr 1
graphics suppressed, ascii substituted
0dBFS level = 1.0
orch now loaded
audio buffered in 4096 sample-frame blocks
PortAudio V19-devel (built Apr 21 2014 11:58:26)
   0: dac0 (Microsoft Sound Mapper - Output)
   1: dac1 (Speakers (High Definition Audio)
   2: dac2 (Digital Audio (S/PDIF) (High De)
   3: dac3 (Digital Audio (S/PDIF) (High De)
   4: dac4 (Primary Sound Driver)
   5: dac5 (Speakers (High Definition Audio Device))
   6: dac6 (Digital Audio (S/PDIF) (High Definition Audio Device))
   7: dac7 (Digital Audio (S/PDIF) (High Definition Audio Device))
   8: dac8 (ASIO4ALL v2)
PortAudio: selected output device 'Speakers (High Definition Audio'
writing 8192 sample blks of 64-bit floats to dac
SECTION 1:
new alloc for instr 1:
B  0.000 .. 11.000 T 11.000 TT 11.000 M:  0.99990  0.99990
new alloc for instr 2:
B 11.000 .. 21.000 T 21.000 TT 21.000 M:  0.99983  0.99983
Score finished in csoundPerformKsmps().
inactive allocs returned to freespace
end of score.          overall amps:  0.99990  0.99990
       overall samples out of range:        0        0
0 errors in performance
Elapsed time at end of performance: real: 21.098s, CPU: 21.098s
closing device
227 8192 sample blks of 64-bit floats written to dac

And of course I can hear it this way. But why doesn't direct play work?
Edited to add: since it seem that the adc[s] is/are causing some kind of problem for PortAudio (which don't show up via play through rendered file because presumably it doesn't try to initialize the adcs when playing that way), I've uninstalled ASIO4ALL and rebooted, but still no luck playing directly, I just get a more cryptic log now because it lists no adcs at all, but still doesn't get past enumerating those non-existing adcs now:
STARTING FILE
Creating options
Creating orchestra
Creating score
rtaudio: PortAudio module enabled ...
using blocking interface
Elapsed time at end of orchestra compile: real: 0.003s, CPU: 0.017s
sorting score ...
    ... done
Elapsed time at end of score sort: real: 0.004s, CPU: 0.017s
--Csound version 6.03.2 (double samples) May 12 2014
midi channel 1 using instr 1
midi channel 2 using instr 2
midi channel 3 using instr 1
midi channel 4 using instr 1
midi channel 5 using instr 1
midi channel 6 using instr 1
midi channel 7 using instr 1
midi channel 8 using instr 1
midi channel 9 using instr 1
midi channel 10 using instr 1
midi channel 11 using instr 1
midi channel 12 using instr 1
midi channel 13 using instr 1
midi channel 14 using instr 1
midi channel 15 using instr 1
midi channel 16 using instr 1
graphics suppressed, ascii substituted
0dBFS level = 1.0
orch now loaded
audio buffered in 4096 sample-frame blocks
PortAudio V19-devel (built Apr 21 2014 11:58:26)
Failed to initialise real time audio input

This with direct run (Ctrl+R), playing via rendered file (Alt+F) still works as before.

A: Meh, I fixed it for now by picking no inputs in the config as suggested in http://csound.1045644.n5.nabble.com/Csound-QiuteCsound-problem-td3231424.html. This is quite annoying as the line/mic input is auto-configured when plugging stuff in on Windows, so one would expect PortAudio to manage this much by itself, but apparently that's beyond its current feature set. I'll have to remember to change that back to adc when using some input.


text:
Q: Show a RadDesktopAlert on form i want to Show a RadDesktopAlert on a form (not on the desktop). therefore i use second constructor to set its container to form. but nullException raised for this.Container
am i in the correct line to show RadDesktopAlert on the form (it is better to say IN THE FORM)?
and why container is null?
here is my code
      private void Form1_Load(object sender, EventArgs e)
      {
        Telerik.WinControls.UI.RadDesktopAlert q = new Telerik.WinControls.UI.RadDesktopAlert(this.Container);//null exception: Container is null
        q.ScreenPosition = Telerik.WinControls.UI.AlertScreenPosition.BottomCenter;
        q.ContentText = "what ever";
        q.Show();
      }

A: To do that you need to set the ScreenPosition to Manual and then set the popup location
        Telerik.WinControls.UI.RadDesktopAlert q = new Telerik.WinControls.UI.RadDesktopAlert();//null exception: Container is null
        q.ScreenPosition = Telerik.WinControls.UI.AlertScreenPosition.Manual;
        q.Popup.Location = new Point(this.Location.X + 20, this.Location.Y + 20);
        q.ContentText = "what ever";
        q.Show();


text:
Q: Desabilitar seleção para linha do DataGridView c# Windows Forms Olá, desde de já agradeço a atenção
Quero saber como desabilitar a possibilidade de selecionar uma linha de um DataGridView

MeuDataGridView.Rows[Linha desabilitada].enable = false;

Já tentei o Frozen:
MeuDataGridView.Rows[Linha desabilitada].Frozen = true;

Ele bloqueia o DataGridView todo, podem me ajudar?

A: Se tiver uma coleção com as linhas que não podem ser selecionadas, então pode fazer da seguinte forma (pressupondo que as linhas 1, 3 e 5 não podem ser selecionadas):
List<int> linhas = new List<int>() { 1, 3, 5 };

dataGridView1.SelectionChanged += (s, e) =>
{
    if (linhas.Contains(dataGridView1.CurrentRow.Index))
        dataGridView1.ClearSelection();
};


text:
Q: Как выполнить действие по таймеру? Мне нужно чтобы действие выполнялось через 0.5 секунды.
Например:
$('.className').addClass('className2');

A: Один раз
setTimeout(function(){$('.className').addClass('className2');}, 500);

Много раз
setInterval(function(){$('.className').addClass('className2');}, 500);


text:
Q: sklearn pipeline with transformed fitted with different set I'm building a text classifier (13 categories) with sklearn and I'm trying to implement a pipeline in order to make a CV grid search for the classifier and vectorizer paramters (min_df, max_df, etc. ).
The classifier is going to be used in a set of already available 50k documents and I have for training around 5k annotated near similar documents.
Since the annotated training documents are not exactly from the same source I don't want to train the classifier using features extract from the annotated corpus but from the main not annotated corpus. Therefore, I first do a TfidfVectorizer fit in the main non annotated documents:
vectorizer = TfidfVectorizer(ngram_range=(1,2),min_df = 0.01,max_df = 0.95,stop_words = None,use_idf=True,smooth_idf = True)
vectorizer.fit(non_annotated_docs)

and then, from this learned vocabulary, I calculate the features that will be used as input to the classifier:
X_tfidf = vectorizer.transform(annotated_docs)
X_tfidf = X_tfidf.toarray()

So my question is how can I do the pipeline with gridsearchcsv for the annotated_docs corpus, but using the fit from non_annotated_docs?


text:
Q: Altorouter cant figure out how to route correctly PHP if you haven't used this before the link is: http://altorouter.com/
I am making a small application but do not require a framework, only the routing part. So I've decided to try altorouter out as it seemed quite simple.
I want to map certain routes to do certain things. for example:
www.example.com/products/
this should show my products.php template and pull data from the database to populate the fields. I have got this working with the following:
$router->map( 'GET', '/products', function() {
    require('partials/connectdb.php'); //Require Database Connection
    $pageContent = getProductsContent($conn); //prepare all the page content from database
    require __DIR__ . '/products.php'; //require the template to use
});

The same for all of the other standard pages, my problem is when the route can change. For example:
www.example.com/shoes/
www.example.com/shorts/
www.example.com/shirts/
www.example.com/ties/
When a user goes to these routes I want to get the param 'shoes' and then while still using the products.php template, do the logic for only shoes.
So looking at the docs it says you can do:
www.example.com/[*] //which means anything.
However after adding this into my listed routes, it voids anything else the user trys to visit. So if they visit:
www.example.com/products // Like it worked before
It actually does the logic inside:
www.example.com/[*]
Does anyone know altorouter and can help me out please? I will paste my full page code below:
// Site Router
$router->map( 'GET', '/', function() {
    require('partials/connectdb.php'); //Require Database Connection
    $pageContent = getHomeContent($conn);
    require __DIR__ . '/home.php';
});

$router->map( 'GET', '/products', function() {
    require('partials/connectdb.php'); //Require Database Connection
    $pageContent = getProductsContent($conn);
    require __DIR__ . '/products.php';
});

$router->map( 'GET', '/[*]', function($id) {
    require('partials/connectdb.php'); //Require Database Connection

    $test = 'this was a test';
    $pageContent = getProductsContent($conn);
    require __DIR__ . '/products.php';
});

// match current request url
$match = $router->match();

// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
    call_user_func_array( $match['target'], $match['params'] );
} else {
    // no route was matched
    header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}

A: Your url should be
www.example.com/products/
www.example.com/products/shoes
www.example.com/products/shirts
Then you can do this:
$router->map( 'GET', '/products/:type', function($type) {
   require('partials/connectdb.php'); //Require Database Connection

   if(!isset($type)){
     $pageContent = getProductsContent($conn); //prepare all the page content from database
     require __DIR__ . '/products.php'; //require the template to use

    if($type == 'shoes'){
      //do this
      echo 'shoes';
    }
    if($type == 'shirts'){
      //do that
      echo 'shirts';
    }
});


text:
Q: conflicting CSS and Javascripts I am developing a component for Joomla website. This website has a sophisticated template with fancy css and scripts (namely some K2 components are named) In this component I am using colorbox to display modal picture gallery but what happens is
as soon as this component is called CSS properties and functions of javascript of template fails resulting in some weared page displays.
As I have not written these CSS and javascripts it will be quite cumbersome for me to prevent conflicts among CSS and scripts.
So what is my question is
Is there any way to prevent conflict between these scripts without diving much into the actual scripts.
Please guide me through this.
Thanx in advance

A: K2 is a content component for Joomla. It's not unusual for framework plug-ins or add-ons to have conflict(s) with one another. Unfortunately, you might have to search into Joomla or K2 forum for answers. Either that, you can try disabling other plug-ins one by one till the conflict disappears (hopefully).

A: One of the main conflicts in JavaScript is between MooTools (required for some Joomla functionaly) and other JavaScript libraries. Most common is the $ global variable which is commonly used as a DOM selector.
In MooTools, it only selects by ID, while in other libraries like JQuery, it uses CSS selectors.
So if you have a Joomla extension that loads another JavaScript library like JQuery, you'll run into problems. For JQuery, there is a specific solution.
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
For other libraries however, you'll need to dive into the JS, or use an extension that offers the same functionality but uses MooTools.
As for CSS, the only way around this is to edit the CSS files. Good extensions should use some sort of namespacing for their CSS. For example, prefix all CSS classes with the component name. Or wrap all HTML in a wrapper element named after the component, or module etc.
If this doesn't exist, you'll have to add it yourself.
Probably the easiest is to edit the extensions HTML and add:
<div id="extension-name">
  <!-- extension HTML here -->
</div>

around the extension.
Then edit the extensions CSS and add
#extension-name

before all CSS selectors.
For example, if you have:
.left-column {
  float: left;
}

change it to:
#extension-name .left-column {
  float: left;
}

You can even automate this process with a regex search and replace.


text:
Q: How to remove blank lines between matches in Ansible I am trying to remove blank lines between two lines using Ansible but cannot get it work. My source file looks like this:
###This line has blank lines after it

###End of block

#More lines

And I would like the result to look like this:
###This line has blank lines after it
###End of block

#More lines

So far I have this task using the replace module:
- name: Remove blank lines between matches
  replace:
    path: /home/vagrant/abcd
    after: '###This line has blank lines after it'
    regexp: '(^\n)'
    replace: ''
    before: '###End of block'

But the task does not appear to work. In fact the task does not do anything to the source file.
If I remove the last line of the task (before: '###End of block'). The lines do get removed but it also removes all blank lines until EOF which is not what I want. Here is the result with the last line removed:
###This line has blank lines after it###End of block
#More lines

Which is not expected.
I have a solution using sed but I want to keep it idempotent as possible. Maybe I need better regex?
Any ideas please?
Thanks.

A: After playing with this some more and playing with the regex I've come up with this:
- name: Remove blank lines between matches
  replace:
    path: /home/vagrant/abcd
    after: '###This line has blank lines after it'
    regexp: '(^\s*$)'
    replace: ''

This produces:
###This line has blank lines after it
###End of block

#More lines

Which is what I was after. But I will wait until the bug is fixed before using in production.

A: According to this issue: https://github.com/ansible/ansible/issues/31354 using after and before parameters together currently does not work as expected.
You can delete after paremeter from your task and in this case it will work as expected, but I know that it is not what you want to achieve.


text:
Q: Radio Input selected value on Update Laravel Hi there I really need your help I have this blade view:

            <?php  $k=1;  $k<=count($matrix_column_answers->where('deleted', 0)); ?>

                @foreach($matrix_column_answers as $matrix_column_answer)

                     @if($matrix_column_answer->deleted == 0)
                    <input type="text" name="matrix_column_answer[{{$k}}]" value="{{$matrix_column_answer->text}}"
                    class="form-control" placeholder="Column  ">
                        <input type="hidden" name="matrix_column_answer" value="{{$matrix_column_answer->id}}"
                    class="form-control" placeholder="Column  ">
                    @endif

                   <?php $k++;  ?>
                   @endforeach

             @foreach($matrix_row_answers as $matrix_row_answer)
             <?php  $r=1;  $r<=count($matrix_row_answers->where('deleted', 0)); ?>

                    <input type="text" name="matrix_row_answer[{{$r}}]" value="{{$matrix_row_answer->text}}"   class="form-control" placeholder="Row {{ $r }} ">
                @if($matrix_row_answer->row_id && $matrix_row_answer->col_id)

                          <input type="radio" name="col_nr[{{ $r  }}]"
                                 value="1"    class="col1" checked>

                          <input type="radio" name="col_nr[{{ $r  }}]"
                                 value="2"    class="col2" checked>

                          <input type="radio" name="col_nr[{{ $r  }}]"
                                 value="3"    class="col3" checked>

                          <input type="radio" name="col_nr[{{ $r  }}]"
                                 value="4"    class="col4" checked>

                @else

                            <input type="radio" name="col_nr[{{ $r  }}]"
                                   value="1"    class="col1">

                            <input type="radio" name="col_nr[{{ $r  }}]"
                                   value="2"    class="col2">

                            <input type="radio" name="col_nr[{{ $r  }}]"
                                   value="3"    class="col3">

                            <input type="radio" name="col_nr[{{ $r  }}]"
                                   value="4"    class="col4">

                @endif

                         {{--  <input type="hidden" name="row_col_nr[{{$r}}]" value="0" class="row_col_nr{{ $r  }}"> --}}

<?php $r++;  ?>
            @endforeach

I am taking from database this values:
#items: array:4 [▼
    0 => {#562 ▼
      +"id": 431
      +"question_id": 1261
      +"text": "something"
      +"row_id": 431
      +"col_id": 975
    }
     1 => {#565 ▼
      +"id": 432
      +"question_id": 1261
      +"text": "smthing"
      +"row_id": 432
      +"col_id": 976
    ..

This row_id and col_id is what tells me which radio button was clicked on create,  I knew from this values that I take from db to check the radio buttton, what I have tried so far it is not working, it is checking all cells of the last column only which is not right..
Can someone give me a little help..?


text:
Q: Which IDE is best for Verifone EDC programming I am currently Using source insight ide for Payment EDC programming. but it is not a good ide. i am not able to compile directly from that ide. i am currently adding project files, then making the programming changes and compiling using batch script. this process is very error prone and tedious.
I searched on net for IDE's to develop EDC application in verifone devices, but i could not get any concrete answer. verifone does not have its own ide. even if it has its may be for their internal use.
Can you please help me in suggesting which IDE can be used for verifone EDC application development. i tried in eclipse and qt creator. but could not generate lib symbols in it.

A: I'm not familiar with "EDC" in relation to VeriFone, but for my Verix, VerixV and eVo projects, I use Visual Studio.  You'll have to finesse it a bit to get it to work, but after a few tweaks, you will be all set up and ready to go and you can build from within the IDE, have it sign your output, move files to the appropriate locations, etc.  You'll also get intellisense (with some caveats) and the ability to set it to build for different platforms based on the solution configuration.
If you decide to take this route, here are some settings you'll need (and I'll be honest--I don't remember which of these I explicitly set and which were already that way).  To find them, right-click the project and go to properties. Let's say you're program is called myProgram

*

*Under "General" be sure the configuration type is Makefile

*"VC++ Directories"

*

*Executable Directories = $(PATH);

*Include Directories = $(EVOVMAC)\include;$(EVOVMAC)\template

*"NMake"

*

*Build Command Line=NMAKE /i /f myProgram.smk Configuration=$(Configuration)

*Rebuild All Command Line=NMAKE /i /f myProgram.smk /a Configuration=$(Configuration)

*Output=myprogram.exe

*Include Search Path=(the include files to myprogram);$(EVOVCS)Include;$(EVOSDK)\include; $(EVOACT)Include;$(EVOVMAC)Include;$(NMakeIncludeSearchPath)

Note that you may need to tweak that last one a bit
That should be enough to get you started.  There are several other things you can do to your make file to automatically do this or that, depending on your needs.


text:
Q: Adding Field to Profile "Name" I am trying to add an extra field or two underneath the "Name" or "About" section in the Wordpress user profile. So far I have only been able to accomplish this by:
//Begin
add_action('profile_personal_options',function(){
    ob_start();
});

//Grab Contents and Inject
add_action('show_user_profile',function($user){
        $contents = ob_get_contents();
    ob_end_clean();

    echo str_replace('<label for="description','!!!!!<label for="description',$contents);
});

But this seems like a dirty hack - what is the right way to accomplish this?

A: check out my older article
HOW TO ADD WORDPRESS AUTHOR BIO & PROFILE PAGE
https://phirebase.com/blog/how-to-add-author-bio-profile-page/
just short example to add Twitter and Facebook fields:
function my_new_contactmethods( $contactmethods ) {
// Add Twitter
$contactmethods['twitter'] = 'Twitter';
//Add Facebook
$contactmethods['facebook'] = 'Facebook';
return $contactmethods;
}
add_filter('user_contactmethods','my_new_contactmethods',10,1);

Single loop
<?php the_author_meta('facebook'); ?>
– show facebook name
<?php the_author_meta('twitter'); ?>
– show twitter name
Author page
<?php echo $curauth->facebook; ?>
– show facebook name
<?php echo $curauth->twitter; ?>
– show twitter name


text:
Q: One-time resolving promise singleton (Angular service) The question applies to promises in general and isn't specific to Angular, but the example makes use of Angular $q and service singletons.
Here is a plunker
var app = angular.module('app', []);

app.factory('onetimeResolvingService', function ($q) {
  var promise = $q(function(resolve, reject) {
    setTimeout(function () {
      resolve();
    }, 500);
  });

  return promise;
});

app.controller('AController', function (onetimeResolvingService, $q) {
  onetimeResolvingService.then(function () {
    console.log('A resolved');
    return $q.reject();
  }).then(function () {
    console.log('A resolved');
  });
});

app.controller('BController', function (onetimeResolvingService, $q) {
  onetimeResolvingService.then(function () {
    console.log('B resolved');
    return $q.reject();
  }).then(function () {
    console.log('B resolved');
  });
});

and the document is

It will naturally output

A resolved
B resolved

What would be a good pattern to make the singleton promise resolve only the first time, i.e.

A resolved

and not the subsequent times?
Something like onetimeResolvingService.$$state.status = 2 could possibly can do the trick, but it looks like $q hack and smells bad.

A:
What would be a good pattern to make the singleton promise resolve only the first time

To not to. One of the key facets of a promise is that once it's settled, it's settled, and both the settled state (resolved or rejected) and the value are at that point unchanging. See §2.1.2 and §2.1.3 of the A+ promises spec:

2.1.2 When fulfilled, a promise:
  2.1.2.1 must not transition to any other state.
  2.1.2.2 must have a value, which must not change.
2.1.3 When rejected, a promise:
  2.1.3.1 must not transition to any other state.
  2.1.3.2 must have a reason, which must not change.

If the callbacks added via then are not satisfied at some stage (e.g., your second hookup), it's not a promise. It's something...else.

A: T.J. Crowder is correct in that the functionality you're looking for in a promise does not exist.  The question of how to achieve what you're looking for however can be found in a structure like below:
    function OnetimeValue($q) {
        var promisedValue = $q(function(resolve, reject) {
            setTimeout(function () {resolve('The one time value');}, 500);
        });

        var valueGot = false;
        this.GetValue = function GetValue() {
            var res;
            if (!valueGot) {
                res = promisedValue;
            } else {
                res = $q(function(resolve, reject) {
                    resolve(null);
                });
            }
            valueGot = true;

            return res;
        };
    }

Assuming you new this once (as angular services do), GetValue() will return the promisified string upon the first call.  Subsequent calls return null.
This plunker shows the above in action

A: Edit: Whoops, misread the question.

There is now a way to do this with EcmaScript promises.  The static Promise.resolve() method takes a promise and waits on its value; if it has already been resolved, it simply returns the value.
For example, here's how we're using this method to make multiple calls to fetchQuery rely on a single async authentication call:
fetchQuery gets an auth token (JWT) with:
const authToken = await AuthToken.get();

And AuthToken looks like (TypeScript):
class AuthToken {
  private static _accessTokenPromise: Promise<string>;

  public static async get() {
    if (!this._accessTokenPromise)
      this._accessTokenPromise = this.AuthFunction(); // AuthFunction returns a promise

    return await Promise.resolve(this._accessTokenPromise);
  }
}

Or simply call then() twice on the same promise object per the OP's question to have two calls wait on the same async operation.

A: If you're using lodash you can simply use memoize like this:
const returnFirstRunResultAlways = _.memoize(async function(params) { ... })


text:
Q: How do I color the stippled underline in Sublime Text 3? I have a plugin using the add_regions command to draw underlines for certain regions.
I also have a custom tmLanguage and tmTheme, so I can control font style/foreground color etc. for scopes I have set.
Now, I'm trying to get my underlines to be a specific color (and not the default white-ish ST3 color)... I know this is possible because the spellcheck in ST3 has a red squiggly underline.
I've poked at changing the scope/settings/keys etc. in my tmTheme and my plugin's add_regions command, but nothing seems to stick.
Any direction would be very helpful!

A: You can simply set up a dummy scope in your tmTheme file with the foreground setting valued to the color you want your underline to be. Then pass in that scope name to the add_regions function call.
Example for yellow underline...
In the tmTheme file:
...
<dict>
  <key>name</key>
  <string>Yellow Underline</string>
  <key>scope</key>
  <string>underline.yellow.text</string>
  <key>settings</key>
  <dict>
    <key>foreground</key>
    <string>#FFFF00</string>
  </dict>
</dict>
...

In your plugin:
# ...
# set regions variable above
view.add_regions('key', regions, 'underline.yellow.text', '', sublime.DRAW_STIPPLED_UNDERLINE | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE)
# ...

Ta-da! You should have yellow underlines now :)


text:
Q: Error: Maven2RepositoryLayoutFactory: Unsupported repository layout legacy I get this error message from maven:
[ERROR] Failed to execute goal on project battleships: Could not resolve dependencies for project com.miteff.travelex:battleships:wa
r:2.0.0-BUILD-SNAPSHOT: The following artifacts could not be resolved: javax.jms:jms:jar:1.1, com.sun.jdmk:jmxtools:jar:1.2.1, com.s
un.jmx:jmxri:jar:1.2.1: Could not transfer artifact javax.jms:jms:jar:1.1 from/to java.net (https://maven-repository.dev.java.net/no
nav/repository): Cannot access https://maven-repository.dev.java.net/nonav/repository with type legacy using the available connector
 factories: BasicRepositoryConnectorFactory: Cannot access https://maven-repository.dev.java.net/nonav/repository with type legacy u
sing the available layout factories: Maven2RepositoryLayoutFactory: Unsupported repository layout legacy -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

I have almost blank Spring project with log4j. Log4j is registered this way
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.15</version>
</dependency>

A: There are two solutions known to me:

*

*Update log4j version to 1.2.17 solves the issue.

*Stay with log4j version 1.2.15, but add scope runtime to it in this way:
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.15</version>
    <scope>runtime</scope>
</dependency>

A: The only way I found to solve this problem is to have simple maven 2 side project into which I put the failed dependencies. I then run maven 2 against this project, the dependencies download fine and then maven 3 finds them.
I tried using update policy 'always' but that didnt always work.


text:
Q: Writing a program to scrape forums I need to write a program to scrape forums.
Should I write the program in Python using the Scrapy framework or should I use Php cURL?
Also is there a Php equivalent to Scrapy?
Thanks

A: I would choose Python due to superior libxml2 bindings, specifically things like lxml.html and pyQuery.  Scrapy has its own libxml2 bindings, I haven't looked at them to test them, though skimming the Scrapy documentation didn't leave me very impressed (I've done lots of scraping just using these parsers and manual coding).  With any of these you get a truly superior HTML parser, querying via XPath, and with lxml.html and pyquery (also built on lxml) you get CSS selectors.
If you are doing a small job scraping a forum, I'd skip a scraping framework and just do it by hand -- it's easy and parallelizing etc is not really needed.

A: I wouldn't use PHP for a new application that I'm writing. I don't like the language for various reasons.
Also, it's strength is as a server side scripting language to deliver dynamic pages over the web. Not as a general purpose programming language. That's another minus point. I'd stick with Python.
As for which framework to use, there are lots of them around. Harvestman, Scrapy etc. There's also the 80legs cloud based crawler than you might be able to use.
Update : People have been downvoting this answer probably because I said I didn't like PHP. Here's a list of reasons why. Not entirely accurate but a decent summary nevertheless http://wiki.python.org/moin/PythonVsPhp


text:
Q: Convert json query to insert a variable and re-convert it to json query I am kinda frustrated. I copied the following Metabase query string from the network tab in the browser:
query = "{\"database\":17,\"query\":{\"source-table\":963,\"filter\":[\"and\",[\"=\",[\"field\",17580,null],\"XXXXXX_XXXXXX\"],[\"=\",[\"field\",17599,null],\"**chl-43d813dd-05a7-45b8-a5b0-8eb960289aa5**\"]],\"fields\":[[\"field\",17579,null],[\"field\",17569,null],[\"field\",17572,null],[\"field\",17586,null],[\"field\",17592,{\"temporal-unit\":\"default\"}],[\"field\",17611,null],[\"field\",17582,null],[\"field\",17597,null],[\"field\",17603,null],[\"field\",17607,null],[\"field\",17576,null],[\"field\",17588,null],[\"field\",17596,null],[\"field\",17608,null],[\"field\",17587,{\"temporal-unit\":\"default\"}],[\"field\",17578,{\"temporal-unit\":\"default\"}],[\"field\",17602,null],[\"field\",17606,null],[\"field\",17605,{\"temporal-unit\":\"default\"}],[\"field\",17601,null],[\"field\",17590,null],[\"field\",17580,null],[\"field\",17598,{\"temporal-unit\":\"default\"}],[\"field\",17577,null],[\"field\",164910,null],[\"field\",46951,null],[\"field\",46952,{\"temporal-unit\":\"default\"}]]},\"type\":\"query\",\"middleware\":{\"js-int-to-string?\":true,\"add-default-userland-constraints?\":true}}"

As the next step I wanted to convert it to a String to replace the bold reference with a variable.
The String looks like this:
query = '{"database\":17,\"query\":{\"source-table\":963,\"filter\":[\"and\",[\"=\",[\"field\",17580,null],\"XXXXXXXX-XXXXXXXX\"],[\"=\",[\"field\",17599,null],\"'+channelRef+'\"]],\"fields\":[[\"field\",17579,null],[\"field\",17569,null],[\"field\",17572,null],[\"field\",17586,null],[\"field\",17592,{\"temporal-unit\":\"default\"}],[\"field\",17611,null],[\"field\",17582,null],[\"field\",17597,null],[\"field\",17603,null],[\"field\",17607,null],[\"field\",17576,null],[\"field\",17588,null],[\"field\",17596,null],[\"field\",17608,null],[\"field\",17587,{\"temporal-unit\":\"default\"}],[\"field\",17578,{\"temporal-unit\":\"default\"}],[\"field\",17602,null],[\"field\",17606,null],[\"field\",17605,{\"temporal-unit\":\"default\"}],[\"field\",17601,null],[\"field\",17590,null],[\"field\",17580,null],[\"field\",17598,{\"temporal-unit\":\"default\"}],[\"field\",17577,null],[\"field\",164910,null],[\"field\",46951,null],[\"field\",46952,{\"temporal-unit\":\"default\"}]]},\"type\":\"query\",\"middleware\":{\"js-int-to-string?\":true,\"add-default-userland-constraints?\":true}}'

With
 q = json.dumps(query)

the result looks exactly as I want to:
q = "{\"database\":17,\"query\":{\"source-table\":963,\"filter\":[\"and\",[\"=\",[\"field\",17580,null],\"XXXXXXXX-XXXXXXXX\"],[\"=\",[\"field\",17599,null],\"**chl-caabef81-f081-4532-9b6e-ac20b3d4c6cf**\"]],\"fields\":[[\"field\",17579,null],[\"field\",17569,null],[\"field\",17572,null],[\"field\",17586,null],[\"field\",17592,{\"temporal-unit\":\"default\"}],[\"field\",17611,null],[\"field\",17582,null],[\"field\",17597,null],[\"field\",17603,null],[\"field\",17607,null],[\"field\",17576,null],[\"field\",17588,null],[\"field\",17596,null],[\"field\",17608,null],[\"field\",17587,{\"temporal-unit\":\"default\"}],[\"field\",17578,{\"temporal-unit\":\"default\"}],[\"field\",17602,null],[\"field\",17606,null],[\"field\",17605,{\"temporal-unit\":\"default\"}],[\"field\",17601,null],[\"field\",17590,null],[\"field\",17580,null],[\"field\",17598,{\"temporal-unit\":\"default\"}],[\"field\",17577,null],[\"field\",164910,null],[\"field\",46951,null],[\"field\",46952,{\"temporal-unit\":\"default\"}]]},\"type\":\"query\",\"middleware\":{\"js-int-to-string?\":true,\"add-default-userland-constraints?\":true}}"

But when I use this query string to send an API request, I get the following error message(s):
{"via":[{"type":"java.lang.ClassCastException"}],"trace":[],"message":null}

Traceback (most recent call last):
File "c:\Users\XXXX\Documents\XXXXXXXX\Test.py", line 308, in
main()
File "c:\Users\XXXX\Documents\XXXXXXXX\Test.py", line 114, in main some_function(XXXX, window, selected_path)
File "c:\Users\XXXX\Documents\XXXXXXXX\Test.py", line 290, in some_function
dataframe = DataFrame(result)
File "C:\Users\XXXX\AppData\Roaming\Python\Python310\site-packages\pandas\core\frame.py", line 756, in init
raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!

Does have anyone have an idea?
Thank you very much in advance!

A: You can use the built-in json module:
import json
query = "{\"database\":17,\"query\":{\"source-table\":963,\"filter\":[\"and\",[\"=\",[\"field\",17580,null],\"XXXXXX_XXXXXX\"],[\"=\",[\"field\",17599,null],\"**chl-43d813dd-05a7-45b8-a5b0-8eb960289aa5**\"]],\"fields\":[[\"field\",17579,null],[\"field\",17569,null],[\"field\",17572,null],[\"field\",17586,null],[\"field\",17592,{\"temporal-unit\":\"default\"}],[\"field\",17611,null],[\"field\",17582,null],[\"field\",17597,null],[\"field\",17603,null],[\"field\",17607,null],[\"field\",17576,null],[\"field\",17588,null],[\"field\",17596,null],[\"field\",17608,null],[\"field\",17587,{\"temporal-unit\":\"default\"}],[\"field\",17578,{\"temporal-unit\":\"default\"}],[\"field\",17602,null],[\"field\",17606,null],[\"field\",17605,{\"temporal-unit\":\"default\"}],[\"field\",17601,null],[\"field\",17590,null],[\"field\",17580,null],[\"field\",17598,{\"temporal-unit\":\"default\"}],[\"field\",17577,null],[\"field\",164910,null],[\"field\",46951,null],[\"field\",46952,{\"temporal-unit\":\"default\"}]]},\"type\":\"query\",\"middleware\":{\"js-int-to-string?\":true,\"add-default-userland-constraints?\":true}}"
my_json = json.loads(query)
# make edit's (works like a dict)
query = json.dumps(my_json)

A: I don't see a bold reference in your JSON string, but this is all handled with the json library:
import json
query = "YOUR QUERY STRING"
object = json.dumps(query)
# Make your changes to your dict object here
new_query = json.loads(object)


text:
Q: How to fix "Fatal error: Uncaught Error: Call to undefined function get_header()" I am trying to put this website back online. The error message is the following:

Fatal error: Uncaught Error: Call to undefined function get_header()
  in
  /homepages/25/d584099293/htdocs/clickandbuilds/X3DSYSTEMS/wp-content/themes/x3dprotheme/index.php:4
  Stack trace: #0 {main} thrown in
  /homepages/25/d584099293/htdocs/clickandbuilds/X3DSYSTEMS/wp-content/themes/x3dprotheme/index.php
  on line 4

The client told me he "accidentally reset the domain".
First when I went on the website, I had an error message about Wordfence and I did what I needed to do to correct it (here what I did:
After moving a site or deleting some files, I see: PHP Fatal error: Unknown: Failed opening required /var/www/html/wordfence-waf.php
I removed the firewall setup manually.
Then I got this new error message about index.php:
In this index.php, here is what I found:
<?php get_header(); ?>

<?php get_footer(); ?>

I try to get this website back online.
The webhost is 1and1 IONOS. I can't log into WP, but I have SFTP access.

A: What webhost is this? Maybe if we know, we can ascertain what the "domain reset" involved and backtrack the fix once we know exactly what those steps entailed.
When these sorts of things happen to me (I manage about 30 WordPress sites), the first thing I do is disable all plugins, and sometimes if I can't actually log into WordPress, I remove the plugins via SFTP or through cPanel.
You're stuck though if you have no access to the host. It'll extremely difficult to solve this without access to the server or control panel for the hosting environment. Do you at least have SFTP access?

A: This looks like a path to a core theme file.
If you are using child theme, you should be able to update the parent via the theme settings found in your dashboard, without data loss from style sheets, etc. you made in your child theme.
This would work like the backup restore as suggested above, but without the need to get into cPanel or FTP.

A: The client changed the "target" with his webhost, and the site is back online.
There was also a problem with revolution slider, but anyway, the problem looks solved.


text:
Q: Firebase, autentificacion con telefono y google En mi aplicación uso Firebase para autenticarme.
Primero el usuario se autentica con el teléfono, necesito verificarlo y luego en el momento quiera, puede loguearse con Google para tener una mejor experiencia sobre la app.
El login en ambos lo hace perfecto, no tengo ningún problema con eso, es más, desinstalas la app, vuelves a instalarla y es como si nada hubiera pasado.
Pero el problema que tengo es que cuando el usuario cambia su número de teléfono y vuelve a entrar a la aplicación (ej. La desinstalo y volvió a instalar) se registra con su número, luego si quiere usar su cuenta de Google, me da este error:
SIGN_IN

com.google.firebase.auth.FirebaseAuthUserCollisionException: This credential is already associated with a different user account.

REAUTHENTICATE

com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The supplied credentials do not correspond to the previously signed in user.

Que es lo que puedo hacer para que el usuario pueda volver a usar su cuenta de Google con otro teléfono hasta ahora vengo borrando los usuarios viejos, pero no es bueno eso.
¿O qué otra alternativa tengo?
PD: por si dicen de activar múltiples cuentas por correo, no funciono.

A: Firebase te permite crear una cuenta con distintas formas de autentificar como facebook, google, email, etc. Si creas una cuenta supongamos con email y contraseña y luego decides logearte con facebook tendras un problema de FirebaseAuthUserCollisionException esto se puede solucionar linkeando las cuentas con este metodo: firebase.auth().currentUser.linkWithCredential(credential).
Pero antes que copies y peges hay un problema!. Para hacer el linkeo necesitas que exista un currentUser, y si no estas logeado no hay cuenta al cual puedas linkear  esta nueva forma de autentificacion y claro si estabas intentando logear entonces obvio no estas logeado.
Lo que debes hacer entonces es pedirle al usuario que se autentifique con el metodo que uso anteriormente, esto lo podes saber usando metodo firebase.auth().fetchProvidersForEmail(email) que te traera una lista con los metodos de autentificacion validos para esa cuenta.
Finalmente ahora que ya estas autentificado correctamente podes usar el metodo de linkWithCredential() usando la credencial que habia dado CollisionException para permitir que la proxima vez tu usario pueda autentificarse con ese metodo y no vuelvas a tener el CollisionException.


text:
Q: Fixed/absolute positioning neglected in iOS when focusing on input I'm building an app with Phonegap and I have a header which I have fixed to the top of viewport.
header {
  position: fixed;
  top: 0;
  width: 100%;
  height: 30px;
  background-color: red;
  z-index: 100;
}

This works as I want except when I tap a input field and the keyboard slides up. Then the positioning is totally discarded. The header is slided higher up outside the visable view. It returns to its place after closing the keyboard again.
I have read that some mobile browser don't care about positioned fixed and absolute to make sure that a possibly small screen don't get covered with a fixed element. Is this true?
Is there a way around this?
I have tried setting the header to absolute when a input is focused. I read about it here, http://dansajin.com/2012/12/07/fix-position-fixed/. However, it doesn't seem to be working for me.

A: PhoneGap's implementation of fixed positioning for iOS is poor when it comes to the virtual keyboard. I've tried a number of proposed solutions, including the one you linked to, but none of them worked satisfactorily. Disabling KeyboardShrinksView can cause the input field to get hidden under the keyboard.
I ended up going with this workaround, which simply hides the fixed header when the keyboard slides into view and shows it again after the keyboard slides out of view. I await a more complete fix, but this solution has the benefit of being clean and reliable. The 10 ms delay on show() is enough to prevent the header from momentarily flashing in the wrong place while the keyboard is sliding back down. The 20 ms delay on hide() prevents the header from popping up in the wrong place if the user goes directly from one input field to the next.
$(document).on('focus','input, textarea, select',function() {
    setTimeout(function() {
        $('header').hide();
    },20);
});
$(document).on('blur','input, textarea, select',function() {
    setTimeout(function() {
        $('header').show();
    },10);
});