text:
Q: Creating a new alert cause "List does not exist." I have a script that create alerts for specific document libraries in multiple webs. It work with sharepoint-server cmdlet and is aimed at SharePoint 2013. I tested the script with a test library and user with no issue at all.
#----------------------------------------------------------[Declarations]----------------------------------------------------------

# Site where the alerts will be added, all the subsite will be handled
$siteToHandleUrl = "A Valid Url"

# Email that will recieve all the alerts
$emailToAlert = "A Valid Email"

# Lists where alerts will be added
$listsToHandle = @("A Valid List Name")

#-----------------------------------------------------------[Execution]------------------------------------------------------------

$web = Get-SPWeb -Identity $siteToHandleUrl
$webs = $web.Site.AllWebs | Where-Object {$_.Url -like "$siteToHandleUrl*"}
$user = $web.EnsureUser($emailToAlert)
$existingAlerts = $user.Alerts.Title
if ($null -eq $existingAlerts) {
    $existingAlerts = @()
}
$addedAlerts = @()

foreach ($web in $webs) {
    Write-Host "Handling $($web.Title)"
    $lists = $web.Lists

    foreach ($listToHandle in $listsToHandle) {
         $alertName = "Automated Alert for $($list.Title) in $($web.Title)"
         $list = $web.Lists[$listToHandle]

        if (-not $existingAlerts.Contains($alertName)) {
            Write-Host "Adding alert for $($list.Title)"

            $newAlert = $user.Alerts.Add()
            $newAlert.Title = $alertName
            $newAlert.AlertType=[Microsoft.SharePoint.SPAlertType]::List
            $newAlert.List = $list
            $newAlert.DeliveryChannels = [Microsoft.SharePoint.SPAlertDeliveryChannels]::Email
            $newAlert.EventType = [Microsoft.SharePoint.SPEventType]::All
            $newAlert.AlertFrequency = [Microsoft.SharePoint.SPAlertFrequency]::Daily
            $newAlert.Update()
        }
    }
}

Now when I try this script for the actual librairies, I get this error message on the $newAlert.Update() :
Exception calling "Update" with "0" argument(s): "List does not exist.
The page you selected contains a list that does not exist.  It may have been deleted by another user."

Yet the library do exist and the object is literally coming from the web. Debugging show that $user has a valid user and $list has the list object. If I go the SharePoint site, I can add manually a new alert with no issues.

A: If this is your whole script, it seems you did not define the variable $listsToHandle.
Write-Host "Handling $($web.Title)"
    $lists = $web.Lists

    foreach ($listToHandle in $listsToHandle) {
         $alertName = "Automated Alert for $($list.Title) in $($web.Title)"
         $list = $web.Lists[$listToHandle]

As it is not defined before, in the foreach part in fact you have not lists to loop and I guess that is the reason console returns error "List does not exist".
And if seems you haven't defined $list before you use it in $alertName

A: I found the issue. Turn out that the way you obtain the user is very important :
...
foreach ($web in $webs) {
    Write-Host "Handling $($web.Title)"
    $lists = $web.Lists
    $user = $web.EnsureUser($emailToAlert)

    foreach ($listToHandle in $listsToHandle) {
         $alertName = "Automated Alert for $($list.Title) in $($web.Title)"
         $list = $web.Lists[$listToHandle]

        if (-not $existingAlerts.Contains($alertName)) {
            Write-Host "Adding alert for $($list.Title)"

            $newAlert = $user.Alerts.Add()
            $newAlert.Title = $alertName
...

You must get your user for each web you are handling. The object the EnsureUser is different depending on the web you are calling. In this case the $user.Alerts collection is only a collection of the alerts for the specified web. So if you try to add to this collection an alert on a list that is not in the web, it will not work.


text:
Q: InvalidPidMappingException in KafkaListener BeginTransaction We have been getting lots of InvalidPidMappingException failures recently.
I came across https://github.com/spring-projects/spring-kafka/issues/660, but this is specific to producerOnly publishing in tx.
In our case, this is happening in consumers, so it cannot be resolved using retries (keeps failing with each rollback retry).
There's a fix in kafka to address this exception, but will probably be released in 4 months (v2.5.0). https://github.com/apache/kafka/pull/7115
Is there a way we can recover from these failures?
One option we're considering is to use ContainerAwareErrorHandler to restart the listenercontainer in case of these 2 specific exceptions. Any issues with this approach? what would happen if another listener is processing another message?
 org.apache.kafka.common.KafkaException: Cannot execute transactional method because we are in an error state
    at org.apache.kafka.clients.producer.internals.TransactionManager.maybeFailWithError(TransactionManager.java:924)
    at org.apache.kafka.clients.producer.internals.TransactionManager.beginTransaction(TransactionManager.java:290)
    at org.apache.kafka.clients.producer.KafkaProducer.beginTransaction(KafkaProducer.java:642)
    at org.springframework.kafka.core.DefaultKafkaProducerFactory$CloseSafeProducer.beginTransaction(DefaultKafkaProducerFactory.java:597)
    at org.springframework.kafka.core.ProducerFactoryUtils.getTransactionalResourceHolder(ProducerFactoryUtils.java:101)
    at org.springframework.kafka.transaction.KafkaTransactionManager.doBegin(KafkaTransactionManager.java:160)
    at com.projectdrgn.common.messaging.config.KafkaProducerConfig$kafkaTransactionManager$kafkaTransactionManager$1.doBegin(KafkaProducerConfig.kt:65)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:376)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:137)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.recordAfterRollback(KafkaMessageListenerContainer.java:1463)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListenerInTx(KafkaMessageListenerContainer.java:1438)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:1398)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:1165)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:949)
    at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:884)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:748)
    Caused by: org.apache.kafka.common.KafkaException: org.apache.kafka.common.errors.InvalidPidMappingException: The producer attempted to use a producer id which is not currently assigned to its transactional id.
    at org.apache.kafka.clients.producer.internals.TransactionManager$AddPartitionsToTxnHandler.handleResponse(TransactionManager.java:1204)
    at org.apache.kafka.clients.producer.internals.TransactionManager$TxnRequestHandler.onComplete(TransactionManager.java:1069)
    at org.apache.kafka.clients.ClientResponse.onComplete(ClientResponse.java:109)
    at org.apache.kafka.clients.NetworkClient.completeResponses(NetworkClient.java:561)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:553)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:307)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:238)
    ... 1 common frames omitted
    Caused by: org.apache.kafka.common.errors.InvalidPidMappingException: The producer attempted to use a producer id which is not currently assigned to its transactional id.

redpajama_set_name: RedPajamaStackExchange


text:
Q: EditText colors and DateDialog text I'm currently developing an android app. I've just discovered something weird and I can't seem to remove it. There is 2 weird things happening:
First issue:
I can't seem to figure out why the "Mon, Jan 25, 2016" text is at the top of my DateDialog and if it's possible to remove? You can see the image below, to see my DateDialog.
You can also see the styling of the DateDialog below.
Second issue:
I have an EditText box and the colors of the two buttons at the buttom of the dialog, can't seem to change color. Which styling elements do I have to add or is there an easy solution for me to fix this??
Datedialog:

EditText box:

Styling:
<resources>
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <!--<item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>-->
</style>

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/MenuBar</item>
    <item name="colorPrimaryDark">@color/ShadowMenuBar</item>
    <item name="colorControlNormal">@color/ColorPrimaryDark</item>
    <item name="colorControlActivated">@color/ColorPrimaryDark</item>
    <item name="colorControlHighlight">@color/ColorPrimaryDark</item>
    <item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>

<style name="MyDatePickerDialogTheme" parent="@style/Theme.AppCompat.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
    <item name="android:colorAccent">@color/ColorPrimaryDark</item>
    <item name="colorAccent">@color/ColorPrimaryDark</item>
</style>

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/ColorPrimaryDark</item>
    <item name="android:calendarTextColor">@color/ColorPrimaryDark</item>
    <item name="android:dayOfWeekBackground">@color/ColorPrimaryDark</item>
    <item name="android:yearListSelectorColor">@color/ColorPrimaryDark</item>
    <item name="android:datePickerMode">calendar</item>
</style>

DateDialog creation code:
private void setDateTimeField() {
    Date.setOnClickListener(this);
    Calendar newCalendar = Calendar.getInstance();
    DateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            if(view.isShown())
            {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);

            }
        }
    },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}


text:
Q: Run an SQLite command and quit? If I run something like this:
sqlite3 mydb.sqlite -cmd 'UPDATE users SET update_time = 0;'

It's going to successfully run the command, however it's also going to open the sqlite command line interface. Is it possible to make it run the command and then close afterwards? I've tried adding .quit at the end of my command:
sqlite3 mydb.sqlite -cmd 'UPDATE users SET update_time = 0; .quit'

but it says "command invalid" so I guess it's expecting actual SQL queries only.
Any idea if it can be done?

A: Keeping the CLI active is what the -cmd option does.
To execute some command and quit, don't use this option:
sqlite3 mydb.sqlite 'UPDATE users SET update_time = 0;'


text: Q: Statistical test for comparing directional data I have a dataset with number of bats flying out in 8 directions from their home site (i.e) I studied a bat colony with N individuals and I have counted the number of bats (from that colony) that flew out in 8 directions every night. By comparing the emergence proportions of different nights, I want to test if the colony has any directional preferences across seasons. This is a categorical data with each direction having a corresponding count/proportion of bats flying out per night. What would be the best statistical approach to do test this?


text:
Q: Why are there two icons in the Unity launcher for Nautilus? Okay, so I installed Ubuntu 11.10.
The thing is, when I click the home folder icon in the launcher (Win + 1), the home folder opens and a new icon appears in the launcher.
I want the windows to be highlighted in the first icon only if you catch my drift (4th icon).
I thought if I could remove the first icon and then right-click on the other icon and keep it in the launcher, it may work - but then folders open and the icon remains blank without any indication that a window is open (looks same as first icon).

Also, the icons numbered from top to bottom exclude the dash icon.

A: According to the bug, you just need to remove the following line from your custom Nautilus launcher (~/.local/share/applications/nautilus-home.desktop):
OnlyShowIn=GNOME;Unity;

I had this problem and removing that line and logging out and logging back in worked for me.

A: Disclaimer: I am not a Linux programmer, and this answer contains modifying files out of your home folder. It works for me, but do it on your own risk.
This problem appears when you configure your Home icon to have a quicklist for your favourite places the way it is described here.
The way to solve it, as written on the Bug 842257 page, is instead of creating a copy of /usr/share/applications/nautilus-home.desktop in ~/.local/share/applications and modifying this copy, rather modifying the original file. So the steps are:

*

*Delete the copy, if there is any: ~/.local/share/applications/nautilus-home.desktop

*Open a terminal and write:
gksu gedit /usr/share/applications/nautilus-home.desktop

*Add this text at the bottom of the file, save and close.
X-Ayatana-Desktop-Shortcuts=Videos;Documents;Music;Pictures;Downloads
[Videos Shortcut Group]
Name=Videos
Exec=nautilus Videos
TargetEnvironment=Unity

[Documents Shortcut Group]
Name=Documents
Exec=nautilus Documents
TargetEnvironment=Unity

[Music Shortcut Group]
Name=Music
Exec=nautilus Music
TargetEnvironment=Unity

[Pictures Shortcut Group]
Name=Pictures
Exec=nautilus Pictures
TargetEnvironment=Unity

[Downloads Shortcut Group]
Name=Downloads
Exec=nautilus Downloads
TargetEnvironment=Unity

*Reboot. It should work now, only one icon, with the quicklist.
If it still doesn't work, you can try Alt+F2, then run
unity --reset-icons

This will reset the icons of the original install on your launchbar, so you will have to repopulate it the way you want.
For getting the original nautilus-home.desktop file back, you can reinstall Nautilus and have the default settings and files:
sudo apt-get install --reinstall nautilus

A: This is a confirmed bug. Bug 842257
It will be fixed at some point. There should only be one icon in the Launcher.

A: I had the same issue. Make sure you don't have a custom nautilus-home.desktop file in ~/.local/share/applications. When I deleted that everything started working again.
I created one a while ago in 11.04, I guess something has changed in 11.10.

A: Just unlock the file manager from Launcher. Then, open it again from the search icon typing nautilus. Finally, lock it to launcher.
It worked for me.

A: The dash icon is not supposed to have a number since it would be redundant. The numbers are there so that you can activate an entry by pressing super+num. For instance, in your case, you would be able to launch and/or switch to Firefox by pressing super+2 and super+3 for the terminal. Launching the dash is done by a simple tap on super.
I have seen the bug you're referring to, but it was quite some time ago. Have you installed all upgrades? I've also seen that caused by an extension, but I don't remember which it was, but it may have been one to add quicklists. It should not be that way out of the box. Try opening a guest session and I'm sure that problem goes away. Would be nice if you confirmed that though.

A: It is possible to have a custom nautilus-home.desktop file without this problem, as some other answers have mentioned. Another fix (mentioned here: Opening home folder causes another file cabinet icon to appear) is to go to gnome-tweak-tool and set Have file manager handle the desktop to off.

A: The problem is a contradiction in the 'Home Folder' file
/usr/share/applications/nautilus-home.desktop
In the original file this line exists:
OnlyShowIn=GNOME;Unity;

while in quick list it is:
TargetEnvironment=Unity

This is solved by changing (TargetEnvironment=Unity) to:
TargetEnvironment=GNOME;Unity;

worked for me.


text:
Q: Using CryptoStreams to encrypt and HMAC data Let's say we have a message that is signed with an HMAC, then that message and the HMAC are encrypted, then that is sent over a TCP socket:
// endpoint info excluded
TcpClient client = new TcpClient();
var stream = client.GetStream();

// assume pre-shared keys are used and set at this point
AesManaged aes = new AesManaged();
var aesEncryptor = aes.CreateEncryptor();
CryptoStream aesStream = new CryptoStream(
    stream, aesEncryptor, CryptoStreamMode.Write);

// assume pre-shared keys here too
HMACSHA256 mac = new HMACSHA256();
CryptoStream macStream = new CryptoStream(
    aesStream, mac, CryptoStreamMode.Write);

// assume a message with actual data is written to the macStream
// which updates the hash of the HMAC and also pipes the message
// to the aesStream which encrypts the data and writes it to the
// TCP socket stream
byte[] message = new byte[1024];
macStream.Write(message, 0, message.Length);
macStream.FlushFinalBlock();

// flushing the final block of the macStream actually flushes the
// final block of the aesStream, so I get an error when trying to
// write the HMAC hash to the aesStream
aesStream.Write(mac.Hash, 0, mac.Hash.Length);
aesStream.FlushFinalBlock();

I abstracted out a lot of the code, so this isn't a working example. I could probably work around this my writing the data twice, once to HMAC.TransformBlock and again to the aesStream, but I'd like to avoid that. Any ideas?

A: Since I'm dealing with similar topics atm, I'll put an answer here:
Like Maarten Bodewes wrote, I suggest you do encrypt-then-MAC.
You could then write the HMAC-Bytes after doing FlushFinalBlock() on the aesStream.
Don't forget to dispose the CryptoStreams and Algorithms objects!
var stream = client.GetStream();

HMACSHA256 mac = new HMACSHA256();
CryptoStream macStream = new CryptoStream(stream, mac, CryptoStreamMode.Write);

AesManaged aes = new AesManaged();
var aesEncryptor = aes.CreateEncryptor();
CryptoStream aesStream = new CryptoStream(macStream, aesEncryptor, CryptoStreamMode.Write);

byte[] message = new byte[1024];
aesStream.Write(message, 0, message.Length);
aesStream.FlushFinalBlock();

//No need to FlushFinalBlock() on macStream, would throw

//Write HMAC here
stream.Write(mac.Hash, 0, mac.Hash.Length);

//Dispose
aesStream.Dispose();
aes.Dispose();
macStream.Dispose();
mac.Dispose();

A: You really should perform encryption before MAC to create a secure solution, especially if you send the data over a socket (as you may be vulnerable to padding oracle attacs). So although your question is valid, it it better to change the order of the streams.

A: So I put a hack in place that seems to be working for the moment. I created a stream wrapper class called ProtectedStream. Here's the gist:
public class ProtectedStream : Stream
{
  private Stream stream;

  public ProtectedStream(Stream stream)
  {
    if(stream == null)
      throw new ArgumentNullException("stream");

    this.stream = stream;
  }

  public override void Close()
  {
    this.stream.Close();
    base.Close();
  }

  public override int Read(byte[] buffer, int offset, int count)
  {
    return this.stream.Read(buffer, offset, count);
  }

  public override void Write(byte[] buffer, int offset, int count)
  {
    this.stream.Write(buffer, offset, count);
  }

  // and continue overriding every other overridable Stream member
  // in the same fashion
}

And then the original code looks like this:
// assume pre-shared keys are used and set at this point
AesManaged aes = new AesManaged();
var aesEncryptor = aes.CreateEncryptor();
CryptoStream aesStream = new CryptoStream(
    stream, aesEncryptor, CryptoStreamMode.Write);

// assume pre-shared keys here too
HMACSHA256 mac = new HMACSHA256();
CryptoStream macStream = new CryptoStream(
    new ProtectedStream(aesStream), mac, CryptoStreamMode.Write);

Note that aesStream is wrapped inside a ProtectedStream. This hides the fact that aesStream is a CryptoStream from macStream so when you call FlushFinalBlock on macStream it doesn't call FlushFinalBlock on aesStream.


text:
Q: How to use A recyclerview instead of list view I know How you a Listview in case When we need to get the data from the internet and to show it in Listview . Now the listview is deprecated. I wanted to know how to you recyclerview instead of listview.
2nd thing I was using swipe to delete and pull to refresh in a listview , also wanted to know does recycler view support these features or not ?
please also provide the link where I can learn how to make a custom recyclerview in place of the listview


text:
Q: Error when executing SQLAgent job in SQL 2012 which starts ssis package built in 2008 I've built a SSIS package in 2008 R2. It works perfectly so now I want to install it on a server of a customer. Though they have installed SQL Server 2012.
After converting the package i've executed it within the solution succesfully.
Though if I try to run a SQL Server Agent Job designed to execute the package it gives the following error:

To run a SSIS package outside of SQL Server Data Tools you must
  install Read Ini of Integration Services or higher.

(Read Ini is the first task the package should execute.)
I've checked and Integration Services 11.0 is installed. Also the SQL Server Agent user has been granted permissions to the Integration Services.
The package has been built under Integration Services 10.0.
Thanks in advance.

A: Integration Services is a little touchy.
you can execute, becouse when you lanch the package, it runs on your machine.
i suggest to recreate the package on SSIS 2012.


text:
Q: popup don't worked currently in chrome I want when mouse hover on the images in my website popup run .I wrote this codes.
.popupbigimg:hover , .popup:hover  ,.divbigimg:hover {
    z-index: 1000;
    margin: auto;
    background-color: #fff;
    border: 3px solid #fff;
    -webkit-box-shadow: 2px 2px 2px 2px rgba(212, 209, 209, 0.4);
    -ms-box-shadow: 2px 2px 2px 2px rgba(212, 209, 209, 0.4);
    box-shadow: 2px 2px 2px 2px rgba(212, 209, 209, 0.4);

    -moz-transform: scale(1.03);
    -webkit-transform: scale(1.03);
    -o-transform: scale(1.03);
    -ms-transform: scale(1.03);
    transform: scale(1.03);

    -webkit-transition: all 500ms ease;
    -moz-transition: all 500ms ease;
    -ms-transition: all 500ms ease;
    -o-transition: all 500ms ease;
    transition: all 500ms ease;
    display: table;

}

This codes run currently in ff but in chrome no.Please see this image:

When popup running another elements display on the image.You can see my website in this link.
Please advice.

A: Adding a high z-index to #colman2 resolved this for me.


text:
Q: Why does a hole moves from one atom to another? I know that in p-type semiconductors there are holes i.e the absence of electrons. What I can not understand is why electron from neighboring atom tends to fill that hole leaving a hole behind itself? I mean what makes that electron to leave its particular atom?

A: Because a covalent bond lowers energy.
Let us say there is an As and an adjacent Si. One filled hybridized orbital of Si and one empty hybridized orbital of As form a covalent bond, and still they each has a vacancy.
A wandering electron fills the holes so that another covalent bond is formed, lowering the energy.
In statistical perspective, states of lower energy will dominate in long term.
The filling of holes in acceptor material (and subsequent stripping of electrons in donor material) will stop when the electrostatic force pull them back, that is, the lowering of energy is cancelled by enhanced energy by electrostatic force.

A: First, let's try to understand about electrons it will help us to understand about holes.The picture you often see of electrons as small objects circling a nucleus in well defined "orbits" is actually quite wrong. As we now understand it, the electrons aren't really at any one place at any time at all. Instead, they exist as a sort of cloud. The cloud can compress to a very small space briefly if you probe it in the right way, but before that, it really acts like a spread-out cloud. For example, the electron in a hydrogen atom likes to occupy a spherical volume surrounding the proton. If you think of the proton as the size of a grain of salt, then the electron cloud would have about a ten-foot radius. If you probe, you'll probably find the electron somewhere in that region.
The weird thing about that cloud is that its spread in space is related to the spread of possible momenta (or velocities) of the electron. So here's the key point, which we won't pretend to explain here. The more squashed in the cloud gets, the more spread-out the range of momenta has to get. That's called Heisenberg's uncertainty principle. It could quit moving if it spread out more, but that would mean not being as near the nucleus, and having higher potential energy. Big momenta mean big kinetic energies. So the cloud can lower its potential energy by squishing in closer to the nucleus, but when it squishes in too far its kinetic energy goes up more than its potential energy goes down. So it settles at a happy medium, with the lowest possible energy, and that gives the cloud and thus the atom its size. It lowers the average energy of the system.


text:
Q: How to get aggregate Pipline result using MongoDB in golang mgo.v2 liabry Question background is I want retrieve aggregated data from MongoDB data by using golang mgo.v2 liabary.
I have a collection dataset as following.collection name is useragents
{
    "_id" : ObjectId("57f940c4932a00aba387b0b0"),
    "tenantID" : 1,
    "date" : "2016-10-09 00:23:56",
    "venueList" : [
        {
            "id" : "VID1212",
            "sum" : [
                {
                      "name" : "linux",
                      "value" : 12
                },
                {
                    "name" : "ubuntu",
                    "value" : 4
                }
            ],
            "ssidList" : [    // this is list of ssid's in venue
                {
                    "id" : "SSID1212",
                    "sum" : [
                        {
                            "name" : "linux",
                            "value" : 8
                        },
                        {
                            "name" : "ubuntu",
                            "value" : 6
                        }
                    ],
                    "macList" : [  // this is mac list inside particular ssid  ex: this is mac list inside the SSID1212
                        {
                            "id" : "12:12:12:12:12:12",
                            "sum" : [
                                {
                                    "name" : "linux",
                                    "value" : 12
                                },
                                {
                                    "name" : "ubuntu",
                                    "value" : 1
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "id" : "VID4343",
            "sum" : [
                {
                     "name" : "linux",
                     "value" : 2
                }
            ],
            "ssidList" : [
                {
                    "id" : "SSID4343",
                    "sum" : [
                        {
                            "name" : "linux",
                            "value" : 2
                        }
                    ],
                    "macList" : [
                        {
                            "id" : "43:43:43:43:43:34",
                            "sum" : [
                                {
                                    "name" : "linux",
                                    "value" : 2
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

I have already solved MongoDB shell script that i want by help from stack-overflow community.but I am troubling on when I was implemening it in golang using mgo.v2 library.
This is mongodb shell script
db.useragents.aggregate([
    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },
    { "$unwind": "$venueList" },
    { "$match": { "venueList.id": { "$in": ["VID1212", "VID4343"] } } },
    { "$unwind": "$venueList.sum" },
    {
        "$group": {
            "_id": "$venueList.sum.name",
            "count": { "$sum": "$venueList.sum.value" }
        }
    },
    {
        "$group": {
            "_id": null,
            "counts": {
                "$push": {
                    "name": "$_id",
                    "value": "$count"
                }
            }
        }
    }
])

Please go though question background
And I implement golang code as following
func GetBrowserStats(constrains models.Constrains) ([]bson.M, error) {

    session := commons.GetMongoSession()
    defer session.Close()
    var col = session.DB("analytics").C("useragents")

    pipeline1 := bson.M{
        "$match": bson.M{
            "venueList.id": bson.M{
                "$in": []string{"VID1212", "VID4343"},
            },
        },
    }
    pipeline2 := bson.M{
        "$unwind": "$venueList",
    }
    pipeline3 := bson.M{
        "$match": bson.M{
            "venueList.id": bson.M{
                "$in": []string{"VID1212", "VID4343"},
            },
        },
    }
    pipeline4 := bson.M{
        "$unwind": "$venueList.sum",
    }

    pipeline5 := bson.M{
        "$group": bson.M{
            "_id": "$venueList.sum.name",
            "count": bson.M{
                "$sum": "$venueList.sum.value",
            },
        },
    }
    pipeline6 := bson.M{
        "$group": bson.M{
            "_id": bson.NewObjectId(),
            "counts": bson.M{
                "$push": bson.M{
                    "name":  "$_id",
                    "value": "$count",
                },
            },
        },
    }

    all := []bson.M{pipeline1, pipeline2, pipeline3, pipeline4, pipeline5, pipeline6}
    pipe := col.Pipe(all)

    result := []bson.M{}
    err := pipe.All(&result)
    println(result[0])
    if err != nil {
        println(err.Error())
        errMsg := "Error occourred while getting dashboard configs from mongo stack:" + err.Error()
        log.Error()
        return result, errors.New(errMsg)
    }
    return result, nil
}

I have create a pipline and serve it into pipe.All() but there is null result return from the result varible.
I want to return following object in result
{ "_id" : ObjectId("57f73573d6e0ac1a9f2ab346") , "counts" : [ { "name" : "ubuntu", "value" : 1 }, { "name" : "linux", "value" : 14 } ] }

A: Finally I find the solution.I like to share it with stackoverflow community.
I refer this one : google group answer
 session := commons.GetMongoSession()
    defer session.Close()

    pipeline := []bson.D{
        bson.D{
            {"$match",
                bson.M{
                    "venueList.id": bson.M{"$in": []string{"VID1212", "VID4343"}},
                },
            },
        },
        bson.D{
            {"$unwind", "$venueList"},
        },
        bson.D{
            {"$match",
                bson.M{
                    "venueList.id": bson.M{"$in": []string{"VID1212", "VID4343"}},
                },
            },
        },
        bson.D{
            {"$unwind", "$venueList.sum"},
        },
        bson.D{
            {"$group",

                bson.M{
                    "_id": "$venueList.sum.name",
                    "count": bson.M{
                        "$sum": "$venueList.sum.value",
                    },
                },
            },
        },
        bson.D{
            {"$group",
                bson.M{
                    "_id": bson.NewObjectId(),
                    "counts": bson.M{
                        "$push": bson.M{
                            "name":  "$_id",
                            "value": "$count",
                        },
                    },
                },
            },
        },
    }

    query := bson.D{
        {"aggregate", "useragents"}, // useragents is a collection name
        {"pipeline", pipeline},
    }

    var res interface{}
    err := session.DB("analytics").Run(query, &res)
    if err != nil {
        println(err.Error())
    } else {
        println(res)
    }


text:
Q: Hashmap + Insertion Order I read about HashMap and it says insertion order is not maintained. I have executed below code and for 10,000 times response is returned in same order.
Also in key, I am just changing prefix from E to M. Can someone please help in explaining this behavior?
for ( int i = 0; i < 10000; i++ ) {
            Map<String, String> map1 = new HashMap<String, String>();
            map1.put( "E._AUTO", "20");
            map1.put( "E._ITERATIVE", "20");
            map1.put( "E._ANDREW", "20");
            System.out.println(map1);

            Map<String, String> map2 = new HashMap<String, String>();
            map2.put( "M._AUTO", "20");
            map2.put( "M._ITERATIVE", "20");
            map2.put( "M._ANDREW", "20");
            System.out.println(map2);
        }

Output:
{E._ANDREW=20, E._ITERATIVE=20, E._AUTO=20}
{M._ITERATIVE=20, M._AUTO=20, M._ANDREW=20}

A: The natural implementation of HashMap loses information on what order it's elements got inserted into the Map. That's it really, this means that you lose this information if not tracking it explicitly. This doesn't say anything about two identically filled HashMap's contents and order of contents. When an element is inserted, the algorithm puts it in the nearest possible place in the Map (these are hidden from you). If you put the same objects in the same order into two maps, it's only logical they will look similar. You still lose information about the order in which you put your elements in the Map.

A: It would appear at first glance from your example code that HashMap's output ordering of a given set of Strings will always be the same depending on input order because:

*

*HashMap uses hashCode

*hashcode on a string is consistent for any given String †
However, the Java HashMap in it's current form may change the ordering as more elements are inserted (changing the hash table size), or for different insertion order of the same String set. For example:
for (int i = 1; i < 15; i++) {
//for (int i = 14; i > 0; i--) {
    map1.put(String.format("%04d", i), "");
    System.out.println(String.format("%04d:", i) + map1);
}

Running that forwards and backwards yields different iteration ordering after 14 insertions. Also between inserting "0013" and "0014" (running forwards) the last few elements are the same but the iteration order is changed:
0013:{... 0012=, 0003=, 0011=, 0002=, 0010=, 0009=, 0008=}
0014:{... 0003=, 0012=, 0002=, 0011=, 0009=, 0008=, 0010=}
This may look random, but run it again and it will happen in exactly the same way. Therefore this particular implementation is unpredictable in it's ordering as elements are inserted, but deterministic given the same starting and input conditions. I emphasise implementation as, in J7 (u6+), you can change this behaviour for various hash-based collections using java -Djdk.map.althashing.threshold=<threshold> such that, across different JVM instances on the same machine, this behaviour becomes unpredictable.
Consistent hash-based map ordering
LinkedHashMap will maintain iteration order (normally insertion-order). If you want to play around with the differences between the two, you can see the results more clearly with non value-based hashCodes. You could wrap the String as so:
class StrCont {
    private String s;
    public StrCont (String s) { this.s = s; }
    public String toString() { return this.s; }
    // uses the Object.hashCode implementation
}

The StrCont class uses the default hashCode from Object. Therefore it is (generally) a hexString of the memory location for the object; the wrapped String becomes irrelevant to the hash. Using that as your key:
    map1.put( new StrCont("E._AUTO"), "20");
    map1.put( new StrCont("E._ITERATIVE"), "20");
    map1.put( new StrCont("E._ANDREW"), "20");
    // need only 5/6 more than this to highlight the differences

Repeating this more than once produces new object references with the same String "value", but totally different hashCodes. Ordering is completely destroyed for the HashMap, and maintained for the LinkedHashMap.
TLDR: Value-based hashCodes (such as those from String) in your current JRE's HashMap implementation are a distracting case where, because of your chosen implementation's (also internal state-based) determinism, you may start to think all HashMaps give a consistent ordering based on the hashCode.
But if you depend on consistent iteration ordering you need to use an ordered hash map such as LinkedHashMap.
† While this is true (in J7 only) from J7u6 there is a hash32 function which maps may use if they have been switched to use the alternative hashing method with java -Djdk.map.althashing.threshold=<minEntries>. This can therefore produce different ordering for the same String key input sequences even between restarts of a given JVM on the same machine.

A:
I have executed below code and for 10,000 times response is returned in same ordered.

That's just what happens to occur with the version you're using and the values you're inserting. There's no guarantee it will continue to occur, or that insertion order is maintained if you add different values, or if you remove items then add others.
Basically, it's not saying that it definitely won't be in a particular order - it's saying that you absolutely should not rely on it being in that order.
Also note that if you expected insertion order to be maintained, your examples already demonstrate that it's not. The output shows items not being presented in insertion order.
LinkedHashMap will maintain insertion order, by maintaining a linked list of entries alongside the hash map internally. (An exception here is that there's a constructor which allows you to specify that items will be presented in access order rather than insertion order, which is usually used when you want this as the basis of a cache.)


text:
Q: updating component primefaces datepicker with pattern "MMMM yyyy" via ajax call leads to "uncaught name at position [...]" exception I have a primeface datepicker inside a modal dialog. Setting the initial date with the pattern "MMMM yyyy" (german) works fine. When i am trying to update the componenent via an ajax call im getting the javascript exception "uncaught name at positon [...]".
I am using Primefaces 7.0 and wrote a Year Month Converter by myself.
PrimeFaces locale:
PrimeFaces.locales['de'] = {
    closeText: 'Schließen',
    prevText: 'Zurück',
    nextText: 'Weiter',
    monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
    monthNamesShort: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
    dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
    dayNamesShort: ['Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam'],
    dayNamesMin: ['S', 'M', 'D', 'M ', 'D', 'F ', 'S'],
    weekHeader: 'Woche',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: '',
    timeOnlyTitle: 'Nur Zeit',
    timeText: 'Zeit',
    hourText: 'Stunde',
    minuteText: 'Minute',
    secondText: 'Sekunde',
    currentText: 'Aktuelles Datum',
    ampm: false,
    month: 'Monat',
    week: 'Woche',
    day: 'Tag',
    allDayText: 'Ganzer Tag',
};

Converter:
/**
 * The Class YearMonthConverter.
 */
@Slf4j
@SuppressWarnings("common-java:DuplicatedBlocks")
@FacesConverter(value = "yearMonthConverter")
public class YearMonthConverter implements Converter {

    private static final String PATTERN = "MMMM yyyy";

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        String componentPattern = extractPattern(uiComponent);
        String pattern = componentPattern.equals("") ? PATTERN : componentPattern;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.GERMANY);

        try {
            return YearMonth.parse(s, formatter);
        } catch (DateTimeParseException e) {
            log.warn("conversion of date '{}' expected pattern '{}' failed with {}", s, pattern, e);
            return YearMonth.now();
        }
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        if (o instanceof YearMonth) {
            String componentPattern = extractPattern(uiComponent);
            String pattern = componentPattern.equals("") ? PATTERN : componentPattern;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.GERMANY);

            return formatter.format((YearMonth) o);
        } else {
            return null;
        }
    }

    private String extractPattern(UIComponent component) {
        // try to get the pattern from component
        if (component instanceof Calendar) {
            Calendar calendarComponent = (Calendar) component;
            return calendarComponent.getPattern();
        } else if (component instanceof DatePicker) {
            DatePicker datepickerComponent = (DatePicker) component;
            return datepickerComponent.getPattern();
        }

        return "";
    }
}

Example xhtml-file:
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:p="http://primefaces.org/ui"
      xmlns:composite="http://java.sun.com/jsf/composite"
      xmlns:h="http://xmlns.jcp.org/jsf/html">

<composite:interface>

</composite:interface>

<composite:implementation>

    <style type="text/css">
        .ui-panel .ui-panel-content {
            padding: 0;
        }
    </style>

        <!-- modaler someDialog -->
        <p:dialog id="someDialog"
                  header="some header"
                  widgetVar="someDlg"
                  modal="true"
                  width="500"
                  height="280"
                  resizable="false"
                  closeOnEscape="true">

            <p:panel id="pnlContent" styleClass="ui-noborder">
                <p:panelGrid id="inputArea" columns="2">
                    <p:outputLabel value="Label:" style="width: 12em; display: block;"/>
                    <p:outputLabel value="example"
                                   style="display: block;"/>

                    <p:outputLabel value="Monat:" style="width: 12em; display: block;"/>
                    <h:panelGroup>
                        <!-- Monat zurück -->
                        <p:commandButton
                                id="btnPrevMonth"
                                action="#{someDialogVC.previousMonth}"
                                style="padding: 2px"
                                icon="fa fa-angle-double-left"/>
                        <!-- Monatsanzeige -->
                        <p:datePicker id="dpMonat" view="month"
                                      value="#{someDialogVC.state.selektierterMonat}"
                                      converter="yearMonthConverter" pattern="MMMM yyyy" yearNavigator="true"
                                      yearRange="2000:2050" inputStyle="width: 17em;" readonlyInput="true">
                            <p:ajax event="dateSelect" listener="#{someDialogVC.monthChanged}"/>
                        </p:datePicker>
                        <!-- Monat vor -->
                        <p:commandButton
                                id="btnNextMonth"
                                action="#{someDialogVC.nextMonth}"
                                style="padding: 2px"
                                icon="fa fa-angle-double-right"/>
                    </h:panelGroup>
                </p:panelGrid>

                <p:separator style="border-color: #aaaaaa; margin-bottom: 10px;"/>

                <div style="display: flex; justify-content: flex-end">
                    <p:commandButton id="btnCreate"
                                     value="Anlegen"
                                     action="#{someDialogVC.createAndExit()}"
                                     disabled="#{someDialogVC.doGetAnlegenDisabled()}"/>
                </div>
            </p:panel>

            <p:blockUI block="pnlContent" trigger="btnCreate">
                <p:graphicImage name="images/loader.gif"/>
            </p:blockUI>

        </p:dialog>

</composite:implementation>

</html>

setting initial date in bean:
    @PostConstruct
    public void init() {
        data = new someDialogVO();
        state = new someDialogVS();

        state.setSelektierterMonat(YearMonth.now());
    }

code snippets bean:
    public void previousMonth() {
        state.setSelektierterMonat(state.getSelektierterMonat().minusMonths(1L));
        updateMonat();
    }

    public void nextMonth() {
        state.setSelektierterMonat(state.getSelektierterMonat().plusMonths(1L));
        updateMonat();
    }

    private void updateMonat() {
        PrimeFaces.current().ajax().update("contentForm:someDialog:dpMonat");
    }

After the ajax update call i am able to see, that the new Month is selected visually but after some milliseconds i am getting the described javascript exception. When using the pattern "MM.yyyy" everything works fine.

A: This appears to be a problem with the datePicker component. I have tried reproducing this with a minimalistic test:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui">

<h:head>
    <script>
    PrimeFaces.locales ['de'] = {
            closeText: 'Schließen',
            prevText: 'Zurück',
            nextText: 'Weiter',
            monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ],
            monthNamesShort: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez' ],
            dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
            dayNamesShort: ['Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam'],
            dayNamesMin: ['S', 'M', 'D', 'M ', 'D', 'F ', 'S'],
            weekHeader: 'Woche',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix:'',
            timeOnlyTitle: 'Nur Zeit',
            timeText: 'Zeit',
            hourText: 'Stunde',
            minuteText: 'Minute',
            secondText: 'Sekunde',
            currentText: 'Aktuelles Datum',
            ampm: false,
            month: 'Monat',
            week: 'Woche',
            day: 'Tag',
            allDayText: 'Ganzer Tag'
        };
    </script>
</h:head>
<h:body>

    <p:datePicker view="month" locale="de"
        pattern="MMMM yyyy" value="#{monthOverviewController.currentDate}">
    </p:datePicker>

</h:body>
</html>

And sure enough, the same uncaught exception: Unknown name at position 0 occurs, which most likely originates from here. I have tested this with a couple of the translations provided on PrimeFaces' Wiki, all with the same result.
The problem lies within the _setInitValues function in the datePicker component:
_setInitValues: function () {
    var parsedDefaultDate = this.parseValue(this.options.defaultDate);

    this.value = parsedDefaultDate;
    this.viewDate = this.options.viewDate ?
                this.parseValue(this.options.viewDate)
                :
                ((((this.isMultipleSelection() || this.isRangeSelection()) && parsedDefaultDate instanceof Array) ? parsedDefaultDate[0] : parsedDefaultDate) || this.parseValue(new Date()));
    this.options.minDate = this.parseOptionValue(this.options.minDate);
    this.options.maxDate = this.parseOptionValue(this.options.maxDate);
    this.ticksTo1970 = (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000);

    if (this.options.yearRange === null && this.options.yearNavigator) {
        var viewYear = this.viewDate.getFullYear();
        this.options.yearRange = (viewYear - 10) + ':' + (viewYear + 10);
    }

    if (this.options.userLocale && typeof this.options.userLocale === 'object') {
        $.extend(this.options.locale, this.options.userLocale);
    }

    if (this.options.disabledDates) {
        for (var i = 0; i < this.options.disabledDates.length; i++) {
            this.options.disabledDates[i] = this.parseOptionValue(this.options.disabledDates[i]);
        }
    }
},

The defaultDate is the value of the bean property (currentDate) formatted using the components pattern and locale, resulting in our case in the German string. Now the very first instruction in _setInitialValues attempts to parse this date. However, the custom translation has not yet been loaded (see $.extend(this.options.locale, this.options.userLocale); and thus the month name (in most cases) cannot be resolved. This is in my opinion an error in the component and the best/most stable solution should be waiting for an appropriate fix. An intermediate solution (keep in mind this is just a hack at best) would be to copy the JavaScript file and move the loading of the translation up above the first parse:
_setInitValues: function () {
    if (this.options.userLocale && typeof this.options.userLocale === 'object') {
        $.extend(this.options.locale, this.options.userLocale);
    }
    var parsedDefaultDate = this.parseValue(this.options.defaultDate);


text:
Q: Meaning of Down to the? What is the meaning of down to the?
E.g. in this statement:

In order to use this feature, the statements must be exactly the same
  - down to the number of spaces, tabs, capital/small letters.

My understanding of the above statement is that the statement must be exactly the same, including the number of spaces, tabs, capital/small letters.
Am I correct? If not please correct me.

A: Your understanding is correct.
The phrase 'down to' is used to convey a sense of doing something in great detail, often with the implication of a 'wider' starting point, e.g.,

He cleaned the car from top to bottom, from washing and waxing the paintwork, down to polishing the wheels and vaccuuming the carpets

A: There's also down to the wire, meaning that something is not completed until the very last moment (whether by procrastination, unavoidable delays, or even very close results). http://idioms.thefreedictionary.com/down+to+the+wire http://en.wiktionary.org/wiki/down_to_the_wire http://www.knowyourphrase.com/phrase-meanings/Down-to-The-Wire.html
For other "down to" expressions: http://esl-bits.net/idioms/id174.htm


text:
Q: Unable to deploy Talend job web service I am trying to deploy a Talend (V5.4.1) job service by following the guide here: https://help.talend.com/display/KB/Deploying+or+exposing+a+job+as+a+Web+service
I am able to generate the .war file and to place the .war file into tomcat/webapp folder, but the "error" shows up when I try to call the web service in the browser:

"patchSolrIndexUpdate_0.1" is the job I created on Talend, it works fine when I run it manually.
I have also added axis.jar files into my tomcat/lib, but it does not help. Is anyone experienced in the similar behavior? Thanks for help.

A: Okay, I got this issue solved. It's really stupid, the url should be localhost:8080/patchSolrIndexUpdate_0.1/services/patchSolrIndexUpdate?method=runJob
instead of
localhost:8080/patchSolrIndexUpdate_0.1/services/patchSolrIndexUpdate_0.1?method=runJob.
Can't believe this took me a day to figure out that extra string _0.1 ....


text:
Q: Using Input in Laravel I'm trying to style certain contains on a page based on whether a form field contains a value when submitted.  In my blade template I've got the following code:
@if (Input::has('field'))

@else

@endif

However, Input::has() seems to always return false.  I know that the data is there however because I can populate the form field itself like this:
{{Form::text('field', Input::old('field'))}}

The same Input::has('field') call will return true in the post method on my controller however.  Does this mean that the has method doesn't look at the data in the old array?  If not, what would be a good alternative to my approach?

A: Just use Input::old() - which contains the data. Input::has() is for the controller using your post data.
This should work:
@if (Input::old('field'))

@else

@endif

A: Input::has() does not take session-bound data (aka old input) into consideration, so it will not be useful for checking for a value in that way.
How about using CSS by itself? You can target element attributes in CSS -- in this case, the value attribute.
/* Target all inputs. */
input { color: #444; }

/* Target all inputs that have a "value" attribute defined (even if empty) */
input[value] { color: #bada55; }

Note that this will only work if the value attribute is not that entirely. If it is defined but empty, the new color will still take precedence. So this solution may or may not work, entirely dependent on how your HTML is generated. Food for thought.


text:
Q: Linear algebra. Functional analysis. For which a set of vectors in three-dimensional space, the coordinates of which are given by the equations $$x + y + z = 0, \\ 3(x + 4)-a = 0$$, is a linear subspace in the linear space of all vectors?
I know that a subset of $A$ is a subspace of a linear space $M$, it must also be a linear space and it is necessary and sufficient that the operations of addition and multiplication by a number do not lead beyond the limits of this subset. How can I show this? First prove the axioms of a linear space?


text:
Q: Use Flickity to group years on history timeline I am new to Flickity and have been trying to emulate the following timeline setup history timeline slider. This site is using Flickity to display the history timeline. I have the basic code working, but have been unable to figure out how to connect the data-nav and data-nav-title attributes together in order to keep the specific years grouped together. The following code from the Nature site seems to control the grouping, but I am unsure of how to implement it on my setup. I have created a demo here on Codepen.
e.on("select.flickity",function(j) {
    var l=b(j.target);
    var f=l.closest(".c-timeline__wrapper");
    var g=l.data("flickity");
    var i=f.find(".carousel-nav");
    var k=i.find(".carousel-cell");
    var h=l.find(".carousel-cell").eq(g.selectedIndex).data("navTitle");
    k.filter(".is-nav-selected").removeClass("is-nav-selected border-secondary");
    k.filter('[data-nav="'+h+'"]').addClass("is-nav-selected border-secondary")
});

b(".carousel-nav").on("click",".carousel-cell",function(h) {
    var i=b(h.target);
    var k=i.data("nav");
    var g=i.closest(".c-timeline__wrapper");
    var f=g.find(".carousel-main");
    var j=f.find(".carousel-cell").filter('[data-nav-title="'+k+'"]').eq(0).index();
    f.flickity("select",j)
})
};


text:
Q: Cannot set property '$submitted' of undefined error - Jasmine AngularJS I am trying to test a function of my controller, Inside that function I trying to set the $submitted property of form like following.
$scope.submitForm=function(){
     $scope.form.$submitted = false;
     $scope.done = true;
     // code
};

When I call this function from my test like:
it('should be called', function () {
     contactUsController.submitForm();
     expect(contactUsController.submitForm).toHaveBeenCalled();
});

Error:
TypeError: Cannot set property '$submitted' of undefined

A: You need to initialize $scope.form as an object before you can set properties on it. Otherwise you are setting a property on a non existant object and hence get an error of can't set property of undefined.
Just edit your code like this:
$scope.submitForm=function(){
     $scope.form = {};
     $scope.form.$submitted = false;
     $scope.done = true;
     // code
};

A: As my comment helped, add below code in the beginning of the controller:
$scope.form = {};


text:
Q: Limit the redirection of pages using htaccess file I want to redirect some pages of my site.
These pages have the following form:
xxxx.html (x=digit, up to 4 digits), eg 1.html, 24.html, 6875.html etc
I want to redirect these pages to the following format:
index.php?id=xxxx.
The solution I have already apply is the following line in the htaccess file:
RewriteRule ([0-9]+)\.html$ /index.php?id=$1  [R=302,QSA,L]

The redirection works perfectly but the problem is that I want to limit this rule for pages that have up to 4 digits, eg 6789.html, 234.html.
For example I don't want the rule to be applied for the page 55555.html.

A: This is probably what you are looking for:
RewriteEngine on
RewriteRule ^/?([0-9]{1,4})\.html$ /index.php?id=$1  [R=302,QSA,L]

That slightly modified pattern will work in the http servers host configuration and likewise in dynamic configuration files (.htaccess style files).

And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).


text:
Q: How can I get a divID located inside an iframe from the head in HTML using JS? I want to create a div inside an iframe, call the divID and change it. Can it be done from the head using JS?
Here is what I tried and won't work for me:

console.log(document.getElementById("mydiv").id);
document.getElementById("myDiv").setAttribute("id", "MyDiv2");
console.log(document.getElementById("MyDiv2").id);

This is mydiv


text:
Q: Using custom URL to make an state change in ionic app i have to redirect to a certain page in ionic app when app is loading from an external URL.

*

*i want to redirect to another state from handleOpenURL callback.


text:
Q: Verifying the existence of a derivative of an absolute value function at x = 0. I've been struggling with this question for a while, and any advice would be greatly appreciated.

A: For $x>0$ we have $f(x)=x^4$, hence $f'(x)=4x^3$.
For $x<0$ we have $f(x)=-x^4$, hence $f'(x)=-4x^3$.
For $x=0$ we use the definition:
$$\frac{f(h)-f(0)}{h}=|h^3|=|h|^3 \to 0$$
as $h \to 0.$ Hence $f$ is differentiable at $0$ and $f'(0)=0.$

A: Your derivative calculation is correct but can be simplified in a different way for making the differentiability of $f$ much more obvious. By definition, $$\frac{d}{dx}(|x|)=\frac{x}{|x|}.$$
Now, if $f(x)=x|x^3|$, we can rewrite as $$f(x)=x|x^2 \cdot x|=x\cdot x^2\cdot |x|=x^3|x|.$$ Taking the derivative, we have
\begin{align*} f'(x)&=3x^2 |x| + x^3\cdot\frac{x}{|x|}\\
&=\frac{3x^2\cdot|x|^2 + x^4}{|x|}\\
&=\frac{4x^4}{|x|}\\
&=\frac{4x^2\cdot|x|^2}{|x|}\\
&=4x^2 |x|. \end{align*}
So, it is obvious now that the derivative exits at $x=0$. But as I said, one could derive at this result even from your calculation as follows:
\begin{align*}
\frac{4x^6}{|x^3|} &= \frac{4\cdot|x^3|^2}{|x^3|}\\
&= 4|x^3|\\
&= 4x^2|x|.
\end{align*}


text:
Q: How to fix "Invalid regular expression" in react-native? E:\React-Native\reactnativeapp>npm start
I passed this command for compile my project in VS code via NPM command but last time its gave me error.
> @ start E:\React-Native\reactnativeapp
> expo start

Starting project at E:\React-Native\reactnativeapp

Expo DevTools is running at http://localhost:19002

Opening DevTools in the browser... (press shift-d to disable)

error Invalid regular expression:
 /(.*\\__fixtures__\\.*|node_modules[\\\]react[\\\]dist[\\\].*|website\\node_modules\\.*|heapCapture\\bundle\.js|.*\\__tests__\\.*)$/: Unterminated character class. Run CLI with --verbose flag for more details.

Metro Bundler process exited with code 1

Set EXPO_DEBUG=true in your env to view the stack trace.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ start: `expo start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Ashish\AppData\Roaming\npm-cache\_logs\2019-11-08T06_13_41_377Z-debug.log


text:
Q: Windows 10 screen shot of active window is offset. C# Winforms I have a C# application Winforms .Net 3.5 that takes a screenshot of itself. When running under Windows 7, it works fine, but under Windows 10, the screenshot is offset from the window. With 100% magnification, the screenshot is just a little larger than the window, showing a few pixels of the background on the sides and bottom. But for larger magnifications, it shows a frame that is offset to the upper left by an amount that increases with the magnification level. Since this application needs to be run on laptops where the magnification is necessary (particularly for those of us with old eyes), this is a significant issue.
The code taking the screenshot is
Rectangle bounds = this.Bounds;
using (Bitmap ScreenShot = new Bitmap(bounds.Width, bounds.Height))
{
    // code hiding a few controls on the form (control.Visible = false)
    this.Update();
    using (Graphics G = Graphics.FromImage(ScreenShot))
    {
        G.CopyFromScreen(bounds.Left, bounds.Top, 0, 0, bounds.Size);
    }
    // code unhiding the same elements
    SaveScreenshot(Screenshot);
}

The application was originally compiled under Windows 7 using VS2008, but recompiling it under Windows 10 with VS2017 hasn't solved the issue.
Any ideas what would cause this to go wrong under Windows 10, but not Windows 7?
I would prefer not to have to upgrade to a later version of .Net if possible.
Here is a sample of the screenshots it is providing at 125% magnification.


text:
Q: $\frac{301 \times 16}{7} = ?$ How to estimate the answer?
Though  we can get it's exact number , we have to estimate the result.
My Attempt: $301 \approx 300$ and $\frac{16}{7} = 2\frac{2}{7} \approx  2\frac{2}{8} = \frac{9}{4} $
So $\frac{301}{\frac{7}{16}} \approx \frac{300  \times 9}{4} = 675$
Can anyone give any better method?

A: I have no idea what "excellent number sense" is, but if you showed me that calculation and said "you have 3 seconds to estimate the result", my estimate would be "about $630$".
My reasoning would be

Welll, $\frac{7}{16}$ is a little less than a half, so dividing by it will multiply the number by a little more than $2$. Twice $301$ is $602$, so a little more than that is $630$.


text:
Q: How to make a cost effective but scalable site? Portal Technology Assessment in which we will be creating a placement portal for the campuses and industry to help place students. The portal will handle large volumes of data and people logging in, approximately 1000 users/day in a concurrent mode.
What technology should i use? PHP with CakePHP as a framework, Ruby on Rails, ASP.NET, Python, or should I opt for cloud computing? Which of those are the most cost beneficial?

A: Any of those will do, it really depends on what you know. If you're comfortable with Python, use Django. If you like Ruby go with ROR. These modern frameworks are built to scale, assuming you're not going to be developing something on the scale of facebook then they should suffice.
I personally recommend nginx as your main server to host static content and possibly reverse-proxy to Django/mod_wsgi/Apache2.
Another important aspect is caching, make sure to use something like memcached and make sure the framework has some sort of plugin or it's easily attachable.

A: Language choice is important as you must choose language that you and your team feel the most comfortable with as you must develop mid-large size application. Of course use framework with Python it must be Django, with ASP.NET .NET or MVC.NET whatever you feel better with with Ruby ROR and with PHP there are too large amount of frameworks.
1000 concurrent users is not that much, especially it depends what users will do. Places where users will get large amount of data are better to Cache with with any caching engine you want. You need to design application this what so you can easily swap between real DB calls and calls to cache. For that use Data Objects like for Logins create an Object array of course if you need it. Save some information in cookies when user logins for example his last login, password in case he wants to change it, email and such so you will make less calls to DB in read mode ( select queries ).
use cookie less domain for static content like images, js and css files. setup on this domain the fastest system you can with simplest server you can, probably something based on Linux.
For servers, best advice is to either get large machine and set Virtual Boxes on it with vmware or other Linux based solution or to get few servers which is better because if on big server down you lost everything if one of 1 is down you still can do some stuff. Especially if you set railroad mode. Railroad mode is simple you set up Application server (IIS or Apache) on one server and make it master while you set up SQL on the same server and make it slave. On other server you set up SQL as master and Application server as slave. So server one serves IIS/Apache and Other one SQL, if one down you just need to change line in host.etc in order to set something somewhere else ( i don't know how to do that in Linux ).
last server for static content.
Cloud Computing, you will use if you want it or not. You will share resources with some applications as Google API for jquery and jqueryUI for instance but you create unique application and  i don't believe making core of application based on cloud computing will do any good. Use large site's CDNs for good.


text:
Q: TimeoutException Traceback (most recent call last) Im having this problem with this code, when y try to get a ID by xpath it wont let me
TimeoutException                          Traceback (most recent call last)
Cell In [118], line 2
1 wait=WebDriverWait(driver,20)
----> 2 wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="_id0:logon:USERNAME"]')))
File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\support\wait.py:90, in WebDriverWait.until(self, method, message)
88     if time.monotonic() > end_time:
89         break
---> 90 raise TimeoutException(message, screen, stacktrace)
TimeoutException: Message:
Stacktrace:
Backtrace:
This is my code:
from selenium import webdriver from
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

s=Service('webdriver//chromedriver.exe')
driver = webdriver.Chrome(service = s)

driver.get('http://190.109.11.66:8888/BOE/BI')
wait=WebDriverWait(driver,20)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="_id0:logon:USERNAME"]')))

I tried several solutions and didnt work

A: Try to except the error
from selenium import webdriver from
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.common.exceptions import TimeoutException

s=Service('webdriver//chromedriver.exe')
driver = webdriver.Chrome(service = s)

try;
    driver.get('http://190.109.11.66:8888/BOE/BI')
    wait=WebDriverWait(driver,20)
    time.sleep(5) # give selenium a sleep time
    wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="_id0:logon:USERNAME"]')))
except TimeoutException:
    pass


text:
Q: Large text not being saved in Rails I am building a site for managing fiction writing, but the story text isn't being saved. Here's part of my _form.html.erb file for the story scaffold:

    <%= f.label :genre %>
    <%= f.text_field :genre %>

    <%= f.label :content %>
    <%= f.text_field :content %>

    <%= f.label :word_count %>
    <%= f.number_field :word_count %>

    <%= f.label :story_text %>
    <%= f.text_area :story_text, :cols => "100", :rows => "10" %>

    <%= f.submit %>

And here is the show page for the story:

<%= notice %>

<%= @story.title %>

by <%= @story.author %>

<%= @story.story_text %>

<%= link_to 'Back', stories_path %>

The title and author are visible but the story_text isn't. I tried manually inserting via SQL commands, but it stops at line breaks, so I think that has something to do with my problem. I could remove all line breaks, replace them with "\n", and then use gsub to replace \n with the HTML break tag but I would rather fix the form to be able to do that without having to use SQL. I should mention that the data type for story_text is simply "text".


text:
Q: MySQL Subquery result array I want to use an array of (id_1)ids from a selection on table_1 to get all rows from table_2 where id_2 = id_1
  SELECT field_b
  FROM table_2
  WHERE id_2 IN (
         SELECT id_1 FROM table_1 WHERE field_a = 1234
  );

Below are example of my tables for reference:
  mysql> select * from table_1;
    +-------+---------+
    |  id_1 | field_a |
    +-------+---------+
    |     1 |    1234 |
    +-------+---------+
    |     2 |    1234 |
    +-------+---------+

mysql> select * from table_2;
+---------+---------+
|    id_2 | field_b |
+---------+---------+
|     1   |  5678   |
+-------+-----------+
|     2   |  0013   |
+-------+-----------+

A: Would an INNER JOIN work just as well well for you?
SELECT field_b
FROM table_2
INNER JOIN table_1
    ON table_2.id_2 = table_1.id_1
WHERE table_2.field_a=1234

A: I don't know if this is what you need:
SELECT * FROM table_2 t2
INNER JOIN table_1 t1
ON t2.id_2 = t1.id_1
WHERE t1.field_a = 1234

A: Another option:
SELECT field_b
FROM table_2
WHERE EXISTS
      ( SELECT *
        FROM table_1
        WHERE field_a = 1234
          AND table_2.id_2 = table_1.id_1
      )


text:
Q: Maths in php giving wrong answer I have a simple equation written in PHP. I have tried to replicate the equation bellow.
When I work out the Equation on pager using the variables I have provided in the PHP I get 2,467.86 (using equation A).
But when I run it in PHP I get 4,2267.11, where have I gone wrong in my PHP ?
Equation A

PHP Equation
<?php
$p = 0;
$i = 0.06;
$c = 12;
$n = 1;
$r = 200;

$x = $i / $c;
$y = pow((1 + $x), ($n * $c));

$vf = $p * $y + (($r * $y - 1) / $x);
?>

Answer:<?php echo $vf; ?>

A: Here:
$vf = $p * $y + ($r * ($y - 1) / $x);
// outputs 2467.1124745799

Your equation was:
$vf = $p * $y + (($r * $y - 1) / $x); // <- NOT $r*$y -1 , but $r*($y-1)

You can see it here - 3v4l


text:
Q: C++: Make class and some of its data members only available in namespace Is it possible to make a class only available inside the namespace? Or is there maybe another way, without using a namespace?
I'm working on creating a framework and don't want the user of this framework to have access to all classes, only to specific ones.
BUT: The user should be able to reach all definitions anyway for creating pointer vars to these classes. Additionally he should not be able to access all data members of these classes, but I want my framework to have access to all data members.
Is that even possible?
Example(just as an explanation for my request):
/* T2DApp.h */
namespace T2D {
    // I don't want the user to be able to create an instance of this class (only pointer vars), but the framework should be able to.
    class T2DApp {
    public:
        // constructor, destructor... //

        SDL_Window*  Window;
        SDL_Surface* Surface;

        bool Running = false;
    }
}

/* T2D.h */
#include "T2DApp.h"

void init();

/* T2D.cpp */
#include "T2D.h"

void init() {
    T2D::T2DApp app;       // function in framework is able to create new instance of T2DApp.
    app.Window.Whatever(); // every data member should be available to framework directly without getter methods.
    app.Window.Whatever(); // dito
    app.Running = true;    // dito
}

/* [cpp of user] */
#include "T2D.h"

void main(etc.) {
    ...
    T2D::T2DApp app;    // User shouldn't be able to create an instance of T2DApp
    T2D::T2DApp* p_app; // but he should still be able to "see" the class definition for creating pointers
    ...
    p_app.Running = true;     // User shouldn't be able to access this data member
    p_app.Window.Whatever();  // But he should be able to access the other data members
    p_app.Surface.Whatever(); // dito
    ...
}

Thank you very much in advance :)

A: It is possible with Pimpl idiom:

"Pointer to implementation" or "pImpl" is a C++ programming technique that removes implementation details of a class from its object representation by placing them in a separate class, accessed through an opaque pointer.


text:
Q: SHA256 For Ruby Not Working On Mac On my mac 10.5 when I use the command OpenSSL::Digest::Digest.new('sha256') I get Unsupported digest algorithm (sha256). Does anyone know how to solve this?

A: The OS X supplied Ruby 1.8.6p287 does not seem to have this compiled in, however the one bundled with MacPorts, 1.8.7p160 does have it.
It's generally better to use the MacPorts version since it is more up-to-date.


text:
Q: Not able to cancel the drag when we exit mouse area I have an slider and an image used for sliding over the slider as shown below.
Image
{
    id: slideImg
    source:  "/slider/SliderSelected.png"
    width: 65
    height: 65

    onDragActiveChanged:
    {

        if (!dragActive )
        {
            main.selection (x + slideImg.width/2 , true);
        }

    }
  property bool dragActive: dragArea.drag.active

}

The mouseArea looks like this :
MouseArea
{
    id: dragArea
    anchors.fill: thumb
    enabled: !isDisabled
    height: 65
    width: 463
    drag
    {
        readonly property int dragThreshold: 10
        target: thumb
        minimumX: 0
        minimumY: 0
        maximumY:100

        maximumX: mainElement.width - thumb.width
        axis: Drag.XAxis
        threshold: dragThreshold
    }
    onCanceled: {
        console.log("onCanceled ")

    }
    onExited: {
        console.log("onExited ")
        Drag.cancel()
    }

}

When i hold the sliderImage and slide it outside the area of the slider i would want to cancel the drag . The drag area should be limited to the mouse area .If we move out of the mouse area i would want to cancel the drag . But the Drag.cancel() is not cancelling the drag . Is there any way to cancel the drag?

A: I am not sure, what you try to achieve by this, but try to unset drag.target
onExited: drag.target = null
onEntered: drag.target = myTarget

I think this should work for you.
But you might also want to look at states (have a dragging state, which is only enabled when the mouse is over the area.
MouseArea {
    id: dragArea
    anchors.fill: parent

    states: [
        State {
            when: dragArea.containsMouse

            PropertyChanges {
                target: dragArea
                drag.target: dragger
            }
        }
    ]
}

You might also want to look at the maximum and minimum X and Y values.
This is probably the thing you are really looking for.
I don't think it is possible to automatically reset the position, but you can easily handle that your self, by storing the ne values in a extra variable, once you legitimately end a drag, and restoring them, once you don't.
I hope I was able to help you!


text:
Q: Libsvm module in Rapidminer Rapidminer has a SVM module based on libsvm. How can I know which version of libsvm it uses?
I tested the SVM classifier against the same data set using both libsvm module in Rapidminer and Libsvm itself, and the resulting prediction score are different even they use the same parameter setting.

A: Just check the RapidMiner's root directory in the file CHANGES.txt (e.g. RM_HOME/CHANGES.txt):
...

*

*Completely revised tree, cluster model, and similarity
visualization

*Latest release of LibSVM integrated (2.84)

*Latest release of xstream integrated (1.2.2)
...


text:
Q: How can I use REST API through OAuth? For test purposes, I'm trying to use some customer's REST API on Salesforce. I don't have any API-consuming code yet (I'm just using CURL, OAuthDebugger, et similia).
I've tried the following this guide, but I'm stuck. This is what I've done:
Phase One: Getting the Authorization Code

*

*I've created a New Connected App with my user's mail

*I've set https://oauthdebugger.com/debug as callback URI

Question n.1: is there another way to get the redirected response?

*I've compiled OAuthDebugger as follows:

*

*Authorize URI: https://test.salesforce.com/services/oauth2/authorize

*Redirect URI: https://oauthdebugger.com/debug

*Cliend ID: my Consumer Key

*Scope: api

*Response type: code

*Response mode: form_post

*I've clicked Send Request, then logged in into Salesforce, and finally authorized the App

*I've been redirected to https://oauthdebugger.com/debug where I successfully got the Authorization Code.

Question n.2: After some time, the Authorization Code expired, but further calls to the same API returned the same (invalid) code again. How can I set/remove its expiration time, and how can I renew it to obtain a new one?

Phase Two: Getting the Token

*At this point, I need to call the Token URL (https://test.salesforce.com/services/oauth2/token) passing the Authorization Code and the Consumer Secret, to get a Token to use for the subsequent REST API calls.
I can't use OAuthDebugger to perform this call, because of the Consumer Secret, so I'm resorting to CURL. I'm not able to get the returning token, by the way.

Question n.3: which callback URL should I use here?

Thanks in advance.

A: So here is my setup in Salesforce:

And then here is what I input into the OAuthDebugger form:

So then when I clicked Send Request, it asked me to login, and then brought me to the authorize page:

And then redirected me back to here:

From there, you want to take the Auth Code that is received and "quickly" perform an grant_type=authorization_code call to get an access token:
POST /services/oauth2/token HTTP/1.1
Host: {your_domain}.salesforce.com
Content-Type: application/x-www-form-urlencoded
cache-control: no-cache
Postman-Token: dd429871-b5ff-4764-b3b5-3a5f3bdac603

grant_type=authorization_code&
client_id={your_client_id}&
client_secret={your_client_secret}&
redirect_uri={your_callback_uri}& //Make sure this is URL encoded
code={your_auth_code} //Make sure this is URL encoded

And this should return you a response similar to this:
{
  "id": "https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P",
  "issued_at": "1278448101416",
  "refresh_token": "5Aep8614iLM.Dq661ePDmPEgaAW9Oh_L3JKkDpB4xReb54_pZebnUG0h6Sb4KUVDpNtWEofWM39yg==",
  "instance_url": "https://yourInstance.salesforce.com/",
  "signature": "CMJ4l+CCaPQiKjoOEwEig9H4wqhpuLSk4J2urAe+fVg=",
  "access_token": "00Dx0000000BV7z!AR8AQP0jITN80ESEsj5EbaZTFG0RNBaT1cyWk7TrqoDjoNIWQ2ME_sTZzBjfmOE6zMHq6y8PIW4eWze9JksNEkWUl.Cju7m4",
  "token_type": "Bearer",
  "scope": "id api refresh_token"
}


text:
Q: MembershipProvider and RoleProvider - do I need to implement all of the required methods? Do I need to implement all the required methods on the MembershipProvider and RoleProvider if writing a custom one to use the AuthorizedAttribute in ASP.NET MVC?
There are a few features that I don't want to implement like CreateUser or 'DeleteRole` because they violate the system I will be authorizing/authenticating against.

A: No, you don't need to implement everything if you never use this functionality. Throwing a NotImplementedException is always a good way to indicate this.

A: I am currently doing the same thing and you don't have to implement all the methods.
You might want to look at the following website.
http://theintegrity.co.uk/2010/11/asp-net-mvc-2-custom-membership-provider-tutorial-part-1/
Great tutorial for implementing a custom membership provider with ASP.NET MVC!

A: No you don't need to implement all methods for the MembershipProvider or RoleProvider; if you never use the API for creating, updating, or deleting, then you could throw an exception when used.  These are there in case you do modify user data, and are also used by the Administration web site option in Visual Studio.  So if you use that web site, it quite won't work as expected as it expects these provider methods to be present.
But if all you do is use the controls, then it would be handy to research which API methods these control use and make sure that you have implementations for those.  What I mean is that Login control uses ValidateUser for sure, and may use GetUser too.  It may also call UpdateUser to update the failed logon count, last login date, etc.
HTH.


text:
Q: Subject of drip the verb
drip verb
  1. let fall or be so wet as to shed small drops of liquid. "the tap won't stop dripping" synonyms:    dribble, drop, leak More antonyms:  gush
  (of liquid) fall in small drops. "water dripped from her clothing"
  cause or allow (a liquid) to fall in small drops. "the candle was
  dripping wax down one side" display a copious amount or degree of a
  particular quality or thing. "the women were dripping with gold and
  diamonds" noun

I am confused with the definition let fall. Instead of tap, can I use water as a subject for drip such as

The water in the tap won't stop dripping

or

The water in the tap drips

?

A: Let fall small drops of liquid is one way to use the verb. If you say "water drips" that meaning is absurd:

Water [lets fall small drops of liquid]. Say what?

However, another given meaning is fall in small drops. That meaning applies when you say "water drips":

Water [falls in small drops]. Just fine.

Now for your sentences, if water falls in small drops, it is unlikely that that is the water in the tap. It is actually water that comes out of the tap that actually drips!

Water drips from the tap.

Without further context, using the could be confusing. However, if you specify the water, the article can be used:

The water dripping from the tap formed a puddle on the floor.


text:
Q: Parse PFUser.currentUser returns nil - Swift I am logging in my users using Parse. As my app opens my LaunchVieWController determines whether users are already signed in or not:
override func viewDidLoad() {
    super.viewDidLoad()

    //Make sure cached users don't have to log in every time they open the app
    var currentUser = PFUser.currentUser()
    println(currentUser)
    if currentUser != nil {
        dispatch_async(dispatch_get_main_queue()) {
            self.performSegueWithIdentifier("alreadySignedIn", sender: self)
        }
    } else {
        dispatch_async(dispatch_get_main_queue()) {
            self.performSegueWithIdentifier("showSignUpIn", sender: self)
        }
    }
}

If users are already signed in they are taken to the table view described below. If they are not logged in, they are taken to a view in which they can go to the signup view or the login view.
My signup works perfectly fine, and signs up users and then redirects them to the table view.
Here is the signup function (it is in a separate controller from the login function):
func processSignUp() {

    var userEmailAddress = emailAddress.text
    var userPassword = password.text

    // Ensure username is lowercase
    userEmailAddress = userEmailAddress.lowercaseString

    // Add email address validation

    // Start activity indicator
    activityIndicator.hidden = false
    activityIndicator.startAnimating()

    // Create the user
    var user = PFUser()
    user.username = userEmailAddress
    user.password = userPassword
    user.email = userEmailAddress

    user.signUpInBackgroundWithBlock {
        (succeeded: Bool, error: NSError?) -> Void in
        if error == nil {

            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("signInToNavigation", sender: self)
            }

        } else {

            self.activityIndicator.stopAnimating()

            if let message: AnyObject = error!.userInfo!["error"] {
                self.message.text = "\(message)"
            }
        }
    }
}

My login function looks like so:
@IBAction func signIn(sender: AnyObject) {
    var userEmailAddress = emailAddress.text
    userEmailAddress = userEmailAddress.lowercaseString
    var userPassword = password.text

   PFUser.logInWithUsernameInBackground(userEmailAddress, password:userPassword) {
        (user: PFUser?, error: NSError?) -> Void in
        if user != nil {
            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("signInToNavigation", sender: self)
            }
        } else {
            if let message: AnyObject = error!.userInfo!["error"] {
                self.message.text = "\(message)"
            }
        }
    }
}

After users log in they are sent to a table view. In that table view I am trying to access the current user object in the following function, as I want to load different data based on who the user is:
override func queryForTable() -> PFQuery {
    var query = PFQuery(className:"MyClass")
    query.whereKey("userID", equalTo: PFUser.currentUser()!)
    return query
}

When I try to log in with a user I get thrown the following error: "fatal error: unexpectedly found nil while unwrapping an Optional value". It seems like the PFUser.currentUser() object is nil.
When users are sent to the table view after signing up the PFUser.currentUser() object is set and works perfectly.
My guess is that this is because of the fact that the PFUser.logInWithUsernameInBackground is happening in the background and that my query is trying to get the PFUser.currentUser() object before it has been loaded. Is there anyway I can work around this issue? In the table view the value of PFUser.currentUser() is needed to load the table data. Can I somehow make sure that PFUser.currentUser() gets assigned with the current user object before the function gets called (for example, by not loading in users in the background thread)?
All help is much appreciated!
EDIT: I've updated this post with some more of my code to help highlight any bug that I may be missing.

A: I discovered that this problem appeared because the segue signInToNavigation was wired from the Login-button, instead from the login view controller itself. This resulted in the segue being executed before the login function was executed, and therefore the PFUser.currentUser()object was not yet assigned when the table view loaded. I solved this by rewiring the segues. Stupid slip-up on my side.
Thanks to Ryan Kreager and Wain for taking time to help me figure out this issue!

A: You can try checking if PFUser.currentUser() != nil instead to make sure it's being set right after login. If it's not being set right off the bat, you know there is a deeper login problem.
Also, try removing the dispatch_async(dispatch_get_main_queue()){ wrapper around your call to the segue.
It's unnecessary (logInWithUsernameInBackground already returns to the main thread) and I have a hunch that it's creating a racing condition where the local object is not being set first because Parse can't do any post-call cleanup since you're going right for the main thread.


text:
Q: An elegant way to solve $\frac {\sqrt3 - 1}{\sin x} + \frac {\sqrt3 + 1}{\cos x} = 4\sqrt2 $ The question  is to find $x\in\left(0,\frac{\pi}{2}\right)$:
$$\frac {\sqrt3 - 1}{\sin x}  + \frac {\sqrt3  + 1}{\cos x} = 4\sqrt2 $$
What I did was to take the $\cos x$  fraction    to the right and try to simplify ;
But it looked very messy and trying to write $\sin x$  in terms of $\cos x$ didn't help.
Is there a more simple (elegant) way to do this.

A: Another approach is to write the equation as
$(\sqrt{3} - 1) \cos x +(\sqrt{3} + 1) \sin x = 4 \sqrt2 \sin x \cos x$
then rearranging gives
$\frac{\sqrt{3} - 1}{2 \sqrt{2}} \cos x +\frac{\sqrt{3} + 1}{2 \sqrt{2}} \sin x = 2  \sin x \cos x$.
Now note that $(\frac{\sqrt{3} - 1}{2 \sqrt{2}})^2 +(\frac{\sqrt{3} + 1}{2 \sqrt{2}})^2 = \frac{1}{8} ((3 -2 \sqrt{3} + 1) + (3 +2 \sqrt{3} + 1) = 1$ so that we can write $\frac{\sqrt{3} - 1}{2 \sqrt{2}}$ as the $\sin$ of some angle, say $\alpha$, and identify $\frac{\sqrt{3} + 1}{2 \sqrt{2}}$ as $\cos \alpha$.
Then you have to solve $\sin(\alpha + x) = \sin(2x)$, with $\tan \alpha = \frac{\sqrt{3} - 1}{\sqrt{3} + 1}$.

A: Replace $\sqrt3=\tan60^\circ,1=\tan45^\circ$
to find $$\sin(15^\circ+x)=2\sin x\cos x=\sin2x$$
Now if $\sin y=\sin A, y=n180^\circ+(-1)^nA$ where $n$ is any integer
As $\sqrt3-1=\tan60^\circ-\tan45^\circ=\dfrac{\sin(60-45)^\circ}{\cos60^\circ\cos45^\circ}=2\sqrt2\sin15^\circ$
Similarly, $\sqrt3+1=2\sqrt2\sin75^\circ=2\sqrt2\cos15^\circ$

A: $\sin(\frac{\pi}{12}) = \frac{\sqrt{3}-1}{2\sqrt{2}}$ and $\cos(\frac{\pi}{12}) = \frac{\sqrt{3}+1}{2\sqrt{2}}$. Plugging them into your equation yields $\sin(x+\frac{\pi}{12}) = \sin(2x)$. So $x = \frac{\pi}{12}$


text:
Q: Search Controller .dimsBackgroundDuringPresentation also dims Status Bar? I have a function to set up my Search Controller which I add to View Did Load.
func setUpSearchController() {
        searchController.delegate = self
        searchController = UISearchController(searchResultsController: nil)
        searchController.hidesNavigationBarDuringPresentation = true
        searchController.dimsBackgroundDuringPresentation = true
        searchController.searchBar.sizeToFit()
        searchController.searchBar.backgroundColor = .white
        searchController.searchBar.barTintColor = .white
        searchController.searchBar.placeholder = "Search"
        searchController.searchBar.searchBarStyle = .minimal
        searchController.searchBar.tintColor = Colours.brandGreen
        definesPresentationContext = true
        messagesTableView.tableHeaderView = searchController.searchBar
    }

When clicking on the Search Bar the Search Controller dims the background as expected by
searchController.dimsBackgroundDuringPresentation = true

The issue is it also dims the status bar making the UI look ugly.  Anyone know how to exclude the status bar from also being dimmed?
As always any help greatly appreciated.  Illustration below.

Update
I realise I'm using the Search Controllers Search Bar inside the TableView Header and changing this from
messagesTableView.tableHeaderView = searchController.searchBar

to
navigationItem.searchController = searchController

I get the desired result.  However, I'd still like the Search Controllers Search Bar inside the Table Views header.


text:
Q: How to pass ConnectionString from appsettings.json file to class library project in dot net core 2.2 I have two projects in my solution. One is an angular core 2.2 web application and other is a class library project which contains the domain models and the dbcontext.
I want to pass the connection string to dbcontext so that i can create the database using the code first approach.
this is my connection string
"ConnectionStrings": {
"DataConnection": "Server=.;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=True;"

this the code in the ConfigureService Method
 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<TestContext>(context => context.UseSqlServer(Configuration.GetConnectionString("DataConnection")));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

}
And this is my DBContext
public class TestContext : DbContext
{
 public CCPGV1Context(string connectionString):base(connectionString)
    {

    }

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);
    }
}

I am new to code first approach as well as dot net core. Please guide me what should i do !

A: Since you are configuring your connection string as a service, you could simply inject the constructor of your DbContext class like this:
public class TestContext : DbContext
  {
  public TestContext(DbContextOptions<TestContext> options):base(options)
         {

         }
   }

A: You have to pass the IConfiguration interface as a parameter, from Microsoft.Extensions.Configuration to the contructor of Startup class (name it whatever, for example purposes, I will call it _configuration).
Then, replace this line
services.AddDbContextPool<TestContext>(context => context.UseSqlServer(Configuration.GetConnectionString("DataConnection")));

with this one:
services.AddDbContext<TestContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DataConnection")));

After thar, add this constructor to you TestContext class:
public TestContext(DbContextOptions<TestContext> options) : base(options)
        {

        }

This for seed the DBContextOptions class with the configuration stablished for TestContext in Startup.cs


text:
Q: I don't understand this error when passing paramters by reference I'm trying to run this program in another file(main.cc) but I get an error on this class, where this is the error.
ERROR
./Library.h:15:24: error: expected ')'
    Library(Book[] &book, int &currentNumOfBooks);
                   ^
./Library.h:15:16: note: to match this '('
        Library(Book[] &book, int &currentNumOfBooks);
               ^

CODE SOURCE:
class Library{

public:

    Book booksLibrary[MAX_ARR_SIZE];
    int currentNumOfBooksLibrary;
    Library();
    Library(Book[] &book, int &currentNumOfBooks);
    void addBook(Book &book);
    void print();
private:
}:


text:
Q: Why is my authenticated NodeJS route returning results with an incorrect JWT token? I have a NodeJS application which I have begun to separate out in to smaller files since the original became a little bloated.
In my index.js I have routes that are protected by a function a freelancer wrote to provide JWT authentication. These routes work as required.
app.use(require('./lib/api-calls/convert.js'));

//  Security Enabled index.js
//
const { app } = require ('./lib/deps/init_dependencies.js');
const { enableSecurity } = require("./security");
const main = async () => {

    // Enable API JWT Security = Comment out the line below to turn off security.
    await enableSecurity(app);

    app.get('/v1/createSession:key/:limit', function (req, apiResponse) {

       // My route, working well

    });
}
main()

I've created /lib/routes/convert.js and am wanting to write new routes in this file which also require JWT authentication. However, I always receive status 200 'OK', regardless of whether the authentication header is correct or not... I'm using Postman to make my calls. Here's my code:
const app = require('express')();

//JWT authentication
const { enableSecurity } = require('../../security');
const main = async () => {

    // Enable API JWT Security = Comment out the line below to turn off security.
    await enableSecurity(app);

    app.get('/v3/convertw3w/:locationValue/:countryCode', function (req, res) {

        res.status(200).send({ status: 'OK' });

    });
}
main()
module.exports = app;

Can anyone spot the problem? I spent far to long on this last night!
thanks

A: Just some food for thought here and we do something similar, but if you use
enableSecurity(app)

As middleware on the route and the
next()

function in the middleware you can omit the need to make this a promise, because middelware is designed to process in order of the middleware and the next function tells express to move to the next middleware.
How we do it, is to have the middleware 'auth', because middleware will pass the req and res objects to each one in the stack you can have all your JWT decode in one place.
We typically will pass the token in the header OR the req object, just depends on the mimetype we pass, so in out auth we check if the token is in the header or the req, if so we decode, if it passes decode we pass
next()

in that code block otherwise we res.json({"response":"not authorized"})


text:
Q: Is it possible to create two RTCPeerConnections connected to eachother in the same window? If so, do I need to do the normal candidate creation and negotiation, or is there an easier way to do this?

A: Found a simple tutorial here: https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample