text:
Q: carousel arrow also changes text in a div react.js I am making a character select screen and I want the bootstrap carousel arrows to also change the text in the scroll to match each character. Right now the scroll is a separate component but I'm open to putting them on the same page.

I was trying to grab it by the class "active" since that came with the bootstrap carousel and populating from a data.json, but it isn't working. Open to other (hopefully easier) ideas as well!!

    state = {
        data: characters,
        curCharacter: {},

    }
    componentDidMount() {
        var cur = this.state.data[0].description;
        this.setState({ curCharacter: this.state.data[0] });
        console.log(this.state.curCharacter)
    }

    characterSelect = (e) => {
        e.preventDefault()
        var cur = document.getElementsByClassName("active")
        console.log("activ1", cur)
        var newClass = cur[0].children[0].alt
        console.log("activ2", newClass);
        var arr = this.state.data;
        console.log(arr);
        for (let i = 0; i < arr.length; i++) {
            console.log(arr[i], arr[i + 2]);
            if (newClass == arr[i].class) {
                this.setState({ curCharacter: arr[i] });
                console.log(this.state.curCharacter)
            }
        }
    }

    render() {
        return (

                                Previous

                                Next

                        <button onClick={handleButtonChoose} className="choose">Choose Character</button>

                        <Scroll
                            text={this.state.description}
                        />

        )
    }
}

export default Character

Thanks in advance!!


text:
Q: bulk letter with datatool: how to handle linebreak csv-field I'm generating a bulk letter using datatool. Therefore I import my data from an external csv-file using the following syntax:
\documentclass[11pt]{dinbrief}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{lmodern}
\usepackage[separator=;]{datatool}
\newrobustcmd{\companyrobust}{\parbox[b]{7.5cm}{\raggedright\company}}
\begin{document}
\inputencoding{latin1}
\DTLloadrawdb{addr}{list.csv} % open database
\inputencoding{utf8}
\DTLforeach{addr}{
  \company=company,
  \firstname=firstname,
  \surname=surname%
}{ % start bulk letter
\begin{letter}{\companyrobust\\\firstname\ \surname}
\subject{\textbf{test}}
\opening{Dear Mr. \surname,}
nothing
\closing{regards}
\end{letter}
}
\end{document}

the corresponding list.csv is the following:
company;firstname;surname
Microsoft Software;Bill;Gates

This was working for me for quite a while but now I have the problem that there is a company in my list which has a linebreak in its name. For example I want to put "Software" in a new line. I tried using \\, \linebreak and \newline but I it did not work and I could not figure out how to succeed. How can I realize a defined line break within a field of the csv-file?

A: If you want to include LaTeX commands in your csv file, you can't use \DTLloadrawdb. If you switch to \DTLloaddb instead, your example works fine with \DTLpar.
list.csv:
company;firstname;surname
Microsoft\DTLpar Software;Bill;Gates

Test file:
\documentclass[11pt]{dinbrief}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{lmodern}
\usepackage[separator=;]{datatool}
\newrobustcmd{\companyrobust}{\parbox[b]{7.5cm}{\raggedright\company}}
\begin{document}
\inputencoding{latin1}
\DTLloaddb{addr}{list.csv} % open database
\inputencoding{utf8}
\DTLforeach{addr}{
  \company=company,
  \firstname=firstname,
  \surname=surname%
}{ % start bulk letter
\begin{letter}{\companyrobust\\\firstname\ \surname}
\subject{\textbf{test}}
\opening{Dear Mr. \surname,}
nothing
\closing{regards}
\end{letter}
}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selecting multiple values from a column and put them into separate columns
I have a table like this:
MainUser | PartyUser
--------------------
George   | Tom
Michael  | Tim
Michael  | James
Michael  | Monica
Jim      | Nick
Jim      | Connie
And I need to get something like this:
MainUser | PartyUser1 | PartyUser2 | PartyUser3 | PartyUser4 ...
----------------------------------------------------------------
George   | Tom        |            |            |
Michael  | Tim        | James      | Monica     |
Jim      | Nick       | Connie     |            |
Can someone help to find a way doing this in sql?
I'm having a hard time figuring this out, so any help would be greatly appreciated.

A: The simple way (assuming you already know all the party users) would be to use pivot() and row_number() statements.
select  MainUser,
        [1] as PartyUser1,
        [2] as PartyUser2,
        [3] as PartyUser3,
        [4] as PartyUser4,
        [5] as PartyUser5,
        [6] as PartyUser6
from (
    select *, row_number() over(partition by MainUser order by PartyUser) as rn
    from party_table
    ) t
PIVOT (max(PartyUser) for rn in ([1], [2], [3], [4], [5], [6])) as u


text:
Q: Unable to merge dex error when adding room dependency When i add room dependencies and try to build project i am getting "unable to merge dex error".
I am adding below dependencies
implementation "android.arch.persistence.room:runtime:1.0.0-alpha1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"

If i remove them i am able to build project successfully.
I am using android studio 3.0 stable version.

A: Replacing "1.0.0-alpha1" with 1.0.0-rc1 solved the problem.


text:
Q: Minecraft: does the server auto-updates the new features into the existing save? Does the minecraft server automatically add the new features once updated, even in the old saves, or it only does that in the new games?

A: It depends what you mean by new features.  I can't guarantee how things will go in the future, but here's how things generally have happened in the past.

*

*New block types will not be added to the existing map.  They WILL, however, start appearing in new chunks.  This was part of the reason lapis lazuli seemed exceedingly rare after its update, people were looking in previously generated chunks.

*New mob types will spawn in existing parts of your map.  They can appear wherever their spawning algorithms determine is "valid," and chunk age isn't factored in.

Those are the only two cases I can think of at the moment.  If you had a specific question or wanted an answer about another group I forgot about, I'd be happy to update my answer.

A: Mobs and craftable items and stuff appear in existing save files after updates. New blocks that randomly spawn on a game when it starts will only appear if you go to a new area far away called chunks. I don't know how many blocks make a chunk.


text:
Q: Android Studio using jars I'm new on Android Studio since I've used Eclipse till now. Now I'm trying to import two libraries (MPChartLib and datetimepicker-library) as a jar.
The steps I did:
1. Create a folder called libraries
2. Drag and drop the jars to the folder
3. Right click on them --> Add to library (something like that)
(As I have seen on some tutorials)
The system recognizes those jars and I am able to work with them. But when I want to run the project, I get the following error:
Information:Gradle tasks [:app:assembleDebug]
:app:preBuild
:app:compileDebugNdk UP-TO-DATE
:app:preDebugBuild
:app:checkDebugManifest
:app:preReleaseBuild
:app:prepareComAndroidSupportAppcompatV72100Library UP-TO-DATE
:app:prepareComAndroidSupportGridlayoutV72100Library UP-TO-DATE
:app:prepareComAndroidSupportMediarouterV72100Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72100Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42100Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:compileDebugJava UP-TO-DATE
:app:preDexDebug UP-TO-DATE
:app:dexDebug UP-TO-DATE
:app:processDebugJavaRes UP-TO-DATE
:app:validateDebugSigning
:app:packageDebug
Error:duplicate files during packaging of APK

C:\Users\Markus\Documents\AndroidStudiosWORKSPACE\TestProject\app\build\outputs\apk\app-debug-    unaligned.apk
Path in archive: res/values/colors.xml
Origin 1:     C:\Users\Markus\Documents\AndroidStudiosWORKSPACE\TestProject\app\libraries\datetimepicker-library.jar
Origin 2:     C:\Users\Markus\Documents\AndroidStudiosWORKSPACE\TestProject\app\libraries\MPChartLib.jar
You can ignore those files in your build.gradle:
android {
  packagingOptions {
    exclude 'res/values/colors.xml'
  }
}
Error:Execution failed for task ':app:packageDebug'.
> Duplicate files copied in APK res/values/colors.xml
File 1:     C:\Users\Markus\Documents\AndroidStudiosWORKSPACE\TestProject\app\libraries\datetimepicker-library.jar
File 2:     C:\Users\Markus\Documents\AndroidStudiosWORKSPACE\TestProject\app\libraries\datetimepicker-library.jar

It's not the first time I get this error, so I have searched for a solution for hours - vainly.
The following is my build.gradle where I have already excluded many files:
 apply plugin: 'com.android.application'

    android {
    compileSdkVersion 21
    buildToolsVersion "20.0.0"

    packagingOptions {
        exclude 'AndroidManifest.xml'
        exclude 'bin/AndroidManifest.xml'
        exclude 'bin/R.txt'
        exclude 'bin/jarlist.cache'
        exclude 'build.gradle'
        exclude 'proguard-project.txt'
        exclude 'project.properties'
    }

    defaultConfig {
        applicationId "com.nomax.gymdiary"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:support-v4:21.0.0'
    compile 'com.android.support:appcompat-v7:21.0.0'
    compile 'com.android.support:gridlayout-v7:21.0.0'
    compile 'com.android.support:mediarouter-v7:21.0.0'
    compile 'com.android.support:recyclerview-v7:21.0.0'
    compile files('libraries/datetimepicker-library.jar')
    compile files('libraries/MPChartLib.jar')
}

I'm sure that I don't have to exclude those important files (which can be seen on latest error where I also have to exclude res/values/colors.xml)
Greetings from Austria!
PS: I have exported the libs from an android project from Eclipse to a jar file. Can this be the problem?


text:
Q: TurnContext.getConversationReference: Missing Information I am writing a bot using the botbuilder npm library. I want to use proactive-messages to send notifications to a user, in a personal chat window.
Using the following code to extract conversation-reference:
const conversationRef: Partial<ConversationReference> = TurnContext.getConversationReference(activity);

Now, when I try to use the reference object returned above as an argument in the following function:
await adapter.continueConversation(convReference, async turnContext => {
        // If you encounter permission-related errors when sending this message, see
        // https://aka.ms/BotTrustServiceUrl
        await turnContext.sendActivity('This is a proactive notification');
    });

I get the following error:

error TS2741: Property 'name' is missing in type '{ id: string; aadObjectId: string; }' but required in type 'ChannelAccount'.

Is it incorrect to try sending proactive notifications to a personal chat? Or is there a workaround for this.
I am using npm botbuilder V4.10.4


text:
Q: To prevent Finder from showing .noindex files I can restrict Finder searching files by adding .noindex -extension, this thread.
However, I want hide those files in Finder search.
How can you prevent Finder from showing .noindex -files?

A: There are a variety of ways to hide things in Mac OS X. Note: if you do any of these you most likely do not need to use the .noindex extensions since files hidden from the finder will not be typically be shown in Finder Spotlight searches.

*

*chflags hidden fileToHide (as already mentioned) does this by setting OS X file attributes.

*use the Unix style period at the start of a file name .fileToHide, of course this will hide the file from the Finder and the command line.

*create a .hidden at the file system root and list the filenames of files to hide from the Finder. This was the way to do it in the first several versions of Mac OS X prior to the chflags method.

*There is also a classic Mac OS 9 file attribute that can hide files, but this should be considered highly depreciated

Note that the various hiding methods and .noindex should all work on Folders too.

A: In the command line use:
chflags hidden fileToHide
To show files again chflags nohidden ...


text:
Q: How do I set "MONTHNAME()" function as column default in MySQL? Actually I need current month name as lowercase string as default value in one of the table column;
DB table may look like Like:
name : john
joined : january

When I try to use mysql function LOWER( MONTHNAME( NOW() ) ) as defailt value this gives me error.
Btw I'm not interested in creating triggers.
any magic queries to do that?

A: From the MySQL documentation:

With one exception, enclose expression default values within parentheses to distinguish them from literal constant default values.

So, the following should work:
CREATE TABLE yourTable (
    month_name VARCHAR(12) DEFAULT (LOWER(MONTHNAME(NOW())))
    ...
)

As @Madhur has pointed out, using an expression as a default will only work from MySQL 8 onwards.

A: If you use MySQL 8.0 or later, then the answers provided by @TimBiegeleisen and @fa06 should solve the problem. In otherwise

... the default value specified in a DEFAULT clause must be a literal constant; it cannot be a function or an expression.

See details in documentation.
So, for previous versions you need to find another way. For example, you could define a trigger that sets default value for the column if the value is not specified:
CREATE TABLE MyTable (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50),
  joined  VARCHAR(12)
);

CREATE TRIGGER defaultMonth
BEFORE INSERT ON MyTable
FOR EACH ROW
SET NEW.joined = IFNULL(NEW.joined, LOWER(MONTHNAME(NOW())));

See also live example for the proposed solution.

A: You can try below
CREATE TABLE orderdata (

    order_date DATE
  , order_month VARCHAR(50) AS (lower(MONTHNAME(order_date)))

);


text:
Q: How to notify Property grid collection propery change I have a wpf application and im using winform host.
In some cases the 'SelectedItem' property is complex type that have a property from type 'List'.
How can i know from code if the collection changed? Or just know of the custom editor opened?

A: You can use a ObservableCollection<T> instead of a List to have the functionality of indicating changes to the contents of the list.
The ObservableCollection implements the interfaces INotifyCollectionChanged and
INotifyPropertyChanged to archive this behaviour.
More information to ObservableCollection on MSDN:
https://msdn.microsoft.com/de-de/library/ms668604(v=vs.110).aspx

A: If I understand well you have collection of elements, and each of them have some other collection.
In that way you could also consider using BindingList as your base collection - it implementsIRaiseItemChangedEvents - Indicates whether a class converts property change events to System.ComponentModel.IBindingList.ListChanged


text:
Q: netbeans debugging pretty display string/vector is there any way, that the debugger in netbeans directly shows me the content of string variables?
Currently, If I press on the small "+" left of the variable name it shows me things like "npos, _M_dataplus, _M_string_length ...". It would help a lot to simply show me the content of the sting instead.
Same happens if I have a vector. In this case it is really a pain to debug variables becaus I always have to search for the content...
(I use NetBeans IDE 8.2)
Thanks
image


text:
Q: PHP error reading remote file When I try to do a file('http://somewebsite.com') i get an error
"URL file-access is disabled in the server configuration"
I tried using ini_set('allow_url_fopen', 'On'); but that didn't work.
I'm using shared hosting.  Any suggestions?
All I want to do is read the html source code of a website.

A: On php version>4.3.4 and <6, you can't set allow_url_fopen in your script. Try using curl instead.

A: If your hosting allows and reads custom .htaccess files, try putting the following line to a .htaccess at the root of your project:
php_flag allow_url_fopen on
and see if it has an effect...


text:
Q: What determins the available amps in an AC to DC converters (wall wart)?
*

*Concerning the older, simple transformer, rectifier, capacitor AC to DC converters, what determines available amps (amp output)? Is it simply the thickness of the transformer wires?

*What about the lighter, smaller, more complex, more modern converters. What factor/component determines available amps (amp output) for them?

A: Wall warts are designed to meet a certain balance of cost, size, efficiency, reliability, output quality, and output power.  Each wall wart will have a different balance.  Apple might focus on size and efficiency, while Samsung might care more about cost.  The designer of the wall wart will understand the goals, the balance, that is required and design the wall wart accordingly.
There are too many designs to really go into the details about what makes one design have higher output power than another.  Suffice it to say that EVERYTHING matters.  Even the plastic case that the wall wart is inside matters.  Just like if you are designing a passenger airplane to go the farthest distance, then even the seats matter.  For a wall wart, the transformers, caps, diodes, wires, integrated circuits, inductors, resistors, MOSFETs, all matter.  You can't just change the caps and expect the whole thing to suddenly output more power.  You have to look at everything.
Let's use a car as an example.  Let's say that you have a typical car that you want to make go faster.  Of course you could replace the engine block to hold more and larger pistons.  But then you need a bigger air intake so you can burn more fuel.  And you need a bigger fuel pump.  Now you need a stronger crankshaft, to handle the power.  And a better transmission, because the old one would get destroyed under the stress.  And a better driveshaft.  And better axles.  And better wheels/tires.  And better brakes, so you can stop this.  And better suspension to handle the increased torque.  And better radiator to cool the hotter engine.  Etc.  The same is true for a wall wart-- but with electronic stuff instead of gear-head stuff.
Everything matters.

A: *

*Since you didn't specify a wall wart, I'm going to assume you mean a regulated wall wart. There is more going on inside there than a transformer. There is always rectification, filtering, and regulation. All of these things affect the current capacity of the wall wart.

*Again, you didn't specify a wallwart, so I'm going to assume SMPS. Same deal as the linear regulation, only there is even more going on inside these wall warts. No single component inside these power supplies determines the current, assuming they are well designed. A poorly designed power supply will always have some kind of bottleneck.


text:
Q: how can i create dynamically flowlayoutpanels and tabpages in my form I need to create some tabpages and flowlayoutpanels in each tab-pages dynamically in my form loaded. After that i wanna add some button in each flowlayoutpanel.
here is my code:
    Public Class Form1
    Dim tabcntrl As New TabControl
    Dim flp(4) As FlowLayoutPanel
    Dim btn As New Button
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        tabcntrl.Dock = DockStyle.Fill
        tabcntrl.Alignment = TabAlignment.Left
        Me.Controls.Add(tabcntrl)
        For i = 1 To 5
            tabcntrl.TabPages.Add("TAB" & i - 1)
            flp(i - 1).Dock = DockStyle.Fill
            tabcntrl.TabPages(i - 1).Controls.Add(flp(i - 1))
        Next
        button_adding()
    End Sub
    Private Sub button_adding()
        For i = 1 To 5
            For j = 1 To i
                btn.Text = j
                btn.Size = New Size(75, 75)
                btn.Visible = True
                flp(i - 1).Controls.Add(btn)
            Next
        Next
    End Sub
  End Class

A: Before setting the Dock property of the FlowLayoutPanel, you need to instantiate a FlowLayoutPanel.
...
tabcntrl.TabPages.Add("TAB" & i - 1)
flp(i - 1) = New FlowLayoutPanel    ' <== ADD THIS LINE
flp(i - 1).Dock = DockStyle.Fill
...


text:
Q: Is chef an overkill for my simple IT infrastructure needs? I'm a full stack developer that owns a few Ruby on Rails applications. Currently I use Capistrano to provision the few (~5) VPS where my apps run, but I'm looking for alternatives to have a more reliable automation process (Capistrano is much better suited for deployment).
The obvious choice was chef (because I already know Ruby) but after toying around a few days it's not clear that it's the best choice:
Chef client-server architecture looks like an overkill for my needs. I don't want to run a server.
I've read a book (Reliably Deploying Rails Applications) that suggest chef-solo, but when then I go to the homepage and it's says it's deprecated and I don't want to learn something that will get out of date fast.
Still I get it running, I try bundle exec knife cookbook create (version 13) and says that it doesn't work any more, that I should download chefDK.
I just installed chef by my Gemfile that was fine but ChefDK it's big, I just want something simple to reliable deploy a few boxes.
It looks like there are a lot of moving parts, stuff that is getting out of date, etc.
So, I know that Chef is great software for managing big infrastructure, but it looks like it's too complex for my use case. What do you think? Do you suggest me to proceed or try for something else (ansible is marketed as being simpler for example)? Thanks

A: There is always advantage to using orchestration for the sake of repeatability alone - doesn't matter what the scale is. Once you hook your testing\development orchestration workflow into Vagrantfiles you won't ever want to go back!
I've used both Chef and Ansible working with Rails apps in the past and it really depends on what you're going for.
What is worth mentioning though that both Chef and Puppet are intended to be agent based (as opposed to Ansible), so it's overkill if your scale is always going to be small in my opinion as there is a little bit of a learning curve to it.
So I'm going to say for your case that Ansible might be a better choice if you are mainly looking to automate infrastructure provisioning due to the fact that it's simple, agentless and runs over SSH.
That said Ansible tends to be more of a sysad tool and makes better glue, whereas Chef is better for dealing with specific nuances of development such as version control. If you're ruby developer it might be up your ally as it's code driven.
The way I'd look at it would be:
I'm using a hosting provider and want to configure a few servers, then Ansible would be my choice.
If I'm running a hosting provider, and need to manage a very large amount of servers then Puppet would be my choice.
If I'm running a sophisticated set of integrated web applications with a decent sized team of software engineers then my choice would be Chef.

A: So chef-solo is not deprecated, we're still tracking down some older docs that claim it is.
Deploying a rails app with solo and Berkshelf is pretty easy, I've got an example recipe over at https://github.com/poise/application_examples/blob/master/recipes/todo_rails.rb
As for it it's overkill, that's hard to answer. It's a lot to learn but the actual overhead of extra stuff in your stack isn't that big so it's mostly a question of if you have to time to spare to learn Chef.


text:
Q: Mailer Error: The following From address failed: Called Mail() without being connected I am using PHPMailer using SMTP to send Email. I have set everything.
But in the last I am getting error : Mailer Error: The following From address failed: Email Address : Called Mail() without being connected
I came to know to set Order of coding, I also did it but still same error. Please help me to solve this issue.

My Code :
<?php

require 'PHPMailer.php';

error_reporting(E_ALL);
ini_set('display_errors', '1');

$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.live.com";
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = "example@outlook.com";
$mail->Password = "password";
$mail->SMTPSecure = 'tls';

$mail->From = "info@neelcomputech.com";
$mail->FromName = $name;
$mail->AddAddress("info@neelcomputech.com");

$mail->IsHTML(true);

$mail->Subject = $subject;

$mail->Body = $mail_body = " ";
$mail_body = "Hello Admin,

You have got email from your website.

";
$mail_body .= '
';
$mail_body .= "

                  Name
                 :
                 $name

                  Email
                 :
                 $email

                  Message
                 :
                 $message

                 ";

if(!$mail->Send())
{
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
else
{
    echo 'success';
}

?>

A: <?php

    require 'PHPMailer.php';

    error_reporting(E_ALL);
    ini_set('display_errors', '1');

    $name = $_POST["name"];
    $email = $_POST["email"];
    $subject = $_POST["subject"];
    $message = $_POST["message"];

    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->Host = "smtp.neelcomputech.com"; // Your SMTP PArameter
    $mail->Port = 587; // Your Outgoing Port
    $mail->SMTPAuth = true; // This Must Be True
    $mail->Username = "info@neelcomputech.com"; // Your Email Address
    $mail->Password = "YOUR PASSWORD"; // Your Password
    $mail->SMTPSecure = 'tls'; // Check Your Server's Connections for TLS or SSL

    $mail->From = "info@neelcomputech.com";
    $mail->FromName = $name;
    $mail->AddAddress("info@neelcomputech.com");

    $mail->IsHTML(true);

    $mail->Subject = $subject;

    $mail->Body = $mail_body = " ";
    $mail_body = "Hello Admin,

You have got email from your website.

";
    $mail_body .= '
';
    $mail_body .= "

                      Name
                     :
                     $name

                      Email
                     :
                     $email

                      Message
                     :
                     $message

                     ";

    if(!$mail->Send())
    {
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    }
    else
    {
        echo 'success';
    }

    ?>

You have to use your own parameters, in your smtp authentication.
Also you can check other mail server's smtp parameters on PHPMailer's Website:
phpmailer.worxware.com/index.php?pg=tip_srvrs

A: You could resolve this by using the following code:
$mail->Host = 'relay-hosting.secureserver.net';

A: It took me a lot of digging to figure out the CentOS 7 disables SMTP connections by default, and its not through Firewalld.
Try running these lines if you run into this " Mailer Error: The following From address failed: " and "Called Mail() without being connected."
sudo setsebool -P httpd_can_sendmail 1
sudo setsebool -P httpd_can_network_connect 1
Thanks to the following web article:
https://gistpages.com/posts/phpmailer_smtp_error_failed_to_connect_to_server_permission_denied_13_fix


text:
Q: In C#, what does an expression x = y == z stand for? Please forgive me the noob question, but C# is not my native language. In code I took over, I stumbled upon
var success = true;
success = Upload.Status == FileStatus.Ok;

In there, FileStatus is of type enum, somewhere custom defined. I guess, success is essentially non-nullable Boolean. I think that the 2nd line sets success to false if (and only if) Upload.Status == FileStatus.Ok, which would also induce that the latter two variables should be of same type.
Could you please let me know, whether my hypotheses are correct? Also: How is such a construct called? What is it short for?

A: success is going to be a bool.
It is initialized with true, but  that should be unessesary.
var success = true;

And will then be set to the result of (Upload.Status == FileStatus.Ok) which is a bool.
success = Upload.Status == FileStatus.Ok;

Think of it as success = (Upload.Status == FileStatus.Ok); if that helps.
And yes, it took me a moment to parse it too. I have a profound dislike for people trying to save lines at the cost of readability. I would use this:
if(Upload.Status == FileStatus.Ok)
    success = true;
else
    success = false;

Maybe use the shorter if syntax.

A: It's assigning the result of an expression to a variable, same as var x = 1 + 2; just that in this case the expression is of type bool.
Needlessly verbose, this would be the same:
bool success;
if (Upload.Status == FileStatus.Ok)
{
    success = true;
}
else
{
    success = false;
}

A: Upload.Status == FileStatus.Ok evaluates to a bool, either true or false. success will be assigned the result of that evaluation.
It's no more mystical than var sum = 4 + 5; resulting in sum being assigned a value of 9.


text:
Q: Angular 2 http delete doesn't make network requests Other verbs work fine to my api but delete doesn't fire anything in the network tab on chrome Dev tools

A: I guess that you forgot to subscribe on the request. Observables are lazy so you need to subscribe to actually execute them. It must be done even if you don't expect a payload in the response.
Something like that:
this.http.delete().subscribe((res) => {
});


text:
Q: What does "If she smokes, she pokes" exactly mean? What does part

she pokes

of phrase

If she smokes, she pokes

exactly mean?

A: Women smokers were considered to be more promiscuous - mass culture with the advent of the roaring Twenties, but traveling across the Americas prior to that through literature post Civil War (see Elmer Gantry)  - which was really an American version of an idea that had been circulating via French Postcards visually.
She smokes, she will have sex

A: The "she pokes" part means "she engages in sexual intercourse of a heterosexual variety".  There is an implication of doing so more readily or enthusiastically than may be otherwise expected.
You may wish to consult Urban Dictionary on the topic.  But then again you may not.

A: Actually, the phrase should be, "if she smokes, she ALLOWs poking."
If she is "loose" with regard to smoking, she is likely to be "loose" regarding other matters such as sex.
But the original phrase is an abbreviation.

A: Basically it means if there is no smoke from your exhaust, there will be no poke from your engine!


text:
Q: Toggle close outside click I am using toggle class for dd & dt it is working fine but my problem is if user click out side i want to close that toggle. How to achive this ?
 <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <script type="text/javascript">
    jQuery=$.noConflict();
    jQuery(document).ready(function() {
        jQuery('.navigation dd').hide();

        jQuery('.navigation dt').click(function(){
                jQuery(this).next('dd').slideToggle('slow');
                jQuery(this).toggleClass('glace_navigationlayer-collapsed');

            });

     });
    </script>

A: You can also try -- what DBS has is proper, ( he posted in a comment ), imho.
//clicking on the body, closes the toggleitem
jQuery(document.body).bind('click.closedd', function() {
    jQuery('.navigation dd').hide();
});

// clicking on the toggle item, won't trigger the click on the body
// that we set up above.
jQuery('.navigation dd').bind('click.closedd', function(e) {
    e.stopPropagation();
});

A: You need to listen for clicks on the <body> and then check to make sure the target is outside of the navigation component.
jQuery('body').on('click', function(evt) {
  var $target = $(evt.target);
  if ( !$target.closest('.navigation').length ) {
    // code to collpase the nav menu
  }
});

I would also recommend refactoring your nav code to use separate expand and collapse functions instead of relying on slideToggle and toggleClass.
Good luck!

A: Not too sure about the requirements, but you can try achieving the above on mouseenter and mouseleave events.
However, if you have to implement the above functionality only on click, then you will have to wire the click event on a container that covers the entire html body.


text: Q: Redirect / rewrite domain in Wildfly 9 How can I configure Wildfly to redirect from olddomain.com to newdomain.com? I know this can be done in apache through htaccess, but I have no idea which configuration files need to be edited in Wildfly and how to configure them.


text:
Q: MySQL (id >= N AND col2 IS NULL) query unexpectedly slow for large N We are using MySQL 5.5.42.
We have a table publications containing about 150 million rows (about 140 GB on an SSD).
The table has many columns, of which two are of particular interest:

*

*id is primary key of the table and is of type bigint

*cluster_id is a nullable column of type bigint
Both columns have their own (separate) index.
We make queries of the form
SELECT * FROM publications
WHERE id >= 14032924480302800156 AND cluster_id IS NULL
ORDER BY id
LIMIT 0, 200;

Here is the problem: The larger the id value (14032924480302800156 in the example above), the slower the request.

In other words, requests for low id value are fast (< 0.1 s) but the higher the id value, the slower the request (up to minutes).
Everything is fine if we use another (indexed) column in the WHERE clause. For instance
SELECT * FROM publications
WHERE inserted_at >= '2014-06-20 19:30:25' AND cluster_id IS NULL
ORDER BY inserted_at
LIMIT 0, 200;

where inserted_at is of type timestamp.
Edit:
Output of EXPLAIN when using id >= 14032924480302800156:
id | select_type | table        | type | possible_keys      | key        | key_len | ref   | rows     | Extra
---+-------------+--------------+------+--------------------+------------+---------+-------+----------+------------
1  | SIMPLE      | publications | ref  | PRIMARY,cluster_id | cluster_id | 9       | const | 71647796 | Using where

Output of EXPLAIN when using inserted_at >= '2014-06-20 19:30:25':
id | select_type | table        | type | possible_keys          | key        | key_len | ref   | rows     | Extra
---+-------------+--------------+------+------------------------+------------+---------+-------+----------+------------
1  | SIMPLE      | publications | ref  | inserted_at,cluster_id | cluster_id | 9       | const | 71647796 | Using where

A: There is some guesswork involved about MySQL using indexes in the wrong order. PRIMARY index seems to be treated in a completely different way than the others.
In a query with a primary key condition indexes PRIMARY and on cluster_id can be used. For some reason, MySQL ignored PRIMARY index and looks at an index on cluster_id first, where you have a condition: it should be NULL. That leaves us with a huge potentially unordered (NULLs everywhere!) set of rows to be filtered by id.
With the next query, however, it's different: PRIMARY index cannot be used at all, so MySQL figures what to use in a better way, apparently using an index on inserted_at first without any hints.
What it should actually do in first query is take PRIMARY index first (tell it to do so). I am not a MySQL user, all my guesswork is backed only by my own understanding of internal data structures. I don't know whether it can apply an index on cluster_id on top of the results, but creating a composite index and comparing performance with and without it may give clues on whether it's used.

A: The performance issue is most likely happening because you only have separate indexes for columns id and cluster_id, but not an index on both these columns simultaneously.
Maybe for larger ids, it is more rare that cluster_id matches the requested value (NULL)? In that case for larger ids the database may need to traverse more records in order to select the requested 200 with cluster_id IS NULL.
If you had a single index on both columns, the database wouldn't need to traverse that many records because it would know which records satisfy the 2 search criteria simultaneously.


text:
Q: Drupal - error installing module "entity" I have a Drupal installation within a Docker container, with Composer and Drush installed. I'd like to install the Entity-API module (https://www.drupal.org/project/entity), and I start off with:
composer require drupal/entity
This gives me an error:
Using version ^0.1.0 for drupal/entity
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: drupal/core[8.5.6, 8.0.x-dev].
    - Can only install one of: drupal/core[8.0.x-dev, 8.5.6].
    - Can only install one of: drupal/core[8.0.x-dev, 8.5.6].
    - drupal/entity 0.1.0 requires drupal/core <8.1.0 -> satisfiable by drupal/core[8.0.x-dev].
    - Installation request for drupal/entity ^0.1.0 -> satisfiable by drupal/entity[0.1.0].
    - Installation request for drupal/core (locked at 8.5.6, required as ~8.5.3) -> satisfiable by drupal/core[8.5.6].

Installation failed, reverting ./composer.json to its original content.

My Drupal version is 8.5.6 and I'm using the latest version of Composer, installed from https://getcomposer.org/installer
How would I get this installed using Composer? Tx

A: Use --update-with-all-dependencies switch:
composer require drupal/entity --update-with-all-dependencies

*

*--update-with-all-dependencies: Also update dependencies of the newly required packages, including those that are root requirements.

  https://getcomposer.org/doc/03-cli.md#require


text:
Q: Can't get Tilestache working on Apache (mod_wsgi) Trying to get a tileserver running on Ubuntu 14.04 with TileStache and Apache.
No problem running the TileStache development server (tilestache-server.py) or the uWSGI example from the API docs:
uwsgi --http :8080 --eval 'import TileStache; application = TileStache.WSGITileServer("/etc/TileStache/tilestache.cfg")'

However, I can't get it to serve tiles with mod_wsgi through Apache (2.4.7). Followed the instructions here: https://github.com/TileStache/TileStache/issues/67:
Created wsgi file (/var/www/tilestache/tilestache.wsgi, owned by Apache with 0750 permissions) containing:
import os, TileStache
application = TileStache.WSGITileServer('/etc/TileStache/tilestache.cfg')

Following those instructions, added:
WSGIScriptAlias /tilestache /var/www/tilestache/tilestache.wsgi

To my Apache config. Navigating to that alias on any of the defined virtualhosts returns a 403 - Forbidden.
I've also tried replacing that line with the following, but returns the same 403:
WSGIDaemonProcess tilestache
WSGIProcessGroup tilestache
WSGISocketPrefix /var/run/wsgi
WSGIScriptAlias /tilestache /var/www/tilestache/tilestache.wsgi

I've also tried moving those lines inside of a virtualhost, with the same result.
Note: I've changed the tilestache.cfg to use the test/simple cache (not actually caching anything).


text:
Q: C++ std::map - thread safe if one thread writes and another reads with always different keys? Thread A writes to the std::map with key C
Thread B reads from std::map with key D
If it is always guaranteed that the keys do not overlap, is this thread safe?
Since std::map uses a tree-structure inside, I could imagine that there could be problems to read from it while it is being mutated.
If std::map does not work, would std::unordered_map be better?

A: *

*If by writing you mean changing the value of an already existing
entry associated with key C, then the answer is (I believe) YES.

*If by writing you mean (potentially) inserting new elements (or removing them), then the answer is definitively NO.

Although not an authoritative source, www.cplusplus.com usually has a section about potential data races for each function.


text:
Q: Advice on ASP.NET MVC to Java migration? I'm an ASP.NET developer trying to learn Java web dev. I would like to migrate a small ASP.NET MVC site to Java.  I have the ASP.NET code and the SQL Server database.  I'm comfortable with Netbeans and Eclipse.  I know the basics of servlets and JSPs.  I'm wondering whether it would make sense to use a web framework instead of using JSP/servlets directly.
I'm stuck at what Java web framework to use.  I would prefer a framework that's MVC based, can generate a data layer quickly based on an existing database schema and has an easy learning curve.  I've peeked at Struts2 and JSF. Both seem a bit complicated but if I spend more time on it, perhaps they be more approachable...?
Are there other frameworks I should explore?  Any recommendations?

A: I'm kinda Spring Framework fan, so I would recommend Spring MVC. I warn you - it isnt easy.   You could reuse JSP as view layer, and switch later to Freemarker/Velocity. And maybe some Hibernate later. There is cool plugin pack for Eclipse from Spring, called Spring Tool Suite - makes development easier. And page with examples: http://www.springbyexample.org/ :)


text:
Q: PowerShell, how to handle a page timeout from an Invoke-WebRequest? I found that a site that I wanted to parse was down today when I went there to download a file.
The code I ran is:
$url = "https://notepad-plus-plus.org/downloads"
$page = Invoke-WebRequest -uri $url -UseBasicParsing

How can I intercept and handle this?

*

*Is there a way to gracefully time out my request after 2 seconds if it does not get a response (which could be from the site being down or from my own internet having problems)?

*What might be the best way to detect if what was returned is "connection timeout junk" as opposed to useful data that I can work with?

$url = "https://notepad-plus-plus.org/downloads"   # Final url will be like: # https://github.com/notepad-plus-plus/notepad-plus-plus/releases/download/v8.4.6/npp.8.4.6.portable.x64.zip
try {
    $page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3
}
catch {
    if ($_.Exception.Response.StatusCode -band 522) { "bad!"}
}

A: You should just call the current default error variable exception message/detail.
$url = "https://notepad-plus-plus.org/downloads"
try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop}
catch {$Error[0].Exception}
# Results
<#
The operation has timed out.
#>

$url = "https://notepad-plus-plus.org/downloads"
try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -ErrorAction Stop}
catch {$Error[0].Exception}
# Results
<#
The remote server returned an error: (522).
#>

Thus do what you want based on that error message.
$url = "https://notepad-plus-plus.org/downloads"
try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -ErrorAction Stop}
catch
{
    If (($Error[0].Exception) -match '522')
    {Write-Warning  -Message 'Bad stuff happened. Now, go do stuff'}
}
# Results
<#
WARNING: Bad stuff happened. Now, go do stuff
#>

Update
Timeout check.
$timer = [Diagnostics.Stopwatch]::StartNew()
$url = "https://notepad-plus-plus.org/downloads"
try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop}
catch
{
    $Error[0].Exception

    If (($Error[0].Exception) -match 'timed out')
    {Write-Warning  -Message 'Timeout occurred. Do you want to set a differnet timeout'}
}
$timer.Elapsed.TotalSeconds
# Results
<#
The operation has timed out.
WARNING: Timeout occurred. Do you want to set a differnet timeout
3.0225485
#>


text:
Q: How To Send Message To Specific User In Blazor Server Using SignalR? I have implemented a simple public chat room system using blazor server and signalR with database to store username and message. IN system user join chat just by entering its name and the UI for chatting appears.
Now, what I want is to add another feature where message can be sent to specific user that is present in that public chat room.
Any help will be great and Thank you.

Below is my code for public chat room .
Below is my Hub
    public class Chat:Hub
    {
        public async Task SendMessage(Message message)
        {
            await Clients.All.SendAsync("Receiver", message);
        }
    }

Below is code to save username and message in database
    public string MsgBody { get; set; }
    public string UserName { get; set; }
    public Message chatmsg { get; set; } = new Message();
    public bool isChatting = false;
    public string errorMsg;
    public List<Message> messages = new List<Message>();
    public List<Message> messagesList = new List<Message>();
    public HubConnection hubConnection;
    [Inject]
    public NavigationManager NavigationManager { get; set; }
    [Inject]
    public MainService mainService { get; set; }
    public async Task SendAsync()
    {
        chatmsg.UsrName = UserName;
        chatmsg.MessageBody = MsgBody;
        mainService.SaveMessage(chatmsg);
        await hubConnection.SendAsync("SendMessage", chatmsg);
        MsgBody = string.Empty;
        chatmsg = new Message();
    }

Below is code to load data
    public async Task Chat()
    {
        if (string.IsNullOrWhiteSpace(UserName))
        {
            errorMsg = "Enter your name";
        }
        try
        {
            isChatting = true;
            messagesList.Clear();
            hubConnection = new HubConnectionBuilder().WithUrl(NavigationManager.ToAbsoluteUri("/chat")).Build();
            hubConnection.ServerTimeout = TimeSpan.FromMinutes(60);
            hubConnection.On<Message>("Receiver", BroadcastMessage);
            await hubConnection.StartAsync();
            LoadMessage();
            await ChatJoinLeftMessage($"[Notice] {UserName} joined chat room.");
        }
        catch (Exception e)
        {

            errorMsg = $"ERROR: Failed to start chat client: {e.Message}";
            isChatting = false;
        }
    }
    private void BroadcastMessage(Message message)
    {
        bool isMine = message.UsrName.Equals(UserName, StringComparison.OrdinalIgnoreCase);
        messagesList.Add(new Message(message.UsrName, message.MessageBody, isMine));
        StateHasChanged();
    }

    private void LoadMessage()
    {
        messages = mainService.GetAllMessages();
        foreach (var item in messages)
        {
            bool isMine = item.UsrName.Equals(UserName, StringComparison.OrdinalIgnoreCase);
            messagesList.Add(new Message(item.UsrName, item.MessageBody, isMine));
        }
    }

Below is my UI
@if (!isChatting)
{

Enter your name to start chatting:

        <input @bind="UserName" type="text" class="form-control my-input">

            <button class="btn btn-outline-secondary" type="button" @onclick="@Chat"> Chat!</button>

   if (errorMsg != null)
   {

        @errorMsg

   }
}
else
{

    you are connected as @UserName
    <button class="btn btn-sm btn-warning ml-md-auto" @onclick="@DisconnectAsync">disconnect</button>

    @foreach (var item in messagesList)
    {
        @if (item.IsNotice)
        {

@item.MessageBody

        }
        else
        {

@item.UsrName

@item.MessageBody

        }
    }

    <textarea class="input-lg" placeholder="enter your comment" @bind="MsgBody"></textarea>
    <button class="btn btn-default" @onclick="()=>SendAsync()">Send</button>

}

A: This is a complete solution how to do that. You can download a working and updated sample of the code from Github:
Note: The purpose of this answer is not how to create a SignlR app, and how to manage users. This is shown in the docs and many other tutorials. But one thing is lacking and it is how to protect the SignalR hub's end points, and how to make the user's claims available in the hub in Blazor Server App. I did not find a single example of dong it with Blazor Server App. I sought some hints from the Blazor team, but to no avail...
Some clarification
Note: Authenticating your users in the front-end of your Blazor Server App will not make you authorized to access protected end-points on the Hub. You should treat the Hub as you treat a Web Api end-points, which requires you to pass an access token when you perform HTTP calls to it. As for instance, if you want to retrieve data from the WeatherForecastController in a Web Api to the FetchData page employing the HttpClient service, you need to pass the access token in the Authorization header
When you use WebAssembly app with API authentication, you can pass the access token to the Hub when the hub connection is created. It's easy, the docs has a sample code demonstrating this, and actually you don't have much to do in order to secure the Hub, and access......................, no even with this there are some issues to deal with because only the UserIdentifier can be accessed in the Hub, not all the user's claims.
However, the answer here is about Blazor Server App, and the solution is to pass the security cookie (".AspNetCore.Identity.Application") to the hub. So, the first step to solve the issue is to capture the cookie from the HttpContext before the Blazor SPA is being rendered, and pass the cookie to the Blazor App as a parameter sent to the App component. Now that the cookie is available in the Blazor App you can access it from the Chat page and pass it to the Hub. Note that, unlike the WebAssembly App sample with SignalR, all the ClaimPrincipal object is available in the Hub, and you can access all its claims, as for instance:
var user = Context.User.Identity.Name
var userid = Context.UserIdentifier

_Host.cshtml
    @{
        // Capture the security cookie when the the initial call
        // to the Blazor is being executed. Initial call is when
        // the user type the url of your Blazor App in the address
        // bar and press enter, or when the user is being redirected
        // from the Login form to your Blazor SPA
        // See more here: https://stackoverflow.com/a/59538319/6152891
         var cookie =
     HttpContext.Request.Cookies[".AspNetCore.Identity.Application"];

    }

     @* Pass the captured Cookie to the App component as a paramter*@
    <component type="typeof(App)" render-mode="Server" param-
       Cookie="cookie" />

App.razor
@inject CookiesProvider CookiesProvider

@* code omitted here... *@

@code{

    [Parameter]
    public string Cookie { get; set; }

    protected override Task OnInitializedAsync()
    {
        // Pass the Cookie parameter to the CookiesProvider service
        // which is to be injected into the Chat component, and then
        // passed to the Hub via the hub connection builder
        CookiesProvider.Cookie = Cookie;

        return base.OnInitializedAsync();
    }
}

CookiesProvider.cs (Complete code)
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SignalRServerIdentityAuthentication
{
    public class CookiesProvider
    {
        public string Cookie { get; set; }
    }
}

Startup.ConfigureService
 services.AddScoped<CookiesProvider>();
 services.AddSignalR();

Startup.Configure
 app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapHub<ChatHub>("/chatHub");
                endpoints.MapFallbackToPage("/_Host");
            });

Note that the NavMenu contain an AuthorizeView component the object of which is to prevent a user from accessing the Chat component, unless she has been authenticated. Note also that the Chat page is protected with the Authorize attribute.
NavMenu.razor

            <NavLink class="nav-link" href="fetchdata">
                 Fetch data
            </NavLink>

        <AuthorizeView>

                <NavLink class="nav-link" href="chat">
                     Chat
                </NavLink>

        </AuthorizeView>

Chat.razor (Complete code)
    @page "/chat"

    @attribute [Authorize]

@using Microsoft.AspNetCore.SignalR.Client
@using Microsoft.AspNetCore.SignalR

@using SignalRServerIdentityAuthentication.Hubs

@inject NavigationManager NavigationManager

@using System.Net.Http
@using System.Net.Http.Json

@using System;

@using System.Net.Http.Headers;
@using System.Threading.Tasks;
@using Microsoft.AspNetCore.Http.Connections;
@using System.Net

@implements IAsyncDisposable

@messageForBoard

    User:
    @userName

    Message:
    <input onfocus="this.select();" @ref="elementRef" id="messageInput" @bind="messageInput" class="form-control my-input"/>

<button @onclick="Send" disabled="@(!IsConnected)" class="btn btn-outline-
     secondary">Send Message</button>

@if (UserList != null)
    {
        <select id="user-list" @bind="selectedUser">
            <option value="">All.....</option>
            @foreach (var user in UserList)
            {
                <option value="@user">@user</option>
            }
        </select>
    }

    Public Message Board:

       @foreach (var message in messages)
       {

@message

       }

    Private Message Board:

       @foreach (var message in privateMessages)
       {

@message

       }

@code {
    HubConnection hubConnection;
    private List<string> messages = new List<string>();
    private List<string> privateMessages = new List<string>();
    private string messageForBoard;
    private string userName;
    private string messageInput;
    private string selectedUser;
    private List<string> UserList;

    private ElementReference elementRef;

    [Inject]
    public CookiesProvider CookiesProvider { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var container = new CookieContainer();
        var cookie = new Cookie()
         {
             Name = ".AspNetCore.Identity.Application",
             Domain = "localhost",
             Value = CookiesProvider.Cookie
         };

         container.Add(cookie);

      hubConnection = new HubConnectionBuilder()
    .WithUrl(NavigationManager.ToAbsoluteUri("/chathub"), options =>
    {
        // Pass the security cookie to the Hub. This is the way to do
        // that in your case. In other cases, you may need to pass
        // an access token, but not here......
        options.Cookies = container;
    }).Build();

        hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            var encodedMsg = $"{user}: {message}";
            messages.Add(encodedMsg);
           InvokeAsync(() => StateHasChanged());
        });

        hubConnection.On<string>("ReceiveUserName", (name) =>
        {
            userName = name;

            InvokeAsync(() => StateHasChanged());
        });

         hubConnection.On<string>("MessageBoard", (message) =>
        {
            messageForBoard = message;

           InvokeAsync(() => StateHasChanged());
        });

        hubConnection.On<string, string>("ReceivePrivateMessage", (user, message) =>
        {
            var encodedMsg = $"{user}: {message}";
            privateMessages.Add(encodedMsg);

            InvokeAsync(() => StateHasChanged());
        });

        hubConnection.On<List<string>>("ReceiveInitializeUserList", ( list) =>
        {
            UserList = list ;

            InvokeAsync(() => StateHasChanged());
        });

        await hubConnection.StartAsync();
        await hubConnection.InvokeAsync("InitializeUserList");

    }
    protected override void OnAfterRender(bool firstRender)
    {
         elementRef.FocusAsync();
    }

   async Task Send() => await hubConnection.SendAsync("SendMessage",
                                       selectedUser, messageInput);
    public bool IsConnected => hubConnection.State ==
                                      HubConnectionState.Connected;

    public void Dispose()
    {
       hubConnection.DisposeAsync();
    }

    public async ValueTask DisposeAsync()
    {
        await hubConnection.DisposeAsync();
    }
}

Note that in order to pass a private message you need to have the UserIdentifier, but you'll also need to associate the user you want to post a private message with the UserIdentifier. You can simply store a list of UserIdentifiers in the Chat, and pass the reiured one. This of course poses some security risks and should be avoided. See my code how I deal with this. The user can only view a list of user names (yes, these are the emails of the connected users. Recall that in the database the UserName colum contains the user's email). You can of course change this to a more displayable values; your display name can be first name + last name, etc. It's up to you. Just remeber that you'll need to add a new claim for this. How to do that merits a new question...
Hubs/ChatHub.cs (Complete code needs some cleaning of unnecessary using statements)
    using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.IdentityModel.Tokens;

using Microsoft.IdentityModel;

using System.Net.Http;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Authentication;
using System.Net.Http.Json;

namespace SignalRServerIdentityAuthentication.Hubs
{
    [Authorize()]
    public class ChatHub : Hub
    {
        private static List<ConnectedUser> connectedUsers = new List<ConnectedUser>();
        public async Task InitializeUserList()
        {
            var list = (from user in connectedUsers
                       select user.Name ).ToList();

            await Clients.All.SendAsync("ReceiveInitializeUserList", list);
        }
        public async Task SendMessage(string userID, string message)
        {
            if (string.IsNullOrEmpty(userID)) // If All selected
            {
                await Clients.All.SendAsync("ReceiveMessage", Context.User.Identity.Name ?? "anonymous", message);
            }
            else
            {
                var userIdentifier = (from _connectedUser in connectedUsers
                                      where _connectedUser.Name == userID
                                      select _connectedUser.UserIdentifier).FirstOrDefault();

                await Clients.User(userIdentifier).SendAsync("ReceivePrivateMessage",
                                       Context.User.Identity.Name ?? "anonymous", message);
            }

        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {

            var user = connectedUsers.Where(cu => cu.UserIdentifier == Context.UserIdentifier).FirstOrDefault();

            var connection = user.Connections.Where(c => c.ConnectionID == Context.ConnectionId).FirstOrDefault();
            var count = user.Connections.Count;

            if(count == 1) // A single connection: remove user
            {
                connectedUsers.Remove(user);

            }
            if (count > 1) // Multiple connection: Remove current connection
            {
                user.Connections.Remove(connection);
            }

            var list = (from _user in connectedUsers
                        select new { _user.Name }).ToList();

           await Clients.All.SendAsync("ReceiveInitializeUserList", list);

           await   Clients.All.SendAsync("MessageBoard",
                      $"{Context.User.Identity.Name}  has left");

            // await Task.CompletedTask;

        }

        public override async Task OnConnectedAsync()
        {
            var user = connectedUsers.Where(cu => cu.UserIdentifier == Context.UserIdentifier).FirstOrDefault();

            if (user == null) // User does not exist
            {
                ConnectedUser connectedUser = new ConnectedUser
                {
                    UserIdentifier = Context.UserIdentifier,
                    Name = Context.User.Identity.Name,
                    Connections = new List<Connection> { new Connection { ConnectionID = Context.ConnectionId } }
                };

                connectedUsers.Add(connectedUser);
            }
            else
            {
                user.Connections.Add(new Connection { ConnectionID = Context.ConnectionId });
            }

            // connectedUsers.Add(new )

            await Clients.All.SendAsync("MessageBoard", $"{Context.User.Identity.Name}  has joined");

            await  Clients.Client(Context.ConnectionId).SendAsync("ReceiveUserName", Context.User.Identity.Name);

        }
  }
}

Hubs/ConnectedUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SignalRServerIdentityAuthentication.Hubs
{
    public class ConnectedUser
    {
        public string Name { get; set; }
        public string UserIdentifier { get; set; }

        public List<Connection> Connections { get; set; }
    }
    public class Connection
    {
         public string ConnectionID { get; set; }

    }
}

A: There are two ways I know of.

*

*You need to keep a record of the users ConnectionId and map that to the User on the server.

Clients.Client(ConnectionId).SendAsync(...);

*When a user connects to the hub put them in a Group that is only for them. For example use their userId as the Group name. Then you can broadcast to that group and only that user will receive the message.

 Clients.Group($"userId").SendAsync(...);

Override OnConnectedAsync() on the hub to set up either method. Dont forget to override OnDisconnectedAsync() to tidy up any state variables or storage on disconnect. If done correctly this also has the benefit of tracking who is connected.
Use the [Authorize] attribute on the hub. See here for how with WASM.
The following code may help as well. (Hub)
var connectionId = Context.ConnectionId;

var userId = Context.UserIdentifier;
var applicationUser = await userManager.FindByIdAsync(userId);

IMHO: For security reasons I do not send the other users details to the client other than their display name. This is why I use [Authorize] attribute. Either technique obfuscates the other users details and connection to the hub.
You could simply just add another property to your Message class to identify the intended recipient of the message and if its blank send to all. Then in your hub use this property to choose between the broadcast methods.


text:
Q: F# - convert Array to list I am reading a file into an array like follows (note I know this is bad code):
let filename = if argv.[0] != null then argv.[0] else System.Console.ReadLine()
let data = File.ReadAllLines(filename)

I want to perform an F# map onto the data returned in that above line. My problem is that I can only perform map on n F# list, and not the System.String[] that File.ReadAllLines() returns. Can I convert a standard .Net array into an F# list. I'm sure that I could just read the file differently, or labor through manually copying the array contents to a list, but it would be a lot easier if there was a simple way to do this.

A: Since File.ReadAllLines returns an array, you can use Array.map on it. It works the same way as List.map.
Another option is Seq.map, since arrays also implement the seq 'a (IEnumerable<T>) interface.
As others have pointed out, you can also convert the array to a list using Array.toList or List.ofArray, but be aware that this operation traverses the array and copies it to a list (hence there's a small overhead involved in doing so).

A: You can use Array.toList to do that.
let data2 = data |> Array.toList

Or you can use List.ofArray
let data2 = data |> List.ofArray

You can also do Array.map instead of List.map and in that case you might not need to map to list at all.


text:
Q: What is the technical relation between a delegate (function pointer, which is written as lambda expression) and LINQ? I understand that:

*

*Delegate is a function pointer and useful to pass a function as a parameter so that the function can be invoked from within another function.

*Anonymous function means a function without a name.

*Lambda expression is a short form syntax to write an anonymous function.
Today while learning about LINQ I came across an example which suggests that the below anonymous method is the same as the subsequent code snippet (lambda expression):
delegate(Student s) { return s.Age > 12 && s.Age < 20; };

is same as:
s => s.Age > 12 && s.Age < 20

What is the technical relation between a delegate (function pointer, which is written as lambda expression) and LINQ?
Another example is as follows:
Func<Student,bool> isTeenAger = delegate(Student s) {
                                    return s.Age > 12 && s.Age < 20;
                                };

var filteredResult = from s in studentList
                     where isTeenAger(s)
                     select s;

versus
public static void Main()
{
    var filteredResult = from s in studentList
                         where isTeenAger(s)
                         select s;
}

public static bool IsTeenAger(Student stud)
{
    return stud.Age > 12 && stud.Age < 20;
}

Both the above codes return same result (first code segment is delegate function, where as the second code segment is a normal function).


text:
Q: How do I find out where emacs 24 (OSX) puts my aspell corrections? I would like to see if it's possible to back them up into github with the rest of my dotfiles.
I searched the config options, but am only seeing the default dictionaries used. I'd like to know where my custom word spelling corrections are being saved at.
I've found that by evaluating ispell-personal-dictionary, I see nil. This means

the spelling program looks for a personal dictionary in a default location.

A: Check in your home directory, specifically, .aspell.en.prel, and .aspell.en.pws.


text:
Q: Able to get response but not in display I wrote a python code for the dialog flow using the flask and webhook. I am able to get the response but it not displayed in the dialog flow. This code running perfectly.
CODE:
# import os
import json
# import urllib
import datetime
from config import Configuration
from swe_commands import SweCommands
from flask import Flask, request, make_response

# Flask application should start in global layout
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)
    print "Request:"
    print json.dumps(req, indent=1)

    res = make_webhook_result(req)
    res = json.dumps(res, indent=1)
    print "Response:"
    print res

    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'

    return r

def make_webhook_result(req):
    # if req.get("queryResult").get("action") != "nakshatra":

    #     return {}

    swe_path = Configuration.swe_path()
    date_and_time = str(datetime.datetime.now())[:19]
    panchang_dictionary = SweCommands.find_panchang(swe_path, date_and_time)

    result = req.get("queryResult")
    parameters = result.get("parameters")
    angam = parameters.get("nakshatra")

    nakshatra = panchang_dictionary[angam]

    speech = "Current nakshatra is %s" % nakshatra
    source = "Panchangam"

    output = {'speech': speech, "displayText": speech, "source": source}

    return output

if __name__ == '__main__':
    port = 5000
    print "Starting app in port %s" % port
    app.run(debug=True, port=port, host='127.0.0.1')

REQUEST:
**{
 "queryResult": {
  "fulfillmentMessages": [
   {
    "text": {
     "text": [
      ""
     ]
    }
   }
  ],
  "allRequiredParamsPresent": true,
  "parameters": {
   "nakshatra": "nakshatra"
  },
  "languageCode": "en",
  "intentDetectionConfidence": 0.6725314,
  "action": "nakshatra",
  "intent": {
   "displayName": "PanchangFind",
   "name": "projects/my-project-1536557558293/agent/intents/6d1d46bf-3787-48cd-9b45-0766d5f2b107"
  },
  "queryText": "What is nakshatra"
 },
 "originalDetectIntentRequest": {
  "payload": {}
 },
 "session": "projects/my-project-1536557558293/agent/sessions/08857865-1d08-2eef-5d4f-83b92107f09b",
 "responseId": "2137da9d-23a9-4735-aec2-7adb7ae52d85-9cc28bb4"
}**

RESPONSE:
**{
 "displayText": "Current nakshatra is Shravana",
 "speech": "Current nakshatra is Shravana",
 "source": "Panchangam"
}**

But it not get displayed in the dialog flow panel? Whether I have to set any parameters for dialog flow panel to receive the response in a dialog flow. Please let me know.

A: I got an answer to this. When we use V1 in dialog flow, the response key is displayText. But in V2 the response key is fulfillmentText. When I added the response key in this name it able to detect the output.


text:
Q: Floating Action button is not showing properly The Floating Action Button is not showing properly in the Android Studio layout editor but it shows properly in-app.
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.Book_Fragment">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="250dp"
    android:scaleType="centerCrop"
    android:src="@drawable/ic_launcher_background"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/floatingActionButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:src="@drawable/fav_selector"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView"
    app:layout_constraintVertical_bias="0.047" />

It seems like this in layout editor of the android studio:
Floting Action Button Here Image


text:
Q: On ARM, how to save the sp_usr register if a thread running in user mode is interrupted As we know, ARM has some banked registers such as sp and lr. In other words, while in irq mode, sp_usr (and lr_usr) is invisible, that is, shadowed by sp_irq. So, my question is how the interrupt handler saves sp_usr. Some people might think that this is unnecessary because sp_usr will automatically remain unchanged during the handling of the interrupt since it's invisible and inaccessible in irq mode. However, this is not always the case. Consider the following scenario:
a) Thread A is running in user space.
b) An external interrupt occurs.
c) The handler runs, and finds that Thread B which has a higher priority now has got the resource it has been waiting for, so decides to reschedule.
d) Saves the context of Thread A. Now Thread B runs, first in SVC mode, then back in user mode. This is just the moment when the value of sp_usr is overridden by thread B.
e) Thread B calls something like sleep. Thread A will resume running from the point where it was interrupted.
So, if sp_usr was not saved when thread A was interrupted, how would thread A restore its context?

A: sp_usr must be saved before the context switch to thread B, then when thread B goes to sleep and the context of thread A is restored. If sp_usr for thread A is not saved then it is lost. Generally in a context switch the current sp is saved in the current tasks control block. When the new task is selected the sp is restored from the new tasks control block.
See this thread: ARM. Access user R13 and R14 from Supervisor mode
A lot of this does depend on which arm architecture you are using!


text:
Q: Encoding an Underscore to %5F I am trying to use the HttpUtility.HtmlEncode to encode an underscore to %5f, but the encoded value does not give me the hex representation. How will I accomplish this?
string encodedValue = HttpUtility.HtmlEncode("First_Name");

The value I want in the encodedValue string is "First%5FName".
Is there something I am missing? I have also tried using the HttpUtility.UrlEncode, but that does not give me the desired result as well.
I know this should be something simple, but I cant get around it.

A: It's an old subject but to convert a char in its HexEscape format you should use:
myString.Replace("_", Uri.HexEscape("_"));

A: if you just want to replace _ with %5f, you can just use myString.Replace("_", "%5f");


text:
Q: Documentation on virtual folders I am looking for documentation for the Windows API on how to make virtual folders. I am going to make sort of my own file system and would like to have an icon under "Computer" for that file system. I have seen other programs which has this type of solution like programs which allows me to explore a Linux file system under in the Explorer program. Much like the same solution I am going to make. I am yet to find any documentation on how to do this, or am I searching for the wrong stuff? Thanks.

A: You are looking for a Shell Namespace Extension. An entry Point for documentation is Creating Shell Data Source Objects and Extending the Shell Namespace.
An example of a almost complete Project can be found on codeplex: An almost complete Namespace Extension Sample
Also in the Windows SDK 7, there is an example of using the Shell ExtensionNamespace (can be found in the folder "Microsoft SDKs\Windows\v7.1\Samples\winui\shell\shellextensibility\explorerdataprovider"). In this Folder you will also find a document which describes the programming model (Using the System Folder View.doc).
If you really want to create a "real" file System Driver, you might want to look at this SO article:
Creating a File System "Driver" which mainly referes to the Ext2 file system driver project.


text:
Q: ComponentScan.basePackageClasses vs ComponentScan.basePackages to register a single Spring webMVC Controller? I want to add a single specific controller class to my Spring WebApplicationContext. I ran across the following example: (its in Scala, but is adapted from here: using ComponentScan or context:component-scan with only one class)
@Configuration
@ComponentScan(
  basePackages = Array("com.example.controllers"),
  useDefaultFilters = false,
  includeFilters = Array(
    new ComponentScan.Filter(`type` = FilterType.ASSIGNABLE_TYPE,
      value = Array(classOf[com.example.controllers.MyController]))))
class MyConfig {
}

This works nicely (but is very verbose).
But Spring's @ComponentScan also has basePackageClasses
@Configuration
@ComponentScan( basePackageClasses=Array(classOf[com.example.controllers.MyController]))
class MyConfig {
}

Of basePackageClasses, Spring's docs says:
Type-safe alternative to basePackages() for specifying the packages to
scan for annotated components.

However, while the first ComponentScan correctly adds only com.example.controllers.MyController, but the second cause all of my @Controller to be scanned and added! Why? What's the use of basePackageClasses?
Example like: https://github.com/mikaelhg/springmvc-example/blob/master/src/main/java/mikaelhg/example/ExampleConfiguration.java
suggest that basePackageClasses can be used to load a single component.

Update:
As an aside, replacing:
@Configuration
@ComponentScan(
  basePackages = Array("com.example.controllers"),
  useDefaultFilters = false,
  includeFilters = Array(
    new ComponentScan.Filter(`type` = FilterType.ASSIGNABLE_TYPE,
      value = Array(classOf[com.example.controllers.MyController]))))
class MyConfig {
}

with
@Configuration
class MyConfig {

  @Bean
  var myController = new com.example.controllers.MyController

}

it seems that MyController never gets gets connected to the servlet (the behavior changed to 404-NotFound) -- when added to a WebApplicationContext.

A: The full javadoc for that attribute reads

Type-safe alternative to basePackages() for specifying the packages to
  scan for annotated components. The package of each class specified
  will be scanned.
Consider creating a special no-op marker class or interface in each
  package that serves no purpose other than being referenced by this
  attribute.

By type-safe, you can't make any mistakes with the String value of the name of the package. If you specify an incorrect class, it will fail at compile time.
When you specify basePackageClasses, Spring will scan the package (and subpackages) of the classes you specify. This is a nice trick with no-op classes/interfaces like Controllers, Services, etc. Put all your controllers in one package containing the Controllers class and specify your Controllers class in the basePackageClasses. Spring will pick them all up.
You still need to specify the filters.


text:
Q: How to use If and Goto in Table loop? I have the following code,
j=0;
Table[{Label[1], j = j + 1, i, If[j == 2, Goto[1], Continue]}, {i, 1,10}]

which does not work; I get does not find Label[1] and for other initial values of j, I get the following result:

{Label[1], 3, 1, Continue}, {Label[1], 4, 2, Continue}, {Label[1], 5,
        3, Continue}, {Label[1], 6, 4, Continue}, {Label[1], 7, 5,
        Continue}, {Label[1], 8, 6, Continue}, {Label[1], 9, 7,
        Continue}, {Label[1], 10, 8, Continue}, {Label[1], 11, 9,
        Continue}, {Label[1], 12, 10, Continue}}

What I intended to do was: when j is equal to 2, the i in loop does not change  until j gets added by one and then it continues. Could you please help me where I made mistake?
Thanks

A: There are easier ways to "skip a beat". For example:
Table[If[i == 2, Nothing, i], {i, 1, 11}]

A: Maybe this does what you want?
j = 0;
Table[Label[1]; j = j + 1; i; If[j == 2, Goto[1]]; j, {i, 1, 10}]

{1, 3, 4, 5, 6, 7, 8, 9, 10, 11}

The main problems where the commas; they have to be semicoli. Notice also that the braces { and } in Mathematica are used as delimiters for lists and not for code blocks  -- contrary to C. For code blocks, just use parentheses ( and ).
Continue is not really necessary here. If you insist on using it, please use Continue[] instead (notice the brackets).

A: If already does what you want:
j = 0;
Table[j++; If[j == 2, j++; j, j], {i, 1, 10}]

A: A different way of doing this might be:
Complement[Table[j, {j, 1, 11}], {2}]


text:
Q: Hover syntax difference What is the difference between:
a.cvc-formsHelpText:hover {
text-decoration:none;
}

And:
.cvc-formsHelpText:hover {
text-decoration:none;
}

The HTML is:

Text.

The first works and the second not, but both refer to  tag.

A: It has nothing to do with hover at all.
#id element.class:pseudo-selector {
  property: value;
}

That's the general syntax. The first selector works because it's selecting the cvc-formsHelpText class, not trying to fruitlessly target a non-existent cvc-formsHelpText element.

A: The problem, when you're saying that the second doesn't work, is that you've omitted a dot, as BoltClock points out: .cvc-formsHelpText
As for the difference between the two syntaxes, the former denotes that the element must be an anchor with the class cvc-formsHelpText. The latter selector (provided that you include the dot that you've omitted) applies to any element with the class cvc-formsHelpText. Obviously, if only anchor elements contain that class, there will be no perceived difference in the way your website behaves.

A: a.blah defines a class for anchor tags (the "a" tag).  .blah defines a class for any tag.

A: cvc-formsHelpText is a class. You need a "." in front of it if you want to style it.
.cvc-formsHelpText:hover {
text-decoration:none;
}

A: cvc-formsHelpText:hover means: an element named cvc-formsHelpText, hovered. For example, <cvc-formsHelpText>, which doesn't exist.
a.cvc-formsHelpText:hover means: an  tag, with class cvc-formsHelpText, hovered.

A: The first says that all "a" tags are found that have "cvc-formsHelpHext" for the CSS "class" attribute. The second looks for tags named "cvc-formsHelpHext", which is not what you are trying to do.


text:
Q: Can I use a table from the WITH clause in the IN clause? In attempt to write more readable SQL code by following this recommendation, I'm trying to use the WITH clause.
It works here:
WITH
    t AS
    (
        SELECT
            *
        FROM
            TABLE1
        WHERE
            COL1 = 'foo'
    )
SELECT
    *
FROM
    t
WHERE
    COL2 > 42

But it doesn't work in the following case:
WITH
    t AS
    (
        SELECT
            COL1
        FROM
            TABLE1
    )
SELECT
    *
FROM
    TABLE2
WHERE
    COL2 IN t

It returns the following error:

1) [Code: -206, SQL State: 42703]  "T" is not valid in the context
  where it is used.. SQLCODE=-206, SQLSTATE=42703, DRIVER=4.22.29

Just in case it's not clear what I mean by the non-working query above, here is what:
SELECT
    *
FROM
    TABLE2
WHERE
    COL2 IN
    (
        SELECT
            COL1
        FROM
            TABLE1
    )

How can I use a table for the WITH clause in the IN clause?

A: "T" acts as a table so you have to select a column in order to compare it with "IN"
WITH
t AS
(
    SELECT
        COL1
    FROM
        TABLE1
)
SELECT
 *
FROM
TABLE2
WHERE
COL2 IN ( SELECT COL FROM t )

A: IN requires a subquery.  You simply need:
WHERE COL2 IN (SELECT ? FROM t)

Note that you need to specify the column as well as the table.

A: I would use exists :
select t2.*
from table2 t2
where exists (select 1
              from table1 t1
              where t1.COL1 = t2.COL2 and t1.COL1 = <whatever filter>
             );


text:
Q: Set custom status if WooCommerce order has items from a certain category Via the following code I added a custom order status (Abonnement) in WooCommerce
function register_abonnement_order_status() {
    register_post_status( 'wc-abonnement', array(
        'label'                     => 'Abonnement',
        'public'                    => true,
        'exclude_from_search'       => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop( 'abonnement (%s)', 'abonnement (%s)' )
    ) );
}
add_action( 'init', 'register_abonnement_order_status' );

// Add to list of WC Order statuses
function add_abonnement_to_order_statuses( $order_statuses ) {

    $new_order_statuses = array();

    // add new order status after processing
    foreach ( $order_statuses as $key => $status ) {

        $new_order_statuses[ $key ] = $status;

        if ( 'wc-processing' === $key ) {
            $new_order_statuses['wc-abonnement'] = 'Abonnement';
        }
    }

    return $new_order_statuses;
}
add_filter( 'wc_order_statuses', 'add_abonnement_to_order_statuses' );

I then used Change WooCommerce order status based on approved status and specific order item answer code to help me further.
I modified that answer to go to the next step:
    function action_woocommerce_order_status_changed( $order_id, $old_status, $new_status, $order ) {
// Compare
    if( $old_status === 'processing' ) {
        // Get items
        $items = $order->get_items();

        foreach ( $items as $item ) {
            // Get products categories
           global $post;
            $terms = get_the_terms( $post->ID, 'product_cat' );
                foreach ($terms as $term) {
                $product_cat_id = $term->term_id;
            break;
            }
            $product_cat = $item->get_product_cat();

            if ($product_cat == 249 ) {
                $order->update_status( 'abonnement' );
                break;
            }
        }
    }
}
add_action( 'woocommerce_order_status_changed', 'action_woocommerce_order_status_changed');

But that doesn't seems to work. So i'm not sure what I'm missing?

A: *

*Explanation via comment tags added in the code

To automatically change the order status after each order, when the order contains items that belong to certain categories, use:
/**
 * Change Order Status
 */
function action_woocommerce_thankyou( $order_id ) {
    if ( ! $order_id ) return;

    // Get order object
    $order = wc_get_order( $order_id );

    // Specific categories: the term name/term_id/slug. Several could be added, separated by a comma
    $categories = array( 'categorie-1', 'categorie-2', 15, 16 );

    // Flag
    $found = false;

    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        // Product ID
        $product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();

        // Has term (product category)
        if ( has_term( $categories, 'product_cat', $product_id ) ) {
            $found = true;
            break;
        }
    }

    // True
    if ( $found ) {
        // Status without the "wc-" prefix || Some options: pending, processing, on-hold, completed, cancelled, refunded, failed, etc...
        $order->update_status( 'abonnement' );
    }
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );

OR using woocommerce_order_status_changed hook where you can target your orders statuses transition from and to, to change the order status to any other.
function action_woocommerce_order_status_changed( $order_id, $old_status, $new_status, $order ) {
    // Compare
    if ( $old_status === 'processing' ) {
        // Specific categories: the term name/term_id/slug. Several could be added, separated by a comma
        $categories = array( 'categorie-1', 'categorie-2', 15, 16 );

        // Flag
        $found = false;

        // Loop through order items
        foreach ( $order->get_items() as $item ) {
            // Product ID
            $product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();

            // Has term (product category)
            if ( has_term( $categories, 'product_cat', $product_id ) ) {
                $found = true;
                break;
            }
        }

        // True
        if ( $found ) {
            // Status without the "wc-" prefix || Some options: pending, processing, on-hold, completed, cancelled, refunded, failed, etc...
            $order->update_status( 'abonnement' );
        }
    }
}
add_action( 'woocommerce_order_status_changed', 'action_woocommerce_order_status_changed', 10, 4 );

Optional: to register a new order status, you can replace your current code with this updated code
/**
 * Register Order Status
 */
function filter_woocommerce_register_shop_order_post_statuses( $order_statuses ) {
    // Status must start with "wc-"
    $order_statuses['wc-abonnement'] = array(
        'label'                     => _x( 'Abonnement', 'Order status', 'woocommerce' ),
        'public'                    => false,
        'exclude_from_search'       => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        /* translators: %s: number of orders */
        'label_count'               => _n_noop( 'Abonnement (%s)', 'Abonnement (%s)', 'woocommerce' ),
    );

    return $order_statuses;
}
add_filter( 'woocommerce_register_shop_order_post_statuses', 'filter_woocommerce_register_shop_order_post_statuses', 10, 1 );

/**
 * Show Order Status in the Dropdown @ Single Order
 */
function filter_wc_order_statuses( $order_statuses ) {
    // Status must start with "wc-"
    $order_statuses['wc-abonnement'] = _x( 'Abonnement', 'Order status', 'woocommerce' );

    return $order_statuses;
}
add_filter( 'wc_order_statuses', 'filter_wc_order_statuses', 10, 1 );

/**
 * Show Order Status in the Dropdown @ Bulk Actions
 */
function filter_bulk_actions_edit_shop_order( $bulk_actions ) {
    // Note: "mark_" must be there instead of "wc"
    $bulk_actions['mark_abonnement'] = __( 'Change status to abonnement', 'woocommerce' );
    return $bulk_actions;
}
add_filter( 'bulk_actions-edit-shop_order', 'filter_bulk_actions_edit_shop_order', 10, 1 );


text:
Q: How to prevent route changing? I have a service in which inside I bind a click event:
$('button').click(function() {
alert('Clicked');
return false;
});

The issue is when I do not start at the default "/" route (i.e. "/testroute"), then that same button when clicked, causes the page url to go to "/" and not fire my event at all. When I click on it again after the route changes to "/", the event triggers as normal. How do I make it such that if I were to start at /testroute (even though it has the same view, different controller, but shares the same service, the alert will fire?

A: You might want to use these events to prevent route changing.

A: Use locationChangeStart. Also read the link Andrey posted.
$rootScope.$on('$locationChangeStart', function(e) {
    e.preventDefault();
  });


text:
Q: Big gap between elements in HTML & CSS So I am trying to design my website and I got this big white gap between my navigation bar and image. Where have I done wrong here?
Also side note: Does anyone know how I can "box" my entire page to let there be empty white spaces on the sides?
HTML:
@{
    Layout = null;
}
<!DOCTYPE html>

    <title>Design</title>

                        <input id="sweBtn" type="button" value="SVENSKA" />
                        <input id="engBtn" type="button" value="ENGLISH" />
                        <input id="searchTxt" type="text" />
                        <input id="searchBtn" type="button" value="SÖK" />

Header

Text

Home

News

Contact

About

<link href="~/Content/custom.css" rel="stylesheet" />

CSS
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

    li a {
        display: block;
        color: white;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
    }

        li a:hover {
            background-color: #111;
        }

#header {
    background-color: #503F31;
    color: white;
    padding: 30px;
}

#sweBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: grey;
}

#engBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: gold;
}

#searchTxt {
    background-color: grey;
    border-color: grey;
}

#searchBtn {
    font-family: 'Times New Roman';
    background-color: Transparent;
    color: gold;
}

#imgTitle {
    position: absolute;
}

#imgHeader {
    height: 1000px;
    width: 3400px;
}

#footer {
    background-color: grey;
    color: white;
    padding-bottom: -250px;
}

Doesnt matter what elements I use, it still a big gap. Help please


text:
Q: Alex, Bethany, Carlos place blocks into boxes
Alex, Bethany, and Carlos are playing a game. In the game, there are $5$ completely empty boxes, and each person has $5$ blocks that are red, blue, yellow, green, and purple. Each of the people take turns placing all $5$ of their blocks (randomly) into a random box, and they will win the game if at least one box receives $3$ blocks of the same color. If the probability that the group will win is $\frac{m}{n},$ find $m + n.$

I noted that the decisions of the first player (assume its Alex) didn't matter, as the probability would be symmetric either way. I also noted that as long as one box had three of the same blocks, the three people would win and the other boxes would essentially be pointless. Therefore, I started counting the amount of ways Bethany and Carlos could place their blocks so that the three people would win. This gave me $$\binom{5}{1} * \binom{5}{1} \cdot 4! * \binom{5}{1} * 4! = 72000.$$ However, this answer felt a little bit off, so I wanted to ask somebody else to check if my answer was correct or not. Thanks!


text:
Q: Excel Max from subset of data MAX IF IF I have a set of data as below:

In the "Latest" Column I want to print "Latest" for the MAX(StepNumber) where tracked = "Yes" for each ManufacuringOrderId. I can try and do this in the SQL, but also wanted to see if I could do it with an array formula. So if this works, the 9th row would say "Latest" and the 4th and 5th rows up from the bottom would also say "Latest".
I tried the formula {=MAX(IF(A:A=[@ManufacturingOrderId],F:F))} returns the Max Step Number for each ManufacturingOrderId, and the formula {=MAX(IF([@Tracked]="Yes",IF(A:A=[@ManufacturingOrderId],F:F)))} will return the max step number for each manufacturing ID that has a process step that is tracked.
However, I can't figure out a way to determine the Max Step number where the process step is tracked for each Manufacturing Order Id.  For Manufacturing Order ID 5601774 the step number would be 160 and for MOID 5624276 the step number would be 150.
help and thanks!

A: If I've understood the question correctly then you should be able to AND the two conditions (that each row is of the same ID as the current row and that it is Tracked) inside the MAX. Then just check whether that number matches the current StepNumber and say "Latest" if it is.
{=IF(MAX(IF(AND(A:A=[@ManufacturingOrderId], [@Tracked]="Yes"),F:F)) = [@StepNumber], "Latest", "")}

A: You can get the MAX stepnumber for each OrderId when Tracked is "Yes" with this array formula
=MAX(IF([ManufacturingOrderId]=[@ManufacturingOrderId],IF([Tracked]="Yes",[StepNumber])))
....so to to get "Latest" in the correct rows you need to check that not only does Stepnumber = that value but also that "Yes" exists in that row, i.e.
=IF(AND([@StepNumber]=MAX(IF([ManufacturingOrderId]=[@ManufacturingOrderId],IF([Tracked]="Yes",[StepNumber]))),[@Tracked]="Yes"),"Latest","")
confirmed with CTRL+SHIFT+ENTER
Revised: This version should be more efficient - using two IFs, rather than AND means the long MAX(IF part of the formula only needs to be evaluated on rows where [Tracked]="Yes"
=IF([@Tracked]="Yes",IF([@StepNumber]=MAX(IF([ManufacturingOrderId]=[@ManufacturingOrderId],IF([Tracked]="Yes",[StepNumber]))),"Latest",""),"")
[Note AND here is used to check 2 single result conditions, not within the array part]


text:
Q: Task 'installDebug' not found in project ':app'.in only one react-native project I am new to React and first tried to do a Hello World Project. I got the mentioned error but also the error, that my sdk path is not set. So I configured a ANDROID_SDK_ROOT variable. Then it worked properly.
Now I want to run the rocket chat app from github on my android device. This is the project: https://github.com/RocketChat.
After navigating into the project (root), I first started the server with npm start, showing me a successful message. Then I wanted to run it on my phone, using npx react-native run-android.
This is the output I get:
FAILURE: Build failed with an exception.

* What went wrong:
Task 'installDebug' not found in project ':app'.

* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack
trace. Run with --info or --debug option to get more log output. Run with --scan to get full
insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 5s

error Failed to install the app. Make sure you have the Android development environment set up:
https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

I know there are already some posts about this error and I tried their solutions so far, but without success yet.
My device is registered and is showing when I do adb devices. The global android sdk variable is also set.
What could have gone wrong? Can someone tell me what I am missing?
Thanks for every help!

A: I fixed it. None of the solutions worked but I found another way.
First, dont forget to start the server. Navigate to the root folder of your project and run npm start. This should run successfully. If it says your ports are already used, just open your task manager and terminate all tasks from NodeJS.
In your android folder, run the command gradlew tasks. This will show you a list of available commands. I dont know why, but the command installDebug was not there, hence the error.
But there were other tasks which sounded similar, for example installFossDebug.
So I ran npx react-native run-android --variant=installFossDebug. But it didnt work. The console showed me a new error, saying Task installInstallFossDebug could not be found (No Typo).
I dont know why install was twice in the task, so I just ran npx react-native run-android --variant=FossDebug and voila, it worked. The app started successfully on my android device.
Good luck! :-)


text:
Q: file-scope mutable static HashSet/Vec/etc I'd like to create C-linkage functions to intercept my program's calls via LD_PRELOAD but I'm implementing the interception functions in Rust.
I have no problem creating the pub extern fn to intercept the calls but I'd like to read/write from the program's global state somewhere since I can't alter the signature of the functions I'm intercepting to accept the metadata.  I don't need heap allocation necessarily, I could live with some large statically initialized pool of HashSet or Vec entries.  But I do need to be able to add and remove elements of the collection during the program's run.
I recognize that this pattern is contrary to many Rust design goals and yet it seems like a legitimate use case to me.
I'm brand new to Rust, so I'm hoping that there's an unsafe option out there to do this.
If it's useful to see code examples:
static mut foo Vec<c_int> = Vec::new();

...fails because you can't have static storage that requires a destructor, or does heap allocations.  And lazy_static! doesn't allow for mutable structures.
Ideally I'd prefer a HashSet<c_int>.  If I can't get that to work, I suppose I could try a Vec::from_elem(100, 0).  That's not ideal since I'll need to nominate some kind of sentry value, but if it works I think I'd be satisfied.