text:
Q: How to improve login script? How can I ensure my login script is secure and make it better, This is my first code:
Help is most appreciated.
<?php

include ('../includes/db_connect.php');

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$username = $_POST['username'];
$password = md5($_POST['password']);

// lets check to see if the username already exists

$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");

$username_exist = mysql_num_rows($checkuser);

if($username_exist > 0){
    echo "I'm sorry but the username you specified has already been taken.  Please pick another one.";
    unset($username);
    header("Location: /registration?registration=false");
    exit();
}

// lf no errors present with the username
// use a query to insert the data into the database.

$query = "INSERT INTO users (firstname, lastname, email, mobile, username, password)
VALUES('$firstname', '$lastname','$email', '$mobile','$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();

echo "You have successfully Registered";
header("Location: /registration?registration=true");
// mail user their information

//$yoursite = 'www.blahblah.com';
//$webmaster = 'yourname';
//$youremail = 'youremail';
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
//    To login, simply go to our web page and enter in the following details in the login form:
//    Username: $username
//    Password: $password
//
//    Please print this information out and store it for future reference.
//
//    Thanks,
//    $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";

?>

A: Follow Artefacto's advice about SQL injection and Hashing passwords in the database. Other things ...
echo "I'm sorry but the username you specified has already been taken.  Please pick another one.";
unset($username);
header("Location: /registration?registration=false");

Wont work because you can't echo then send a header. Headers must be sent before any output.
Also, there is no point doing this:
header("Location: /registration?registration=false");
echo "I'm sorry but the username you specified has already been taken.  Please pick another one.";
unset($username);

The webbrowser will redirect straight away and the user won't see the handy message you've printed.
Also, it's usual to ask for 2 password fields on registration forms incase the user made a typo and didn't notice because all the text was *'s. You compare the 2 and if they are different you assume a typo was made and ask again.

A: That's not a login script. It's a registration script.
See SQL injection in the PHP manual. Your program is vulnerable to this kind of attacks.
Also, don't just or die(mysql_error()). This will expose information about your database that you may not want to expose (table names, etc.). Use proper error handling. For instance, you can throw an exception and define a uncaught exception handler that shows a "oops" page and logs the error.
Finally, use hashes strong than MD5, such as sha1.

A: As said by @Artefacto, that's not a login script.
But if you intend to do a login script I would like to give you a suggestion. I've done this a while ago.
Instead of doing something like this:
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";

I would do this:
$sql = "SELECT * FROM users WHERE username = '$username'";
$user = //use the php-sql (query, fetch_row) commands to fetch the user row.
if (strcmp($user['password'], $password) == 0) {
    //log in success
}

By doing this, you avoid SQL Injection in a simple and elegant way. What you guys think about it?

A: To reiterate what everyone else mentioned. It's important to protect yourself (and sever) from SQL injection. For example:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");

You're just simple taking the value from $_POST['username'] and placing it in the variable $username.
Some people aren't very nice and will try to break your program :( So it's always recommended to escape any data that was taken from a user, before placing it into an SQL query.
For instance...
This:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");

Becomes:
$checkuser = mysql_query("SELECT username FROM users WHERE username='" .mysql_real_escape_string($username). "'");


text:
Q: Rightscale::HttpConnection : re-raising same error: https://eu-central-1.ec2.amazonaws.com:443 temporarily unavailable I'm using chef_gem "right_aws" version '3.0.5'
https://supermarket.chef.io/cookbooks/aws#changelog
v2.5.0 (2014-10-22)

Got the following error when trying to use aws cookbook in ec2-central-1 region
WARN: Rightscale::HttpConnection : request failure count: 1, exception: #<SocketError: getaddrinfo: Name or service not known>
WARN: Rightscale::HttpConnection : request failure count: 2, exception: #<SocketError: getaddrinfo: Name or service not known>
WARN: Rightscale::HttpConnection : request failure count: 3, exception: #<SocketError: getaddrinfo: Name or service not known>
WARN: Rightscale::HttpConnection : request failure count: 4, exception: #<SocketError: getaddrinfo: Name or service not known>
WARN: Rightscale::HttpConnection : re-raising same error: https://eu-central-1.ec2.amazonaws.com:443 temporarily unavailable: (SocketError: getaddrinfo: Name or service not known) -- error count: 4, error age: 0

From this documentation 'http://docs.aws.amazon.com/general/latest/gr/rande.html',
the endpoint should be 'ec2.eu-central-1.amazonaws.com'
I tried to edit my cookbook under libraries-> ec2.rb, but it doesn't work:
require 'open-uri'
module Opscode
  module Aws
    module Ec2
...

def ec2
    region = instance_availability_zone
    region = region[0, region.length-1]
    aws_ec2_endpoint = "https://ec2." + region + ".amazonaws.com"
    Chef::Log.debug("Using AWS EC2 endpoint: " + aws_ec2_endpoint)
    @@ec2 ||= create_aws_interface(RightAws::Ec2)
end

Any workarounds anyone can offer?
Thanks!

A: If you have the same issue, please find all details here:
https://github.com/rightscale/right_aws/issues/190

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make my program not run on other computers? I have an assignment, and it has (amongst others) two demands:

*

*make an installer

*make it so that if it is installed on one computer, anyone trying to run the same files on another computer will fail.

I'm using VS9 (2008) express, I think I can do the installer part, but I'm not sure how to do the "security" part. I don't need any hard to crack safety, just a dumb condition that will stop most users from copying the files to another computer. (Like checking the MAC address).
Any ideas?
EDIT:
I would like to check the MAC address but I want the program finalized during installation. Meaning that after I install I can't move the program to another machine. It also does not have to be a very smart or difficult condition, just bare minimum. I just don't know how to do it in the installation.
EDIT:
It's sad I don't have the complete VS then I would be able to do it easily.

A: If you're looking for some way to mark the first computer as the "authorized" computer, then you need some external service you can ask for permission to launch.
The first person to ask permission would be allowed, the rest would be prevented.
You'll also need to come up with some way of identifying a particular instance of your application that's different for every install.
If your app needs to be authorized for the machine, then you will need to calculate some fingerprint for the machine it can use each time (eg across installs).
[Edit]
This approach is useful when you're worried about copies of the installer being distributed as well.  You did specify that its ok to install on multiple machines, so in that case MasterMind's approach is superior.  It will work, and does not requires a 3rd party server
[Edit 2]
If you're looking for info on how to build a custom installer, try here

A: First of all, come up with some function to generate a unique PC signature, like Windows does for activation.
Your installer will be creating this signature and writing it to a local file (better encrypted). You can create a simple console executable to generate this file and include that executable into your installer package, setting it up to run silently after the successful installation.
Your program when starting will be creating the signature again using the same algorithm and comparing it to the one created during installation. If the new signature is different from the original one or the signature file is missing, then exit without loading the UI.
ADDED: If you don't need it very complex, you can just choose a few unique values like the MAC address you suggested, maybe the hard drive serial number, mainboard serial number, concatenate them into a single string and generate the hash out of it.
This approach will allow for an unlimited number of copies to run (but each installation will only be workable on one single machine where it was installed). If you stick to the identification by hardware (or OS product key as well), then the application can run on various OS installations on the same machine.
This strategy, however, implies that you control all installations (or perform them yourself) or absolutely trust your client not to install additional copies elsewhere or distribute your installer. If you need that kind of protection as well, then you should consider product activation. It can be quite complicated if you do it yourself. There are however third party products to help you. Some offer product activation services: Google: activation service

A: Once you have a decent fingerprint, the rest is easy.  Personally I'd take something like the MAC address and the windows product ID (at HKLM\Software\Microsoft\Windows\CurrentVersion\ProductId) and use a hashing algorithm to get something reasonably obscure.
edit:
Here's a question that shows you how to get your MAC address as a string:
Read MAC Address from network adapter in .NET
Then grab your windows product ID (in case they don't have a network adapter) from the above registry key.  Concatenate both strings and do a GetHashCode() (or use your favorite hashing algorithm) on the result.  This is a simple way to get a UID for a computer.
Write the hash to a file or to a registry entry when your installer is executing and check it when your program starts up.

A: Consider using two or more values that potentially identify the machine, e.g.

*

*Windows product code

*Volume serial number of the C: drive

*MAC address of an ethernet interface

And if just one of these changes but the others match, update that one value in the registry and continue running normally.  Hard drives get replaced (regularly), Windows gets upgraded (occasionally), Ethernet adapters get replaced (rarely but it does happen.)  It can be very frustrating when old software stops working because of this.

A: Bare minimum answer, assuming the only requirement here is that the software should run if installed through the installer, and won't run if copied to another computer:
Write a simple key to the registry. Most likely your product's version number, incase they copy a newer version to the computer, it has a different number to check for.
In your software, just make sure this registry value exists.
For packaging installations, I enjoy using NSIS which has simple methods for writing to the registry.

A: I like the idea of checking the MAC address.
I have also seen product key/online activation combinations where you enter the product key and the software contacts a web service that logs the product key and # of installs.

A: This isn't the most secure option or anything but you did say it didn't have to be smart...
On install, you could set a program variable to be the machine name (or a hash of it if you like).
Like:
myProgram.Properties.Settings.Default.Machine = System.Environment.MachineName;
myProgram.Properties.Settings.Default.Save();

then check that on startup:
if (System.Environment.MachineName != myProgram.Properties.Settings.Default.Machine)
{
    MessageBox.Show("Can't run on this computer");
    this.Close();
}

A: -1 for clinging to an antiquated license-restriction policy that is a poor practice in general. Hardware dongles and "device detection" are SO 1990.
People own more than one computer. They buy new computers. They upgrade their computers. Computers break, resulting in replacement of motherboards or network cards.
All of these, given your design, will result in honest, paying customers being locked out of what they've paid for and will have to call you for support to "reset" their activation.
And each time you do so, your overhead will increase by, very likely, more than the actual cost of a license.
I'm not suggesting you give up and just send your app off to the torrentverse, but you should think more creatively about how to allow customers the freedom to use what they paid for, keep your support costs low, and discourage pirates.
One creative solution would be to cache the user's settings on your server, keyed by their serial number, and synchronize them every time the application starts and is connected to the Net.
This will allow a user to install the app on, say, both a laptop and desktop, and will actually be a value-add for customers because their settings are synchronized between devices.
But it actively discourages users from sharing their license key, since doing so would mean they would be sharing their settings with every pirate user, or that they would have to remember to stay disconnected from the Interwebs when they open or close the app.

A: To get the installer to only work for one machine, you'd pretty much have to build it for the target machine.  I dont think it would be possible to make an installer that assumes the first machine it sees is it's mommy and is attached for life.


text:
Q: Misunderstanding of Replace code I am looking for the right way  to replace $\delta \, \, \text{by} \, \, 0.05 \, \, \, \beta \, \, \, \text{by} \,  \, \, 1.77 \, \, \, \text{and} \, \, \, n \, \, \,  \text{by} \, \, \, 12$ in this expression
(2 δ E^(-δ τ))/(2 E^(-δ τ) - 1)
b[τ_] := (2 δ β E^(-δ τ) - δ ((2 \
E^(-δ τ) -
          1) β - δ) n)/((2 E^(-δ τ) -
      1) β)
f[τ_] :=
 ArcCos[a[τ]/b[τ]]/Sqrt[b[τ]^2 - a[τ]^2]
z[τ_] := τ - f[τ]

I tried something like this
 Replace[τ -
      ArcCos[a[τ]/b[τ]]/
       Sqrt[b[τ]^2 - a[τ]^2], {δ -> 0.05, β ->
       1.77, n -> 12}]

in the final outcome, I had
τ - ArcCos[(2 E^(-δ τ) β δ)/(2 E^(-\
δ τ) β δ -
      n ((-1 + 2 E^(-δ τ)) β - δ) δ)]/
  Sqrt[-((4 E^(-2 δ τ) δ^2)/(-1 +
          2 E^(-δ τ))^2) + (2 E^(-δ τ) \
β δ -
        n ((-1 +
              2 E^(-δ τ)) β - δ) \
δ)^2/((-1 + 2 E^(-δ τ))^2 β^2)]

which seems extremely uncomfortable.
Any help would be much appreciated!

A: Try rather using the following syntax for your replacement:
( <expr> ) /. { x -> 3.14 }

In your case, probably something like:
FullSimplify[  (\[Tau] - ArcCos[a[\[Tau]]/b[\[Tau]]]/
  Sqrt[b[\[Tau]]^2 - a[\[Tau]]^2])
  /. {\[Delta] -> 0.05, \[Beta] -> 1.77, n -> 12} ]

See the explanation on Applying Transformation Rules:

On the other hand, Replace[expr,rules] tries the rules only on the whole of expr, and not on any of its subparts.


text:
Q: wp7 c# get control data context I have a listbox whose item template is a user control:
<ListBox
     x:Name="ChatBox"
     Width="450"
     ItemsSource="{Binding ChatMessage}">
          <ListBox.ItemTemplate>
              <DataTemplate>
                    <local:ChatItem DataContext="{Binding ChatMessage}"/>
              </DataTemplate>
          </ListBox.ItemTemplate>
</ListBox>

in my code behind:
messages = new ObservableCollection<ChatMessage>(dbMessages);
ChatBox.ItemsSource = messages;

How can I get the bound element, that is, the chat message object from inside the control ?
Thanks for help

A: your ChatItem usercontrol is automatically got the its Datacontext to ChatMessage Object. it is not required to set it again. and for binding properties of your usercontrol to ChatMessage object properties then your ChatItem properties must be Dependency Properties if you already have them then just bind them to ChatMessage Properties like this.
<ListBox
 x:Name="ChatBox"
 Width="450"
 ItemsSource="{Binding ChatMessage}">
      <ListBox.ItemTemplate>
          <DataTemplate>
                <local:ChatItem DataContext="{Binding ChatMessage}" ChatItemDependencyProperty = "{Binding Path=ChatMessageProperty}" />
          </DataTemplate>
      </ListBox.ItemTemplate>

hope it helps you..


text:
Q: The mongo can't show its correct size of database in terminal I use pymongo to save the data that I've crawled by scrapy,and when I use show dbs command to check the database in terminal.It looks like this
  > show dbs
EPGD___test                 0.000GB
EPGD_closetest              0.000GB
Testinsert                  0.000GB
local                       0.000GB
sta                         0.000GB
stackoverflow               0.000GB
stackoverflow_test          0.000GB
stackoverflow_test_morning  0.000GB
temptest1                   0.000GB

As you can see ,the size of database EPGD_closetest is 0.000GB,and in the GUI mongoHub,there are also no collections can be found in the database.
[enter image description here][2]: http://i.stack.imgur.com/nDZI1.png.But when I use the following command use EPGD_closetest and db.EPGD_test.find() and I can see there are datas in the database.And I can also get it using pymongo.
The code when I save datas to mongo by pymongo:
    def process_item(self, item, spider):
    valid = True
    for data in item:
        if not data:
            valid = False
            raise DropItem("Missing {0}!".format(data))
    if valid:
        self.collection.insert(dict(item))
        log.msg("Item wrote to MongoDB database {}, collection {}, at host {}, port {}".format(
        settings['MONGODB_DB'],
        settings['MONGODB_COLLECTION'],
        settings['MONGODB_SERVER'],
        settings['MONGODB_PORT']))
    return item

The code when I read datas from mongo by pymongo:
from pymongo import MongoClient

client = MongoClient()

db = client.EPGD_closetest
collection = db.EPGD_test

print collection.find().count()
print collection.find_one({"taxID" : [ "9606" ]})

The result as below:
299
{u'familyID_url': u'http://epgd.biosino.org/EPGD/paralogfamily/getInfor.jsp?familyID=50144', u'description': [u'lectin, mannose-binding, 1'], u'symbol': [u'LMAN1'], u'taxID': [u'9606'], u'taxID_url': [u'http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=9606'], u'familyID': [u'50144'], u'genID': [u'3998'], u'genID_url': u'http://epgd.biosino.org/EPGD/gene/geneinfor.jsp?geneID=3998', u'_id': ObjectId('56fb6c11c75c1608bde3293c'), u'chromosome': [u'18']}

So can anyone tell me what's wrong with my mongo?

A: It is perfectly normal... Because data is very small in your collection so it is showing almost 0.000GB of data. You can put more data to see the changes...
You can also use db.stats() to check data stats of db. Here is the result of db.stats()
{
    "db" : "nxb",
    "collections" : 2,
    "objects" : 5,
    "avgObjSize" : 133.8,
    "dataSize" : 669,
    "storageSize" : 40960,
    "numExtents" : 0,
    "indexes" : 2,
    "indexSize" : 40960,
    "ok" : 1
}


text:
Q: How does one suppress the output of a command? I would like to run some commands in my shell script however would like to know some method to it returns nothing.
example:
#! / bin / bash]
rm / home / user

return: rm: can not lstat `/ home / user ': No such file or directory

I would have put the command to run invisibly no return!

A: To suppress the standard output of a command, the conventional way is to send the output to the null device, with somecommand arg1 arg2 > /dev/null.  To also suppress error output, standard error can be redirected to the same place:  somecommand arg1 arg1 > /dev/null 2>&1.

A: Your direct error is coming from incorrect spacing in the path, should be rm /home/whatever without spaces in the path, assuming you don't have actual spaces in the dir names (in which case you will need to quote or escape properly)
About suppressing output. Redirecting stdout here is a bit strange.
$ touch test.txt
$ rm test.txt > /dev/null 2>&1

^ interactive rm is actually asking if you really want to delete the file here, but not printing the message

If you just want to not get error messages, just redirect stderr (file descriptor 2) to /dev/null
$ rm test.txt 2> /dev/null

or
$ rm test.txt 2>&-

If you want it to not prompt do you really want to delete type messages, use the force flag -f
$ rm -f test.txt 2> /dev/null

or
$ rm -f test.txt 2>&-

To delete a directory you either want rmdir if it's empty or use the recursive -r flag, however, this will wipe away everything /home/user so you really need to be careful here.
Unless you have it running in --verbose mode, I can't think of any case where it needs to close stdout for the rm command.
Also as of bash 4, if you want to redirect both stdout and stderr to the same location just use rm whatever &> /dev/null or something similar


text:
Q: Is Reactive Extensions 2.1 PCL compatible with Xamarin? Riddle me this:
Can the new PCL version of Reactive Extensions be made to work with Xamarin?
If so, how?

A: Nope. But check out https://github.com/mono/rx/tree/rx-oss-v2.1/Rx/NET/Source/Rx_Xamarin for versions that do work.

A: Yes it is possible. At the moment, you will need to switch to the beta channel of the Xamarin tools which implement Mono 3.0. This can be done via Tools > Options > Xamarin in Visual Studio 2012.
Xamarin.Android 4.7 Information
Xamarin.iOS 6.3 Information
The ReactiveUI project should have all of the libraries that you need. Here is a link to the libraries folder on their nuget site.


text:
Q: Can't enable shell-escape I've been trying to add the --shell-escape argument to my pdflatex, and right about nothing works. I'll summarize what I've done so far:

*

*Add --shell-escape to existing pdflatex.exe

*Add --shell-escape to \texlive\2013\bin\win32\pdflatex.exe

*The console either gets stuck at "ABD: EveryShipout initializing macrosgnuplot not recognized", or

*"Package gnuplottex Warning: Shell escape not enabled. (gnuplottex)                You'll need to convert the graphs yourself..", or

*TeXworks produces no PDF

*I have also tried running different compilers such as miktex-pdftex.exe, pdftex.exe, etc.

*I'm running the latest MikTeX / TeX distributions, packages, etc. (just updated everything in my TeX Live Manager)

This only seems to be a big deal when I run anything GNUplot related.
What's going on here?

A: To long for a comment. Run this document with --shell-escape:
\documentclass{article}
\begin{document}
\immediate\write18{echo "hallo"}
blub
\end{document}

Then check the log file. If you found thererunsystem(echo "hallo")...disabled (restricted)
then --shell-escape has not been activated. If the message is runsystem(echo "hallo")...executed. then everything works and your problem lies somewhere else.


text:
Q: Deserializing types from binary file into different namespace in different app (C# .NET) In application called "application1" I serialize this structure into binary:
namespace namespace1
{
[System.Serializeable]
class ClassA
   {
     List<ClassB> List
   }
}

In application called "application2" I have to deserialize this binary but my ClassA and ClassB have to be inside namespace2 instead of namespace1.
So I wrote a serialization binder:
public class TypeNameConverter : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            assemblyName = Assembly.GetExecutingAssembly().FullName;

            if (typeName.Contains("nemespace1."))
                typeName = typeName.Replace("nemespace1.", "nemespace2.");

            Type retType = Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
            return retType;
        }
    }

and I use it like this:
 binaryFormatter.Binder = new TypeNameConverter();
 (T)binaryFormatter.Deserialize(memoryStream);

And this sucessfully deserializes namespace1.ClassA into namespace2.ClassA, but
fails to further deserialize list od nemespace1.ClassB into list of namespace2.ClassB. I guess it fails because list of ClassB is encapsulated into ClassA and BindToType() function does not get called for the "inner elements", it gets called only once for ClassA, then trys to deserialize ClassA and fails to extract list of ClassB with error:
 SerializationException: Could not find type
    'System.Collections.Generic.List`1[[namespace1.ClassB, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]'.

I cannot do any adjustments to application1 (cannot change the way I do serialization) I can only adjust deserialization logic in application2.
I am trying to find the solution for this particular problem, anyone had similar problem or maybe an idea on how to solve this?
Thanks!

A: The only solution to the problem in question I found is manually changing the type inside  already serialized binary file. That includes reading binary file which contains serialized objects of type namespace1.ClassA, finding the bytes in binary file which represent the string which defines the type (that is "namespace1.ClassA") and replacing those bytes with string "namespace2.ClassA", thus making deserializer think that serialized object is of type namespace2.ClassA instead of namespace1.ClassA, and this works!
The link to s.o. question containing golden information, everything you need to know to do this, and an example code.
How to analyse contents of binary serialization stream?


text:
Q: Using ::find but with a custom where clause I use ::find to find the business but business_position I need to use WHERE business_id = and WHERE id to find the correct position, and example is avalible below...
<?php
    $s = Stats::find(Auth::user()->id);
    $myJob = \App\Businesses::find($s->business_id);

    $matchedValues = ['business_id' => $s->business_id, 'id' => $s->business_position];
    $myPosition = \App\BusinessPositions::where($matchedValues)->get();
    ?>

And using $myPosition I use
{{ $myPosition->pay_amount }}

And on that line it throws and error...

Undefined property:
  Illuminate\Database\Eloquent\Collection::$pay_amount (View:
  C:\Users\Darren\MyLavProject\resources\views\pages\business\business.blade.php)

A: Laravel's get() returns a collection of results that match your query (even if there are none or just one, it'll be an array of Laravel model instances).
You can use first() instead of get() to grab the first result, or you can foreach through each of the results get() provides. It depends if your application permits more than one permission per business_id/id combination.

A: $myPosition This is an array of objects.
So if you need the result:
{{ $myPosition[0]->pay_amount }}

Or
@foreach($myPosition as $position)
  {{ $position->pay_amout }}
@endforeach

Of if you don't want to use any of these:
Change your query to :
$myPosition = \App\BusinessPositions::where($matchedValues)->first();

Now you can use: {{ $myPosition->pay_amount }}


text:
Q: SQL Server 2008 - different sort orders on VARCHAR vs NVARCHAR values In SQL Server 2008, I am seeing some strange behavior when ordering NVARCHAR columns; here are a few quick use cases to demonstrate:
Case 1: ORDER on VARCHAR values:
SELECT t.Name
FROM
(
SELECT CAST('A' AS VARCHAR(500))  As Name
UNION SELECT CAST('-A' AS VARCHAR(500))  AS NAME
) As t
ORDER BY t.Name ASC

Which produces (my desired) output of:
-A
A
(The one with the leading dash is displayed first)
Contrast this with the ORDER on NVARCHAR values:
SELECT t.Name
FROM
(
SELECT CAST('A' AS NVARCHAR(500))  As Name
UNION SELECT CAST('-A' AS NVARCHAR(500))  AS NAME
) As t
ORDER BY t.Name ASC

Which produces this output:
A
-A
Assuming I want to sort on NVARCHAR fields (I can't change the db design) using a standard ORDER BY clause (I'm using linq2nhib, which prevents me from doing any casting here) - how do I get the sorting to work in the desired fashion (item with the leading non-alphanumeric value displays first)?
I'm hoping there is some sort of database/server-level collation setting for this...any ideas?

A: Either change the collation in the database or change the collation of individual columns in the tables you need consistent ordering on.
The collations Latin1_General_BIN or Latin1_General_BIN2 work fine with your example.

A: You need to use binary collation to achieve consistent ordering.
ORDER BY t.Name ASC COLLATE Latin1_General_BIN

Edit:
Since you can't do the collate in the query,
you will need to do it at the database level.
You will need to set it on the column(s) that you are comparing and it needs to be binary.
Here's an example of that.

A: You can also order the set with CAST(VARCHAR) on a CTE that returns the primary key and do a join on the table to get the NVARCHAR value.


text:
Q: Find Duplicate value with multiple fields then sum the specific field sql query I have the same problem with this i want to get those duplicate values and i successfully done it using this code
SELECT projNum, ProjCode, LaborCode, Code, Description, Price, QtyMaterials, AIPrice
FROM Cost_MasterMaterials
WHERE Code IN (
    SELECT Code
    FROM Cost_MasterMaterials
    GROUP BY Code
    HAVING COUNT(*) > 1
)

but my problem is after i get the details of the duplicate values and all its field i want to sum the QTYMaterials then retain only one item of every duplicate values.
Sample Table
id | projnum | projcode | code | description | Price | QtyMaterials | AIPrice,
1      23        Null     1207    Dog           Null       1          Null
2      23        Null     1207    Dog           Null       2          Null
3       2        Null     1321    Pig           Null       5          Null
4      12        Null     1621    Cat           Null       6           Null
5       2        Null     1321    Pig           Null       1          Null

Result must be like this
id | projnum | projcode | code | description | Price | QtyMaterials | AIPrice,
1      23        Null     1207    Dog           Null       3          Null
3       2        Null     1321    Pig           Null       6          Null
4      12        Null     1621    Cat           Null       6          Null

I Hope someone can help me of this.

A: You can use SUM with GROUP BY
Try this
SELECT
    projNum, ProjCode, LaborCode, Code, Description,
    Price, SUM(QtyMaterials) QtyMaterials, AIPrice
FROM Cost_MasterMaterials
GROUP BY projNum, ProjCode, LaborCode, Code, Description, Price, AIPrice

A: What you are trying to do is basically you need aggregated value of the Materials or any aggregation field of you choice.
In your case you want to see what are the duplicate records by at code level basically. So you can do  this by looking at your data, one is include all the fields in group by clause - given that all the other values associated are same, you end up having only 1 record ( which will also delete the duplicate at your level) or you can do the MIN/MAX operation on the string fields as well to uniquely get the records at the CODE level (Provided you have only 1-1 mapping of Code to rest of the attributes).

*

*Option 1 is already highlighted by Nayanish Damania. Use the script

*Option 2

SELECT MIN(ID) as ID, MIN(PROJNUM) as PROJNUM, ProjCode ,MIN(description) as description , mIN(Price) as PRICE , MIN(Price) as PRICE, SUM(QtyMaterials) as QtyMaterials
FROM Cost_MasterMaterials
GROUP BY ProjCode
ORDER BY MIN(ID) ASC;


text:
Q: How do I get the Outlook calendar that an appointment is being made to I have created a personal calendar named Time Tracking in Outlook as well as my normal exchange calendar.  I have created a Form Region for a simple Outlook AddIn.  I want the form region to show only if the appointment is going/derived from the Time Tracking calendar.  Below is a screenshot of both calendars.

I want to show the form Region only when it comes from my Time Tracking calendar.
I tried this code:
public partial class TimeTrackingRegionFactory
{
    // Occurs before the form region is initialized.
    // To prevent the form region from appearing, set e.Cancel to true.
    // Use e.OutlookItem to get a reference to the current Outlook item.
    private void TimeTrackingRegionFactory_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
    {
        var appt = e.OutlookItem as AppointmentItem;
        if (appt != null)
            e.Cancel =
                !(appt.Parent as Microsoft.Office.Interop.Outlook.MAPIFolder).Name.Equals(
                    Constants.TIME_TRACKING_CALENDAR);
    }
}

However, I found that the calendar name for both is 'Calendar'.  I saw this question but I checked and both StoreID and Store properties seem the same.
If I save the appointment and then reopen it, it will say the appointment is from the Time Tracking calendar and then display the form region correctly from the code above.
It is like all appointments seem to be defaulted to the Calendar rather than Time Tracking calendar even though I'm trying to create one from there until it is saved.
Is there a way to find out what calendar the appointment item is being saved to?
Thanks, Bill N

A: Look at the appt.Parent property - it will return the parent MAPIFolder object.

A: Dmitry Suggestion Works:
var outlook = new Microsoft.Office.Interop.Outlook.Application();

e.Cancel = !(outlook.Application.ActiveExplorer().CurrentFolder).Name.Equals(
            Constants.TIME_TRACKING_CALENDAR);


text:
Q: Setting the Classpath through Linux Script I need to set 100 jar files through Linux script, so i written this way
The echo result is this way
test/lib/xstream-1.3.1.jar:test/lib/test/lib/xpp3_min-1.1.4c.jar:test/lib/test/lib/xmlsec-1.4.1.jar:test/libtest/lib/xml-apis.jar

My question is in windows the jar files will be termnated by semicolon , in linux it is showing a colon (:) is this correct ??

A: Your assumption about the path separators is correct.

A: CLASSPATH is like PATH in that its entries are separated by a semi-colon on Windows and a colon on other platforms.


text:
Q: How can I remove session for specific user for specific ServiceProvider in WSO2 IS? There is any webservice providing by WSO2 Identity server, to remove a session for specific user to specific ServiceProvider?
I am using SAMLSSO for many web application and they all are integrating with WSO2 server.
Now let's say scenario is,User is login with 2 application at the same time. I want to logout it from one application.
There is one service provided by logout and it's providing single logout and session will be remove for all application. There is webservice provided by IS or way to achieve logout for one specific application ?

A: What you are asking is to have the capability of removing a specific participant from the session created in the Identity Server side. I don't see a straight forward way (OOTB) of achieving this.
Closest you can achieve is as below.

*

*Make your application perform a forceAuth. ForceAuth will request for user credentials despite having the cookies in the browser. (This will prevent the user from experiencing the SSO comfort. Still you can authenticate against the IS)

*Prevent the application from sending an SLO request to WSO2. Rather, terminate the self(application) session upon logout.

*When your application really wants to perform an SLO (logout all the applications, not just yours), your application can send an SLO request to the Identity Server.

Performing a force authentication :

*

*SAML - Send forceAuth=true as a query paramter in your login request. Or else change the SAML AuthenricationRequest payload body to indicate a force authentication as in the spec(Line 2042).

*OIDC - Send prompt=login as an additional query parameter in the /authorization request.

A: You can do this by calling the REST API and SOAP API provided by WSO2 IS. This will remove the session at WSO2 IS but I'm not sure if it will also trigger the SLO to other service providers or not.
Reference:

*

*https://is.docs.wso2.com/en/latest/develop/calling-admin-services/

*https://is.docs.wso2.com/en/latest/develop/session-mgt-rest-api/

*

*Trigger a SOAP request getUserProfile from the UserProfileMgtService.wsdl. The default user profile will be 'default' or you can put the customized profile name you used. This will return the details. Grab the user id from this.

*Trigger a GET to the API: /{user-id}/sessions with the user-id from step 1 to get the list of all active sessions this user currently have. Go through the list of sessions and find the session ID of the Service Provider you need to clear.

*Trigger a DELETE request to API: /{user-id}/sessions/{session-id} with the user id from step 1 & session id from step 2


text:
Q: extracting downsampled timeseries from a normalised csv using pandas I have a dataframe from a CSV that looks like this (sample data here: http://www.speedyshare.com/9A2zf/download/sample.csv):
                          event    name          user  count  amount  commission
2011-05-23 00:00:00  2011-07-22  normal  reading_arts      2      26         0.0
2011-05-23 00:00:00  2011-07-23  normal  reading_arts     14     182         0.0
2011-05-24 00:00:00  2011-07-22  normal  reading_arts      4      52         0.0
2011-05-24 00:00:00  2011-07-22  normal  reading_arts      3      39         0.0
2011-05-26 00:00:00  2011-07-23  normal  reading_arts      2      30         0.0
2011-05-26 00:00:00  2011-07-23  normal  reading_arts      5      75         0.0
2011-05-26 00:00:00  2011-07-22  normal  reading_arts      1      13         0.0
2011-05-27 15:39:28  2011-07-23  normal       hickies     16     208       -10.4
2011-06-01 00:00:00  2011-07-23  normal  reading_arts      2      30         0.0
2011-06-02 00:00:00  2011-07-23  normal  reading_arts     17     221         0.0

..that I created with:
data = read_csv('2011.csv',
                names=('event', 'user', 'count', 'amount', 'commission'),
                parse_dates=True)

'event', while it looks like a date, is actually just an identifier for a particular event.
You'll note there are duplicate entries in the DateTimeIndex, eg: 2011-05-23 00:00:00.
What I eventually want is a set of 3 timeseries (for each of count, amount and commission) for each user for each event, downsampled to weekly buckets by summing up. I'd also like to create similar timeseries for each event, which would simply be a sum of the per-user-per-event time series.
How would I do that?

A: edit - try this code:
Note - I took the csv and added a header to each row.  The row 1 column headers I added are:
time    event   name    user    count   amount  commission

Try running this and let me know if it's still not what you're looking for.
import pandas as pd
import numpy as np

df= pd.DataFrame.from_csv('sample.csv')

resamp = df.groupby(['event','user']).resample('W', how='sum')


text:
Q: nattable combobox filter header with group by I am trying to implement nattable with "ComboBoxFilterRowHeaderComposite".
Filtering is working fine but after filtering rows when I try to do group by, it throws following exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.remove(ArrayList.java:492)
    at ca.odell.glazedlists.FunctionList.listChanged(FunctionList.java:283)
    at ca.odell.glazedlists.event.ListEventAssembler$ListEventFormat.fire(ListEventAssembler.java:424)
    at ca.odell.glazedlists.event.ListEventAssembler$ListEventFormat.fire(ListEventAssembler.java:421)
    at ca.odell.glazedlists.event.SequenceDependenciesEventPublisher$SubjectAndListener.firePendingEvent(SequenceDependenciesEventPublisher.java:445)
    at ca.odell.glazedlists.event.SequenceDependenciesEventPublisher.fireEvent(SequenceDependenciesEventPublisher.java:344)
    at ca.odell.glazedlists.event.ListEventAssembler.commitEvent(ListEventAssembler.java:317)
    at ca.odell.glazedlists.TransformedList.clear(TransformedList.java:98)
    at org.eclipse.nebula.widgets.nattable.extension.glazedlists.groupBy.GroupByDataLayer$1.run(GroupByDataLayer.java:286)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.nebula.widgets.nattable.extension.glazedlists.groupBy.GroupByDataLayer.updateTree(GroupByDataLayer.java:272)
    at org.eclipse.nebula.widgets.nattable.extension.glazedlists.groupBy.GroupByDataLayer.update(GroupByDataLayer.java:313)
    at java.util.Observable.notifyObservers(Observable.java:159)
    at java.util.Observable.notifyObservers(Observable.java:115)
    at org.eclipse.nebula.widgets.nattable.extension.glazedlists.groupBy.GroupByModel.update(GroupByModel.java:124)
    at org.eclipse.nebula.widgets.nattable.extension.glazedlists.groupBy.GroupByModel.addGroupByColumnIndex(GroupByModel.java:44)

Here is my structure for ComboBoxFilterRowHeaderComposite:
filterRowHeaderLayer = new ComboBoxFilterRowHeaderComposite<T>(
            bodyLayerStack.getFilterList(),
bodyLayerStack.getGlazedListsEventLayer(), bodyLayerStack.getSortedList(),
                columnAccessor, columnHeaderLayer, dataProvider, configRegistry);
where,
columnAccessor = new ReflectiveColumnPropertyAccessor(propertyNames);
columnGroupHeaderLayer = new DynamicColumnGroupHeaderLayer(sortHeaderLayerStack, bodyLayerStack.getSelectionLayer(),
                bodyLayerStack.getColumnGroupModel(), tr);
DataProvider is com.vanguard.tip.epm.platform.ui.grid.next.DynamicColumnHeaderDataProvider;
After that
CornerLayerStack cornerLayerStack = new CornerLayerStack(rowHeaderLayerStack, filterRowHeaderLayer);
CompositeLayer gridLayer = new GridLayer(bodyLayerStack, filterRowHeaderLayer, rowHeaderLayerStack, cornerLayerStack);
Then Add gridLayer in GroupByHeaderLayer:
groupByHeaderLayer = new GroupByHeaderLayer(bodyLayerStack.getGroupByModel(), gridLayer, columnHeaderLayerStack.getDataProvider(),
new GroupByHeaderConfigurationWrapper(bodyLayerStack.getGroupByModel(), columnHeaderLayerStack.getDataProvider(), bodyLayerStack.getColumnGroupModel()));
CompositeLayer groupByComposite = new CompositeLayer(1, 2);
groupByComposite.setChildLayer(GroupByHeaderLayer.GROUP_BY_REGION, groupByHeaderLayer, 0, 0);
groupByComposite.setChildLayer("Grid", gridLayer, 0, 1);
I hope this will give you some clarity about my use of Nattable.
When I use text base filter with same structure Grouping is working fine:
filterStrategy = new DefaultGlazedListsFilterStrategy<T>(bodyLayerStack.getFilterList(), columnAccessor, configRegistry);
this.filterRowHeaderLayer = new FilterRowHeaderComposite<T>(filterStrategy, columnHeaderLayer, dataProvider, configRegistry);
Let me know if you need more information.

A: Seems to be a bug for that combination. I created the following ticket for this:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=508334


text:
Q: Django form - custom user I created a custom user in django as it follows:
class Customer(AbstractBaseUser):
...

in my forms.py I imported the class:
from account.models import Customer

class PostForm(forms.ModelForm):

            ...

            client_code = forms.ModelChoiceField(queryset=Customer.objects.all(), required=True,
                    widget=forms.Select(
            attrs={ 'class':'form-select form-select-sm',
                    'aria-label':'Default select example',
            }))

            ...

I run the server and this error is shown:
AttributeError: type object 'Customer' has no attribute 'objects'

The project structure is:
account
 -- models.py
 -- forms.py
...

post
 -- models.py
 -- forms.py
...

The Error:
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 423, in check
    databases=databases,
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/registry.py", line 76, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 412, in check
    for pattern in self.url_patterns:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 598, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/.../dev/.../src/post/urls.py", line 42, in <module>
    path('post/', include('post.urls')),
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/.../dev/project/src/post/urls.py", line 6, in <module>
    from .views import (
  File "/.../dev/project/src/post/views.py", line 3, in <module>
    from .forms import PostForm
  File "/.../dev/project/src/post/forms.py", line 13, in <module>
    class PostForm(forms.ModelForm):
  File "/.../dev/project/src/post/forms.py", line 80, in PostForm
    cliente_code = forms.ModelChoiceField(queryset=Customer.objects.all(), required=True,
AttributeError: type object 'Customer' has no attribute 'objects'


text:
Q: Javascript: Delete/Edit Object within Object I have users defined as such;
const initUsers = {
  'a@test.com':{
    firstName: 'A',
    lastName: 'Test',
    email: 'a@test.com',
    password: 'test',
  },
  'b@test.com':{
    firstName: 'B',
    lastName: 'Test',
    email: 'b@test.com',
    password: 'test',
  }
};

I am able to retrieve a user by doing initUser['a@test.com']. How do I delete the users based on their key which is the email like a@test.com? Or how do I replace it with another key, for example, c@test.com in place of a@test.com?
Thank you.
(JavaScript Beginner)

A: Use Javascript delete keyword to delete objects' properties
delete initUsers['a@test.com']
Should delete it for you
You can't change a property's name of an object. Best bet is to add the new property to the object and delete the one you want to replace


text:
Q: Express.js method is called twice Here is my code:
app.get('/api/questions/:group/:limit', function(req, res) {
  var group = req.params.group;
  var limit = req.params.limit;
  console.log('123');

    return QuestionModel.find({group: group})
                        .sort({ creation_timestamp: -1 })
                        .limit(limit)
                        .exec(function(err, questions) {
                            if(!err) {
                                return res.send( { status: 'OK', result: questions });
                            } else {
                                res.statusCode = 500;
                                log.error('Internal error(%d): %s', res.statusCode, err.message);
                                return res.send({ error: 'Server error' });
                            }
                        });
});

When I open localhost:5000/api/questions/js/5 in the browser I can see that the method was called twice:
123
123

If I rewrite this method like this the method is called only once time:
app.get('/api/questions/:group/:limit', function(req, res) {
  var group = req.params.group;
  var limit = req.params.limit;
  console.log('123');
  return;
});

Why in the first case the method is called twice and how can I avoid this ?
Updated: it works twice in Chrome, but only once in Safari and Firefox.  No messages in browser console.

A: I have found the reason - Web Technology Notifier Extension for Google Chrome.


text:
Q: Outlook folder structure Template Having a lot of different customers and a lot of different areas to work with makes it trivial to have your mail folders in order. Everytime I get a new Project / Customer I want to add a certain Folder Structure in my "Customer" / "Project" sub directory.
It might look like this:
Customer_name/
    Bugs
    Documents
    Important
    Support/
        Done

And as it is today, I have to manually add these manually, which is harsh when you have a lot of it going on and each sub directory under the customer_name directory needs to have "display all items" since it's important to me to see all Items in Bugs / Support / Important.
Makes my life easier.
So, Is it possible to Automize the process somehow? Macro? Folder Templates?
What are my options?
Edit
I have something like this set up at the moment:
Set objOutlook = CreateObject("Outlook.Application")

Set objNameSpace = objOutlook.GetNameSpace("MAPI")
Set objFolder = objNameSpace.PickFolder
If objFolder Is Nothing Then
    WScript.Quit
End If
Set objFolders = objFolder.Folders
customer = InputBox("Enter Customer Name:")
Set objCustomerFolders = objFolders.Add(customer).Folders
objCustomerFolders.Add("Bugs")
objCustomerFolders.Add("Documents")
objCustomerFolders.Add("Important")
Set objSupportFolders = objCustomerFolders.Add("Support").Folders
objSupportFolders.Add("Done")

But this doesn't set the Properties on each folder.
So a follow up question would be, do I have to solve this with programming?

A: Just create an empty version of the folder structure you want.
Then when you get a new project, right click drag this "template" to where you want it, and choose "copy" when you let go.
This will create an empty copy of the folder and all it's subfolders.
If this copy is in the same folder as the original empty one, the top level will get renamed with an appended number, but this probably won't matter since you will be renaming it to your customer / project anyway.
I know it's not a "click a button" solution, but it's a simple drag and drop each time and job done.

A: Set objOutlook = CreateObject("Outlook.Application")

Set objNameSpace = objOutlook.GetNameSpace("MAPI")
Set objFolder = objNameSpace.PickFolder
If objFolder Is Nothing Then
    WScript.Quit
End If
Set objFolders = objFolder.Folders
customer = InputBox("Enter Customer Name:")
Set objCustomerFolders = objFolders.Add(customer).Folders
objCustomerFolders.Add("Bugs")
objCustomerFolders.Add("Documents")
objCustomerFolders.Add("Important")
Set objSupportFolders = objCustomerFolders.Add("Support").Folders
objSupportFolders.Add("Done")

This will suffice.


text:
Q: How to save state when preempted on a Google preemptible instance? I need to be able to save the state of a Centos-based Google Compute instance when it first receives a preemption signal.  The documentation very clearly indicates that a "ACPI G2 Soft Off" signal is sent 30 seconds before a preemptible shutdown.  Unfortunately, Google has given no examples to demonstrate how to capture this signal and I have not yet found a way to capture it.
My initial attempts have all been focused around the ACPI Interface using the acpid daemon.  Using it, I have been able to capture the shutdown (button/power) event without any problems.  But no matter what event I try to capture (button, power, sleep) I have not been able to capture the state transition to the G2 state, which I presume is what I am looking for.
Has anyone successfully managed to capture the preemption signal in a Centos (or any Linux) environment?

A: You may want to use shutdown scripts for this:

Create and run shutdown scripts that allow you to execute commands right before an instance is terminated or restarted, on a best-effort basis. This is useful if you rely on automated scripts to start up and shut down instances, allowing your instances time to clean up or perform tasks, such as exporting logs, or syncing with other systems.
If you have a managed instance group that is being autoscaled, shutdown scripts can be useful because if an instance is shut down due to autoscaling, the shutdown script performs any actions you define before the instance is terminated. For example, your shutdown script might copy processed data or back up any logs.
Shutdown scripts function very similarly to startup scripts; much of the documentation for startup scripts also applies for shutdown scripts.

However, since you have limited time to do the work, consider using persistent external storage systems which won't be deleted when your instance is preempted, e.g., Google Cloud Storage, Google Cloud Bigtable, Google Cloud Datastore, or others.


text:
Q: Overwriting JControllerForm save() Method to Trim POST Data Has No Effect I have a component that has a controller called MyproductControllerGeneralsetting which extends JControllerForm. Inside MyproductControllerGeneralsetting I am overwriting the save method from the parent class in order to modify $_POST data and then the overwriting method calls the parent class' save method to do the actual saving.
Here's the overwritten method in MyproductControllerGeneralsetting:
/**
 * We overwrite the saved form data and trim them to avoid spaces
 */
public function save($key = null, $urlVar = null){
    if($_POST['jform']){
        foreach($_POST['jform'] as $key=>&$value){
            $value = trim($value);
        }
    }

    // Finally, save the processed form data (calls JControllerForm-save())
    parent::save('id', $urlVar);
}

The thing is that even though I've trimmed each POST data field in this overwriting method, if I have some values submitted such as 'value ' (note the space in the end), they are not trimmed.
I've checked the save method of the JControllerForm class and it seems to be getting the data from POST here:
$data  = $this->input->post->get('jform', array(), 'array');

Maybe that's the reason? Is this getting cached data or something?

A: Instead of trying to get the values from $_POST directly, try getting and setting the data in the same way the parent class does - using an internal pointer to a (shared) instance of the JInput class.
Here's a modified, working, overwritten save method:
/**
 * We overwrite the saved form data and trim them to avoid spaces
 */
public function save($key = null, $urlVar = null){
    if($_POST['jform']){

        // Get the original POST data
        $original = JRequest::getVar('jform', array(), 'post', 'array');

        // Trim each of the fields
        foreach($original as $key=>$value){
            $original[$key] = trim($value);
        }

        // Save it back to the $_POST global variable
        JRequest::setVar('jform', $postData, 'post');
    }

    // Finally, save the processed form data
    return parent::save('id', $urlVar);
}

A: The controller is the wrong place for such things anyway, or is there a specific reason you want to do it in the controller?
Better look at the prepareTable function in the model. There you already have the table object with the properties to save and can sanitise them prior to saving.
Additional Info:
If you extend JControllerForm, you can specify
/**
 * @since   1.6
 */
protected $view_item = 'item';

/**
 * @since   1.6
 */
protected $view_list = 'items';

By default, the $view_item will equal to the context. The $view_list tries to guess a pluralized version of the $view_item. Usually by adding an s to the end.


text:
Q: Is it possible to call Scripts.Render or Styles.Render from the code behind of an ASPX file? Is there a way to replicate the behaviour of the @:Scripts/Styles.Render helper from code behind?
If I reference the bundles by using the BundleTable.Bundles.ResolveBundleUrl method, then bundling and minification occurs even with debug=true. I've read other questions, and the solution seems far obvious, by using the previously mentioned helper. But in my case, I don't know the name of the bundle while in the aspx, and it's generated in runtime in the code behind.
So, I need to add the references in the head, from the code behind, and I can't find a way to do it.
Is there a way? Or will I be forced to do it in the .aspx file?

A: You could also just render the script inline
<%: Scripts.Render("~/bundles/my_js") %>

A: This also may be of help for those who have come here later.
An alternate option without using a Literal Control:
  ClientScript.RegisterStartupScript(typeof(Page), "MyJS", Scripts.Render("~/bundles/bundledJS").ToHtmlString(), false);

A: Yep!
This is what I do for Web Forms. This example adds resources to the <head> but also works with any control for which Controls.Add() works
For CSS:
System.Web.UI.WebControls.Literal lit = new System.Web.UI.WebControls.Literal();
lit.Text = System.Web.Optimization.Styles.Render("~/bundles/my_css").ToHtmlString();
Header.Controls.Add(lit);

For JS:
System.Web.UI.WebControls.Literal lit = new System.Web.UI.WebControls.Literal();
lit.Text = System.Web.Optimization.Scripts.Render("~/bundles/my_js").ToHtmlString();
Header.Controls.Add(lit);

Also - since ASPX is a subclass of codebehind, you theoretically COULD get to the bundle name from ASPX by making it a protected (or public) variable in the codebehind (but you didn't post all your code so I'm not sure what you're up to exactly).


text:
Q: Is my proof of $\lim_{x\to \infty}\frac 1x = 0$ correct? I tried to prove $$\lim_{x\to \infty}\frac 1x = 0$$
I started as thus
$$\lim_{x\to \infty}\frac 1x=\lim_{x\to \infty}\frac x{x^2}$$
Applying L'Hospital's Rule
$$\lim_{x\to \infty}\frac 1x=\lim_{x\to \infty}\frac x{x^2}=\lim_{x\to \infty}\frac 1{2x}=\frac12\lim_{x\to \infty}\frac 1x$$
Thus,
$$\frac12\lim_{x\to \infty}\frac 1x=\lim_{x\to \infty}\frac 1x$$
which therefore implies
$$\lim_{x\to \infty}\frac 1x = 0$$
QED.

A: What you have (very cleverly!) shown is that if the limit $\lim_{x\to\infty}{1\over x}$ exists, then, by L'Hopital, it can only equal $0$.  Simply Beautiful Art's answer establishes the same result for $\lim_{x\to\infty}x$.  The difference is, in your case the limit actually does exist, while in SBA's case it doesn't.  That was SBA's implicit message:  You haven't proven the limit is $0$, you've only proven a conditional statement; it remains to show that the limit exists.
One possible way to show that the limit exists without explicitly computing it would be to invoke (or prove) a theorem saying that a monotonically decreasing function that's bounded below necessarily has a limit as $x$ tends to infinity.
In essence, you've done the second step of a two-step process.  There are other MSE questions where assuming the limit exists allows you to compute it; when I have more time I'll try to provide some links.  This is the first time I can think of, though, where I've seen L'Hopital's rule used as part of the derivation.

A: Not an answer - essentially a comment and too long for a comment that I don't want lost in the flurry of existing comments.
Many students try L'Hopital unthinkingly when faced with the limit of an indeterminate form like $0/0$. Often the application is incorrect. Even when it works it's often not the easiest method, and it's rarely the most illuminating. You learn much more thinking about simple order of magnitude inequalities or the first few terms of Taylor series expansions.
There are many answers on this site that illustrate that. Here are some; other answerers should feel free to edit this answer to link to more.
lHopitals $ \displaystyle \lim_{x\rightarrow \infty} \; (\ln x)^{3 x} $?
Finding the limit of a function with a trigonometric exponent
Computing $\lim_{x\to0} \frac 8 {x^8} \left[ 1 - \cos\frac{x^2} 2 - \cos\frac{x^2}4 + \cos\frac{x^2}2\cos\frac{x^2}4 \right]$ without using L'Hospital
Find the limit $\lim_{x\to0}\frac{\arcsin x -x}{x^2}$

A: I too tried the same thing:
$$\lim_{x\to\infty}x=\lim_{x\to\infty}\frac{x^2}x\stackrel{L'H}=2\lim_{x\to\infty}x$$
Thus,
$$\lim_{x\to\infty}x=2\lim_{x\to\infty}x$$
And as you have said,
$$\lim_{x\to\infty}x=0$$
QED (?)

A:
The horizontal lines in the picture are $y = \pm \dfrac 12$. As you can see, after $P = 3$ on the $x$ axis, the values of $f(x)$ are contained on the interval $\left(-\dfrac 12, \dfrac 12 \right)$ on the $y$ axis. In informal terms, the rigorous definition of $\lim_{x \to \infty} \dfrac 1x = 0$ is simply the assertion that that you can do exactly what I did above for any horizontal lines $y = \pm \epsilon$, no matter what (positive) $\epsilon$ you pick. That is, for any positive number $\epsilon$, you can always find some point $P$ somewhere on the $x$ axis such that for every $x$ larger than $P$, its $f(x)$ value is on the interval $(-\epsilon, \epsilon)$.

A: This is incorrect, as you can only use L'Hospital's Rule when you know the limit of the derivative ratio exists.

A: Your expression In other words:
As x approaches infinity, then 1/x approaches 0 so its answer is 0
Try to think in that way...
Your method is wrong as you can only use L'Hospital's Rule when you know the limit of the derivative ratio exists.


text:
Q: How to deal with multiple decimal when parsing XML with XSLT? I work in Retail side where we have MaxLineStatus that implies the current status of the order placed by customer.
As a part of this process, I have a XML that needs to be passed to XSLT for transformation.
My XSLT has a check of MaxLineStatus < 3700.7777 and the value of MaxLineStatus is being passed as 3200.200.100 in the input xml.
In ideal scenario, 3200.200.100 is less than 3700.7777 and in return it should fulfill the criteria and populate the orderLine Node.
Whenever i am passing 3200.200 in place of 3200.200.100 in xml, i am getting the desired output.
I even tried storing the xslt value in some variable and then comparing the value, but still it is not working.
I am comparing the value in below piece of code:
<xsl:attribute name="OrderLineCount"><xsl:value-of select="count(./OrderLine[(@MaxLineStatus < 3700.7777) and (@MaxLineStatus!='3200.150') and (@MaxLineStatus!='1400')])" /></xsl:attribute>

Thank you for the help and sorry for posting the xml and xslt in this manner. I was facing some issue indenting the same. Kindly excuse.
XML:
<OrderRelease APIName="sendReleaseModificationUpdateToILS" CarrierServiceCode="" DeliveryMethod="DEL" DocumentType="0003" EnterpriseCode="RETAIL" MFLocationId="70" NotificationType=" " OrderDate="20190410T06:49:07" OrderHeaderKey="2019041006490764562203" OrderLineCount="1" PriorityCode="" PriorityNumber="0" ProNumber="" ReleaseNo="1" RewardZoneIndicator="N" SCAC="" SalesOrderNo="1119100622586" ShipNode="BBY_9034" ShippingType="" WorkOrderKey="2019041006493464562225"><Shipnode Localecode="en_US_CST" NodeType="DDC" ReceiptProcessingTime="60.00" ShipNode="BBY_9034"><Extn FulfilmentDateBufferTime="0" LocationID="9034" MFLocationId="70" MobileSAS="N" /></Shipnode><Order CarrierServiceCode="" CustomerEMailID="RACHAKONDA.SATYASRINIVAS@BESTBUY.COM" DocumentType="0001" DraftOrderFlag="N" EnterpriseCode="RETAIL" MaxOrderStatus="3200.200.100" MinOrderStatus="1100.100" NotificationType=" " OrderDate="20190410T06:49:07" OrderHeaderKey="2019041006490764562203" OrderNo="1119100622586" OrderPurpose="" PriorityCode="" PriorityNumber="0" ReturnOrderHeaderKeyForExchange=" " SCAC="" SellerOrganizationCode="BBY_281" ShipNode=" " Status="Partially Awaiting Pickup Date" isHistory="N" /><OrderLine CarrierServiceCode="" ConditionVariable1="" ConditionVariable2="" DeliveryMethod="DEL" DependentOnLineKey=" " DerivedFromOrderHeaderKey="2018012921180556404483" DerivedFromOrderLineKey="2018012921180556404485" FulfillmentType="DELIVERY" HasDerivedChild="" LineType="RETURN" MaxLineStatus="3200.200.100" MaxLineStatusDesc="Awaiting Pickup Date" MinLineStatus="3200.200.100" MinLineStatusDesc="Awaiting Pickup Date" OpenQty="1" OrderLineKey="2019041006490764562204" OrderedQty="1" PrimeLineNo="1" ProcureFromNode="" PromisedApptEndDate="20190413T19:00:00" PromisedApptStartDate="20190413T07:00:00" SCAC="" ShipNode="BBY_9034" ShipToKey=" " Status="Awaiting Pickup Date" SubLineNo="1"><Extn ExpectedShipDate="20190410T00:00:00" StreetDate="19000101T00:00:00"><EOMSOrderLineList><EOMSOrderLine ExpectedApptEndDate="20190413T19:00:00" ExpectedApptStartDate="20190413T07:00:00" HingeSettings="" LineShipNodeWMS="WMS" OrderLineKey="2019041006490764562204" SellingStoreId="281" /></EOMSOrderLineList></Extn><Item CustomerItem="3519796" CustomerItemDesc="NINTENDO DS UNIVERSAL GAME SELECTOR CASE" ItemID="1640461" ManufacturerItem="52LB5D" ProductClass="" ProductLine="9.99.224" UnitOfMeasure="EACH" /><Notes NumberOfNotes="0" /><ParentOrderLineRelationships /></OrderLine></OrderRelease>

XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" /><xsl:template match="/OrderRelease"><xsl:copy><xsl:copy-of select="@*" /><xsl:attribute name="MFLocationId"><xsl:value-of select="./Shipnode/Extn/@MFLocationId" /></xsl:attribute><Extn><xsl:attribute name="ReleaseSeqNo"><xsl:value-of select="./Extn/@ReleaseSeqNo" /></xsl:attribute></Extn><xsl:attribute name="OrderLineCount"><xsl:value-of select="count(./OrderLine[(@MaxLineStatus < 3700.7777) and (@MaxLineStatus!='3200.150') and (@MaxLineStatus!='1400')])" /></xsl:attribute><xsl:for-each select="./OrderLine[(@MaxLineStatus < 3700.7777) and (@MaxLineStatus!='3200.150') and (@MaxLineStatus!='1400')]"><OrderLine><xsl:copy-of select="./@*" /><xsl:copy-of select="./OrderLineInvAttRequest" /><Item><xsl:copy-of select="./Item/@*" /><Extn><xsl:attribute name="BrandItemID"><xsl:value-of select="./Item/@CustomerItem" /></xsl:attribute></Extn></Item><Notes><xsl:copy-of select="./Notes/*" /></Notes><ParentOrderLineRelationships><xsl:copy-of select="./ParentOrderLineRelationships/*" /></ParentOrderLineRelationships><Extn><xsl:copy-of select="./Extn/*" /></Extn></OrderLine></xsl:for-each><Notes><xsl:for-each select="./Notes/Note"><xsl:copy-of select="current()" /></xsl:for-each></Notes><Order><xsl:attribute name="OrderPurpose"><xsl:value-of select="./Order/@OrderPurpose" /></xsl:attribute><xsl:attribute name="ReturnOrderHeaderKeyForExchange"><xsl:value-of select="./Order/@ReturnOrderHeaderKeyForExchange" /></xsl:attribute><xsl:attribute name="CustomerEMailID"><xsl:value-of select="./Order/@CustomerEMailID" /></xsl:attribute><xsl:attribute name="SellerOrganizationCode"><xsl:value-of select="./Order/@SellerOrganizationCode" /></xsl:attribute><Extn><xsl:attribute name="BillingPhoneNo"><xsl:value-of select="./Order/Extn/@BillingPhoneNo" /></xsl:attribute></Extn></Order><xsl:copy-of select="./PersonInfoShipTo" /></xsl:copy></xsl:template>

Actual Result:
<OrderRelease APIName="sendReleaseModificationUpdateToILS" CarrierServiceCode="" DeliveryMethod="DEL" DocumentType="0003" EnterpriseCode="RETAIL" MFLocationId="70" NotificationType=" " OrderDate="20190410T06:49:07" OrderHeaderKey="2019041006490764562203" OrderLineCount="1" PriorityCode="" PriorityNumber="0" ProNumber="" ReleaseNo="1" RewardZoneIndicator="N" SCAC="" SalesOrderNo="1119100622586" ShipNode="BBY_9034" ShippingType="" WorkOrderKey="2019041006493464562225"><Extn ReleaseSeqNo="" /><Notes></Notes><Order OrderPurpose="" ReturnOrderHeaderKeyForExchange=" " CustomerEMailID="RACHAKONDA.SATYASRINIVAS@BESTBUY.COM" SellerOrganizationCode="BBY_281"><Extn BillingPhoneNo="" /></Order></OrderRelease>

Expected Result:
<OrderRelease APIName="sendReleaseModificationUpdateToILS" CarrierServiceCode="" DeliveryMethod="DEL" DocumentType="0003" EnterpriseCode="RETAIL" MFLocationId="70" NotificationType=" " OrderDate="20190410T06:49:07" OrderHeaderKey="2019041006490764562203" OrderLineCount="1" PriorityCode="" PriorityNumber="0" ProNumber="" ReleaseNo="1" RewardZoneIndicator="N" SCAC="" SalesOrderNo="1119100622586" ShipNode="BBY_9034" ShippingType="" WorkOrderKey="2019041006493464562225"><Extn ReleaseSeqNo="" /><OrderLine CarrierServiceCode="" ConditionVariable1="" ConditionVariable2="" DeliveryMethod="DEL" DependentOnLineKey=" " DerivedFromOrderHeaderKey="2018012921180556404483" DerivedFromOrderLineKey="2018012921180556404485" FulfillmentType="DELIVERY" HasDerivedChild="" LineType="RETURN" MaxLineStatus="3200.200.100" MaxLineStatusDesc="Awaiting Pickup Date" MinLineStatus="3200.200.100" MinLineStatusDesc="Awaiting Pickup Date" OpenQty="1" OrderLineKey="2019041006490764562204" OrderedQty="1" PrimeLineNo="1" ProcureFromNode="" PromisedApptEndDate="20190413T19:00:00" PromisedApptStartDate="20190413T07:00:00" SCAC="" ShipNode="BBY_9034" ShipToKey=" " Status="Awaiting Pickup Date" SubLineNo="1"><Item CustomerItem="3519796" CustomerItemDesc="NINTENDO DS UNIVERSAL GAME SELECTOR CASE" ItemID="1640461" ManufacturerItem="52LB5D" ProductClass="" ProductLine="9.99.224" UnitOfMeasure="EACH"><Extn BrandItemID="3519796" /></Item><Notes></Notes><ParentOrderLineRelationships></ParentOrderLineRelationships><Extn><EOMSOrderLineList><EOMSOrderLine ExpectedApptEndDate="20190413T19:00:00" ExpectedApptStartDate="20190413T07:00:00" HingeSettings="" LineShipNodeWMS="WMS" OrderLineKey="2019041006490764562204" SellingStoreId="281" /></EOMSOrderLineList></Extn></OrderLine><Notes></Notes><Order OrderPurpose="" ReturnOrderHeaderKeyForExchange=" " CustomerEMailID="RACHAKONDA.SATYASRINIVAS@BESTBUY.COM" SellerOrganizationCode="BBY_281"><Extn BillingPhoneNo="" /></Order></OrderRelease>

A: In XSLT 1.0 the only way to compare strings for < and > relationships is by sorting; the < and > operators always convert to numbers (and if the value can't be converted to a number, it is treated as NaN).
Ideally, move forward to a more recent XSLT version (1.0 is getting VERY old).
If you can't do that, then it's going to be a convoluted work-around. Three possible approaches:
(a) find some way of converting these "dotted decimal" values into numbers that sort correctly. (e.g. pad each component to a standard number of digits, then strip the dots).
(b) sort the values, allocate sequence numbers, and test whether a value satisfies the relevant condition by looking at the sequence numbers.
(c) call out to an extension function in an external language such as Java to do the comparison.


text:
Q: Why doesn't my belkin usb 2.0 4-port ultra-mini hub work on windows xp? I just bought a belkin usb hub.  I am running a fully updated Windows XP.  When I plug in the device, it is not recognized.  The device manager says "Unknown Device".  The device properties say "There is no driver installed for this device."  If I remove the device from the device manager listing and "scan for new hardware" I get back to the same state.
Edit: Its red light is on, so it is getting power.
Why is it not working, and how do I fix it?

A: Try this:

*

*Belkin's support page to see if there is something you are missing for that USB hub.

*Also try to reboot your PC/laptop, but keep the hub plugged in.

*Double check your chipset driver and update it if you need to, along side with any other drivers the PC/laptop manufacturer.

Good luck!

A: Try uninstall your USB root hubs in your XP device manager. After uninstall reboot the PC and try again. The drivers should automitically re-install.
If that does not work, it might be the actual USB port on the PC, not all USB ports actually support USB hubs. Usually the USB ports on the back of teh machine supports USB hubs.
You can also try and see if the manufacturer of your PC/laptop has any


text:
Q: Recommended Java (or Kotlin) serialization format for table-like data and random (indexed) read access? I have around ~50–100MB of data which consists of a list of structured objects. It is created once and I then want to efficiently read/find objects in it without having to deserialize it completely to memory when reading the resources.
Since I want to access objects randomly, I need some kind of index. I do not want to use a whole database approach like sqlite (I only need read access) and avoid 'heavy' dependencies.
Before I try to throw together my own, probably crappy serialization format, I was wondering if there are already good library I could use?
I found some interesting de/serialization formats like VelocyPack (https://github.com/arangodb/java-velocypack), but if I understood the API correctly, it allows efficient iterating over arrays, not random access. Even if I stored an index of some sort, it would not help here.


text:
Q: Rails: table column returning nil (unresponsive) This is the continuation of a previous problem that I was able to solve: Parameters not saving properly (Rails)
But now I've encountered a stranger issue. Although I can get the parameter to save, it is unresponsive when I attempt to refer to it.
The Model:
# == Schema Information
#
# Table name: messages
#
#  id             :integer          not null, primary key
#  content        :text
#  sender_id      :integer
#  recipient_list :text
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#

class Message < ActiveRecord::Base
  attr_accessible :content, :sender_id, :recipient_list
  attr_reader :recipient_list #necessary for jquery-token-fields
  serialize :recipient_list, Array

  validates :content, presence: true
  validates :sender_id, presence: true

  def recipient_list=(ids) #necessary for jquery-token-fields
    recipient_list = ids.split(",")
    super(recipient_list)
  end
end

Object:
#<Message id: 60, content: "foobar123", sender_id: 1, recipient_list: ["1", "2"], created_at: "2012-08-23 06:40:00", updated_at: "2012-08-23 06:40:00">]

View:
<%= Message.find_by_id(60).content %>
<%= Message.find_by_id(60).recipient_list %>

The result is that the call on content returns as expected: "foobar123"  However, the call on recipient_list returns only nil. Despite there clearly being a value there. I suspect that the recipient_list=(ids) method may be overriding the usual function of what the @message.recipient_list would otherwise be doing. Am I at least in the right ballpark? What's going on here?

A: You redefined default recipient_list method with your getter on this line:
attr_reader :recipient_list #necessary for jquery-token-fields

I think you have to remove it. Then everything should be fine.
I don't know what does your comment mean, your model has getters and setters for all of the table columns.


text:
Q: Excel special symbols in formula Folks,
I am trying to run DDE ( with MetaTrader Terminal 4 platform ) from Excel info using a defined syntax of '= MT4|ASK!USDCHF' and it works fine.
However, when I try to use it for a #GOOG symbol or for a ^Coffee, Excel returns it as a formula being corrupt.
The reason for it, obviously is that '#' or '^' after ASK! doesn't get recognised as a normal string value.
How do I embed such symbols? ASCII didn't help either since it works on the output value, not on the input value.


text:
Q: 'to effect' vs 'to give effect'
To give effect to something or to carry/bring/put something into effect is to make it begin doing what it was intended to do.
Are these verb phrases ('to give effect...', to + verb + into + effect) containing 'effect' prolix and tortuous? Why not simply use 'to effect'? They transpire  to suggest that there may be differences?

I originally asked the above. User FumbleFingers kindly replied:

You give effect to X when X is something that already "exists", but hasn't YET been "activated" so it will actually do whatever it's intended to do (such as a plan that hasn't been put into practice yet). Often when you effect X, you cause X (which didn't previously "exist") to come into being. The idea that all "longer" phrasings are prolix, tortuous or otherwise "undesirable" is a serious misconception.

I accept this, but am still confused about the other case where X already exists. User StoneyB answered:

To give effect to something or put it into effect is to cause that something to become capable of producing effects.

But how does this differ from effect? To use StoneyB's example, If I effect a change in my lifestyle, then this change itself can 'cause [that something] to become capable of producing [further] effects'?

A: Oh boy. So first off, let me just run down the difference between 'affect' and 'effect' to avoid confusion.
'Affect' is to change something.

The light affected the plants' growth.

'Effect', when used as a verb, is to make something happen.

The council decided to effect their plans, starting tomorrow.

Now, 'give effect' in the context you used it means something like 'activate' or 'enable'; your original definition used it in a legal context to activate a piece of law.

The court refused to give effect to that part of the document.

From reading the definition, it seems extremely similar to 'effect', in that they both start something; but 'give effect' specifically requires the object exist, and already be inactive, whereas in my above example, the plans are being acted upon; that is, things are being transformed from 'plan' to 'stuff actually being carried out'.
It's kind of a fiddly difference, really.

A: I basically agree with SoltBegins, but let me state it a different way.
To "give effect to" something is to make it work, to make it carry out its desired intent.
To "effect" something (as a verb) is to bring it into existence or make it happen.
So if you said, "Mr Smith effected an agreement between the parties", that would mean that Smith managed to convince the parties to come to some compromise. Like, he convinced them that they should each pay half the cost. If you said, "Mr Smith gave effect to the agreement between the parties", that would mean that he did something to make the agreement actually happen, like he collected the money from each of them.
Addendum
To try to answer your question:
By "make it happen" here I mean something along the lines of "bring it into existence". Maybe it would have been more clear if I'd just left it at "bring it into existence".
"Give effect to" specifically means to cause something that previously existed only as an idea or on paper to actually happen. We routinely talk about "giving effect to a contract" or "giving effect to the new law".
To "effect" simply means to cause, or cause to exist. Sometimes, often, causing something to exist and making it happen are the same thing. When we say "Smith effected X" we often mean that he both caused it to exist and caused it to produce the desired outcome. If, for example, you say "I effected an update to the document", making the update exist and making it actually change the document are probably a single event, you can't separate them out. So in a given case,
whether "to effect X" means to create a concept that is not yet actually happening in the real world,
or if it means both to create the concept and to really make it happen, depends on the context.
In the case of an agreement, if all the parties are truly willing it might be that once the agreement is made, they all go off and do whatever, and no one thinks of a separate step of giving effect to the agreement. It just depends on context.

A: "Effect" is used with verbs or actions, and "give effect" is used with nouns.
Conducting a few searches looking for an example sentence for "give effect," I noticed it's often used in the context of law.  I can't think of a common example where it's not used that way.

He effected his escape with knotted bedsheets
The court refused to give effect to that part of the document


text:
Q: using arrays to store information and retrieving them with php for example, i have

and the process page:
`   $fashion_id = $_GET['menu_id'];
if ($menu_id == "1") {
    $id = "1";
    $menu_name ="Business Fashion";
    $img_file ="images/mushroomsoup.jpg";
    $description ="mushroom soup";
    $color ="red";
}
elseif($menu_id =="2") {
    $id ="2";
    $menu_name ="minestrone soup";
    $img_file ="images/mine.jpg";
    $description ="minestrone soup";
    $color ="blue";
}
elseif($menu_id =="3") {
    $id="3";
    $menu_name ="carrot soup";
    $img_file ="images/carrot.jpg";
    $description ="carrot soup.";
    $color ="green";
}
elseif ($menu_id =="4"){
    $id="4";
    $menu_name ="shark fin";
    $img_file ="images/sharkfin.jpg";
    $description ="sharkfin.";
    $color ="gray";
}

    echo "
Welcome to my restaurant!
";
    echo "You have selected $menu_name. Menu ID($id)
";
    echo "
";
    echo "$description";

    ?>

'
Let's say I want to use array() function instead of using if-else statement, how can I do it? I understand there's a easier method by using a sql statement but I've not been taught sql yet and right now I can only use php.
Thanks in advance!

A: You're probably looking for the switch() construct.
From the PHP manual documentation:

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

So, your code will look like:
switch ($menu_id) {
    case '1':
        # code
        break;
    case '2':
        #code
        break;

    ...

    default:
        # code...
        break;
}

A: This should get you started:
$menus = array(
    1 => array(
        'menu_name'   => "Business Fashion",
        'img_file'    => "images/mushroomsoup.jpg",
        'description' => "mushroom soup",
        'color'       => "red"
    ),
    2 => array(
        'menu_name'   => "minestrone soup",
        'img_file'    => "images/mine.jpg",
        'description' => "minestrone soup",
        'color'       => "blue"
    ),
);

// Print out the menu name for menu ID #1
echo $menus[$menu_id]['menu_name']; // Business Fashion

Basically you put your menu items in an array (of arrays) and then access them using the menu ID you get from for query string.
To put this into a table you would use a simple loop:
foreach ($menus as $id => $menu) {
?>

        <?php echo $menu['menu_name']; ?>
        <?php echo $menu['img_file']; ?>
        <?php echo $menu['description']; ?>
        <?php echo $menu['color']; ?>

<?php
}

You obviously need to alter that to suit your needs but should give you the idea. If you need the menu ID you just echo out $id.

A: You could do something like this:
$menu = array(
   "1"=>array(
      "id"=>1,
      "menu_name"=>"shark fin";
      ...
   )
   ...
)

Then use $entry = $menu[$menu_id] to get the entry, and $id = $entry["id"], etc to get the parts. Don't forget to make sure $menu_id is actually valid. You can easily type in  . (Strange fashion, BTW.)
Good luck in learning PHP!

A: you can use switch case statements.
http://www.php.net/manual/en/control-structures.switch.php


text:
Q: Substitution/change of variable in integration Integration techniques are newbies to me right now, and I was assigned this integral. My professor recommend to use substitution/change of variable to integrate this function.
$$\int (x^6+x^3)\sqrt[3]{x^3+2} dx$$
He gave me a hint after asking him for help and told me ¨Look at what is inside the cubic root, so that when you take the derivative of what is in the inside, you get what is on the outside of the cubic root. So that this works, you could try to factorize something out of x^3+2, that way when you derivee it , the outcome can help you with everything that is on the outside of the cubic root.¨
I was thinking for example x^3+2 = x^3(1+2x^-3)

A: I would rewrite the integral as
$$\int x\color{red}{x^2}(x^3+1)\sqrt[3]{\color{red}{x^3+1}+1}\,\mathrm dx$$
then substitute $u=x^3+1$ (which gives $x=\sqrt[3]{u-1}$)  and $\mathrm du=3x^2\,\mathrm dx$ to get
$$\frac13\int\sqrt[3]{u-1}u\sqrt[3]{u+1}\,\mathrm du=\frac13\int u\sqrt[3]{u^2-1}\,\mathrm du$$
Then another substitution, $v=u^2-1$ and $\mathrm dv=2u\,\mathrm du$, leaving you with
$$\frac16\int\sqrt[3]{v}\,\mathrm dv$$


text:
Q: After texlive package update, nothing compiles I updated my packages in texlive 2021 today through the GUI package manager. Afterwards, no document compiles. When trying to compile a basic document with pdflatex, I receive the following error:
pdflatex

---! c:/Users/.../texlive/2021/texmf-var/web2c/pdftex/pdflatex.fmt made by different executable version
(Fatal format file error; I'm stymied)

When compiling a basic document in xelatex with polyglossia, I receive the following error message:
\documentclass{article}
\usepackage{polyglossia}
\begin{document}
Test
\end{document}

! LaTeX3 Error: Mismatched LaTeX support files detected. (LaTeX3)
Loading 'expl3.sty' aborted! (LaTeX3)         (LaTeX3)        The L3
programming layer in the LaTeX format (LaTeX3)        is dated
2021-06-01, but in your TeX tree the files require (LaTeX3)        at
least 2021-07-12.

Neither compilation produces a log file. Clearly something has gone very wrong, but I wouldn't know what. Any pointers?


text:
Q: How to set statistics level of a table in postgres? I know how to set statistics level for a particular column i.e
alter table table_name alter column column_name set statistics 100;

However, if I wish to set statistics level for a particular table or for a particular schema, is there is one liner command?

A: There is nothing ready-made for a table or schema, because that is seldom useful.
But you can set it for a whole database with
ALTER DATABASE mydb SET default_statistics_target = 1000;

You can also use psql's \gexec to set the statistics target for all columns of a table:
SELECT format(
          'ALTER TABLE %s ALTER %I SET STATISTICS 1000',
          attrelid::regclass,
          attname
       )
FROM pg_attribute
WHERE attrelid = 'pgbench_tellers'::regclass
  AND attnum > 0 \gexec


text:
Q: fail to push new branch to remote repo on github (using -u flag) I simple cloned a project using github copy & paste repository url, created new branch:
git checkout -b <branch>

added and commit changes, then pushed with -u flag:
git push -u origin <branch>

exactly how describe here
and I get:

remote: Repository not found. fatal: repository
  'https://github.com/companyUsername/MyRepo.git/' not found

never happened before...so weird :/

A: Problem: Wrong origin

remote: Repository not found. fatal: repository 'https://github.com/MyRepo.git/' not found

Check your URL as it's in the form https://github.com/username/repository.git. You omitted your username. You can remove and re-add your origin like this:
git remote rm origin
git remote add origin "https://github.com/username/repository.git"


text:
Q: How to get the index of multiple mininum values in a column? I'm trying to get the k minimun values of each column on a dataframe. however I am unable to get the indices.
I have a dataframe that contains the distances between data called ddist. I want to select the k minimum elements in each column and make a list of the no. of row each element is in so I can use it for KNN later.
These are the lines where I tried to get the indices, however i get a list with the indexes and the values and cannot access the indices alone.
list_min = []
for column in ddist:
    idx = ddist.nsmallest(k,column)
    idx=idx[0]
    list_min.append(idx)
list_min

the output looks like this
[43     0.0
 188    0.0
 202    0.0
 Name: 0, dtype: float64,
 21    0.04
 26    0.04
 94    0.04
 Name: 0, dtype: float64,
 27     0.39
 52     0.39
 164    0.39
 Name: 0, dtype: float64,
 33     0.01
 131    0.01
 210    0.01
...

but I only want to get the integers that look appear like a column on each entry.

A: You should try pd.Series.index:
list_min = []
for column in ddist:
    idx = ddist.nsmallest(k,column)
    idx=idx[0]
    list_min.append(idx.index.tolist())
list_min


text:
Q: How to define unique workspace for each branch in Multi branch build Jenkins I'm using Freestyle multi-branch project to define a build for all branches in the project.
The problem is that if I use "Use custom workspace" I cannot define a path using ${branch} name.
I would like to do something like:
Use custom workspace: [dropfolder]\${branch}
But the ${branch} is not recognizable.

A: You cannot use dynamic variables when configuring workspace location.
You can however build multiple branches automatically, check i.e. this question.


text:
Q: iOS AdMob Mediation Not Working (iAd Never Shows Up) I've completely and properly (to my understanding) setup AdMob mediation so that my iAd will show up before my AdMob ad, and if the iAd doesn't fill then I would like to show the AdMob ad. Thing is, iAd banner never shows up..EVER! If I disable iAd in my AdMob account everything works perfectly and AdMobs show up but I would really like to get both working. Any help on this matter would be greatly appreciated. (I've followed Googles guide to setting up mediation). Anyone else having this issue?
Thanks in advance for any help :)

A: Have you added the admob adapter for iAds to your project? It can be found here,
https://developers.google.com/mobile-ads-sdk/docs/admob/ios/mediation-networks
Direct download link : https://dl.google.com/dl/googleadmobadssdk/libadapteriad.zip
If not AdMob won't be able to serve iAds via their mediation SDK.

A: Weird solution but it worked:
By following the guide provided by Google to setup Ad Mediation in iOS, it tells you to implememnt it via Storyboard/nib. Once I removed this method and simply implemented the GADBannerView programmatically, everything began to work as expected. Quite the annoying issue, but thankfully it's solved and I can move on.


text:
Q: Gradle - download dependencies, lock versions and update dependencies manually The issue.
Gradle dependency management made so:

*

*there is no easy way to check availability of dependencies updates (only using some third-party plugins like ben-manes/gradle-versions-plugin) and download updates replacing old versions;

*dependencies artifacts are downloaded from remote repositories and then stored in gradle cache and reused in succeeding builds; but successful compilation of your project must not depend on having a connection to Internet, availability of remote repositories and existence of specific versions of dependencies in these repositories.

The goal.

*

*download and store all dependencies artifacts in VCS;

*manually check updates for these dependencies and download them.

A: My solution works for Gradle configuration using java or android plugins.
java plugin defines compile and testCompile configurations.
compile is for dependencies that are required to compile the production source of the project. testCompile is for dependencies that are required to compile the test source of the project.
Let's define our own configurations in build.gradle:
configurations {
    download
    testDownload
}

Next let's create directories:

*

*libs/compile/downloaded is where download dependencies will be stored;

*libs/testCompile/downloaded is where testDownload dependencies will be stored.

Next we define several tasks.
Delete dependencies from download configuration:
task cleanDownloadedDependencies(type: Delete) {
    delete fileTree('libs/compile/downloaded')
}

Delete dependencies from testDownload configuration:
task cleanDownloadedTestDependencies(type: Delete) {
    delete fileTree('libs/testCompile/downloaded')
}

Download dependencies from download configuration:
task downloadDependencies(type: Copy) {
    from configurations.download
    into "libs/compile/downloaded/"
}

Download dependencies from testDownload configuration:
task downloadTestDependencies(type: Copy) {
    from configurations.testDownload
    into "libs/testCompile/downloaded/"
}

Execute all above tasks to update dependencies:
task updateDependencies {
    dependsOn cleanDownloadedDependencies, cleanDownloadedTestDependencies, downloadDependencies, downloadTestDependencies
}

Next we define our dependencies:
dependencies {
    download(
            'com.google.code.gson:gson:+',
            'joda-time:joda-time:+',
    )
    testDownload(
            'junit:junit:+'
    )

And then we tell where compile and testCompile configurations should take dependencies used for compilation.
    compile fileTree(dir: 'libs/compile', include: '**/*.jar')
    testCompile fileTree(dir: 'libs/testCompile', include: '**/*.jar')
}

Now you can download or update already downloaded dependencies:
./gradlew updateDependencies

If you are using android plugin then you can also add androidTestDownload configuration for dependencies that are required for compilation and running tests on Android device. Also some dependencies can be provided as aar artifacts.
This is the example for Gradle configuration using android plugin:
...

repositories {

    ...

    flatDir {
        dirs 'libs/compile', 'libs/compile/downloaded',
                'libs/testCompile', 'libs/testCompileDownloaded',
                'libs/androidTestCompile', 'libs/androidTestCompile/downloaded'
    }
}

configurations {
    download
    testDownload
    androidTestDownload
}

android {
    ...
}

dependencies {
    download(
            'com.android.support:support-v4:+',
            'com.android.support:appcompat-v7:+',
            'com.google.android.gms:play-services-location:+',
            'com.facebook.android:facebook-android-sdk:+',
            'com.vk:androidsdk:+',
            'com.crashlytics.sdk.android:crashlytics:+',
            'oauth.signpost:signpost-core:+',
            'oauth.signpost:signpost-commonshttp4:+',
            'org.twitter4j:twitter4j-core:+',
            'commons-io:commons-io:+',
            'com.google.code.gson:gson:+',
            'org.jdeferred:jdeferred-android-aar:+'
    )
    compile fileTree(dir: 'libs/compile', include: '**/*.jar')
    testCompile fileTree(dir: 'libs/testCompile', include: '**/*.jar')
    androidTestCompile fileTree(dir: 'libs/androidTestCompile', include: '**/*.jar')
}

task cleanDownloadedDependencies(type: Delete) {
    delete fileTree('libs/compile/downloaded')
}

task cleanDownloadedTestDependencies(type: Delete) {
    delete fileTree('libs/testCompile/downloaded')
}

task cleanDownloadedAndroidTestDependencies(type: Delete) {
    delete fileTree('libs/androidTestCompile/downloaded')
}

task downloadDependencies(type: Copy) {
    from configurations.download
    into 'libs/compile/downloaded/'
}

task downloadTestDependencies(type: Copy) {
    from configurations.testDownload
    into 'libs/testCompile/downloaded/'
}

task downloadAndroidTestDependencies(type: Copy) {
    from configurations.androidTestDownload
    into 'libs/androidTestCompile/downloaded/'
}

task updateDependencies {
    dependsOn cleanDownloadedDependencies, cleanDownloadedTestDependencies, cleanDownloadedAndroidTestDependencies, downloadDependencies, downloadTestDependencies, downloadAndroidTestDependencies
}

fileTree(dir: 'libs/compile', include: '**/*.aar')
        .each { File file ->
    dependencies.add("compile",
            [name: file.name.lastIndexOf('.').with { it != -1 ? file.name[0..<it] : file.name }, ext: 'aar'])
}

fileTree(dir: 'libs/testCompile', include: '**/*.aar')
        .each { File file ->
    dependencies.add("testCompile",
            [name: file.name.lastIndexOf('.').with { it != -1 ? file.name[0..<it] : file.name }, ext: 'aar'])
}

fileTree(dir: 'libs/androidTestCompile', include: '**/*.aar')
        .each { File file ->
    dependencies.add("androidTestCompile",
            [name: file.name.lastIndexOf('.').with { it != -1 ? file.name[0..<it] : file.name }, ext: 'aar'])
}

A: For locking versions of downloaded dependencies (library/ etc versions to hard-coded versions) for making the builds reproducible, now Gradle 4.8 and onwards, we'll have  inbuilt "dependency lock" support. This will help greatly to make builds reproducible if someone is using dynamic versions (M.m.p/i) Major.minor.patch/interimBranch etc (ex: 4.+ or 3.1.+) or version range for pulling artifacts from a binary repository tool (ex: Artifactory / Nexus).
Any Gradle user who is using Gradle version 4.8+ should start using this new feature.
https://docs.gradle.org/4.8/userguide/dependency_locking.html
For Gradle 4.8 Release Notes: https://docs.gradle.org/4.8/release-notes.html
In past, this dependency lock feature was provided to Gradle community and made available via a FOSS plugin available to Gradle from Netflix Nebula's https://github.com/nebula-plugins/gradle-dependency-lock-plugin and https://plugins.gradle.org/plugin/nebula.dependency-lock