text:
Q: What is the difference between casting and coercing? I've seen both terms be used almost interchangeably in various online explanations, and most text books I've consulted are also not entirely clear about the distinction.
Is there perhaps a clear and simple way of explaining the difference that you guys know of?

Type conversion (also sometimes known as type cast)
To use a value of one type in a context that expects another.
Nonconverting type cast (sometimes known as type pun)
A change that does not alter the underlying bits.
Coercion
Process by which a compiler automatically converts a value of one type into a value of another type when that second type is required by the surrounding context.

A: According to Wikipedia,

In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another.

The difference between type casting and type coercion is as follows:
           TYPE CASTING           |                   TYPE COERCION
                                  |
1. Explicit i.e., done by user    | 1. Implicit i.e., done by the compiler
                                  |
2. Types:                         | 2. Type:
    Static (done at compile time) |     Widening (conversion to higher data
                                  |     type)
    Dynamic (done at run time)    |     Narrowing (conversion to lower data
                                  |     type)
                                  |
3. Casting never changes the      | 3. Coercion can result in representation
   the actual type of object      |    as well as type change.
   nor representation.            |

Note: Casting is not conversion. It is just the process by which we treat an object type as another type. Therefore, the actual type of object, as well as the representation, is not changed during casting.
I agree with @PedroC88's words:

On the other hand, coercing implies the creation of a new object in
  memory of the new type and then the original type would be copied over
  to the new one, leaving both objects in memory (until the Garbage
  Collectors takes either away, or both).

A: Usages vary, as you note.
My personal usages are:

*

*A "cast" is the usage of a cast operator. A cast operator instructs the compiler that either (1) this expression is not known to be of the given type, but I promise you that the value will be of that type at runtime; the compiler is to treat the expression as being of the given type, and the runtime will produce an error if it is not, or (2) the expression is of a different type entirely, but there is a well-known way to associate instances of the expression's type with instances of the cast-to type. The compiler is instructed to generate code that performs the conversion. The attentive reader will note that these are opposites, which I think is a neat trick.

*A "conversion" is an operation by which a value of one type is treated as a value of another type -- usually a different type, though an "identity conversion" is still a conversion, technically speaking. The conversion may be "representation changing", like int to double, or it might be "representation preserving" like string to object. Conversions may be "implicit", which do not require a cast, or "explicit", which do require a cast.

*A "coercion" is a representation-changing implicit conversion.

A: Casting preserves the type of objects.  Coercion does not.
Coercion is taking the value of a type that is NOT assignment compatible and converting to a type that is assignment compatible.  Here I perform a coercion because Int32 does NOT inherit from Int64...so it's NOT assignment compatible. This is a widening coercion (no data lost). A widening coercion is a.k.a. an implicit conversion.  A Coercion performs a conversion.
void Main()
{
    System.Int32 a = 100;
    System.Int64 b = a;
    b.GetType();//The type is System.Int64.
}

Casting allows you to treat a type as if it were of a different type while also preserving the type.
    void Main()
    {
        Derived d = new Derived();
        Base bb = d;
        //b.N();//INVALID.  Calls to the type Derived are not possible because bb is of type Base
        bb.GetType();//The type is Derived.  bb is still of type Derived despite not being able to call members of Test
    }

    class Base
    {
        public void M() {}
    }

    class Derived: Base
    {
        public void N() {}
    }

Source: The Common Language Infrastructure Annotated Standard by James S. Miller
Now what's odd is that Microsoft's documentation on Casting does not align  with the ecma-335 specification definition of Casting.

Explicit conversions (casts): Explicit conversions require a cast
  operator. Casting is required when information might be lost in the
  conversion, or when the conversion might not succeed for other
  reasons. Typical examples include numeric conversion to a type that
  has less precision or a smaller range, and conversion of a base-class
  instance to a derived class.

...This sounds like Coercions not Casting.
For example,
  object o = 1;
  int i = (int)o;//Explicit conversions require a cast operator
  i.GetType();//The type has been explicitly converted to System.Int32.  Object type is not preserved.  This meets the definition of Coercion not casting.

Who knows?  Maybe Microsoft is checking if anybody reads this stuff.

A: From the CLI standard:

I.8.3.2 Coercion
Sometimes it is desirable to take a value of a type that is not assignable-to a location, and convert
  the value to a type that is assignable-to the type of the location. This is accomplished through
  coercion of the value. Coercion takes a value of a particular type and a desired type and attempts
  to create a value of the desired type that has equivalent meaning to the original value. Coercion
  can result in representation change as well as type change; hence coercion does not necessarily
  preserve object identity.
There are two kinds of coercion: widening, which never loses information, and narrowing, in
  which information might be lost. An example of a widening coercion would be coercing a value
  that is a 32-bit signed integer to a value that is a 64-bit signed integer. An example of a
  narrowing coercion is the reverse: coercing a 64-bit signed integer to a 32-bit signed integer.
  Programming languages often implement widening coercions as implicit conversions, whereas
  narrowing coercions usually require an explicit conversion.
Some coercion is built directly into the VES operations on the built-in types (see §I.12.1). All
  other coercion shall be explicitly requested. For the built-in types, the CTS provides operations
  to perform widening coercions with no runtime checks and narrowing coercions with runtime
  checks or truncation, according to the operation semantics.
I.8.3.3 Casting
Since a value can be of more than one type, a use of the value needs to clearly identify which of
  its types is being used. Since values are read from locations that are typed, the type of the value
  which is used is the type of the location from which the value was read. If a different type is to
  be used, the value is cast to one of its other types. Casting is usually a compile time operation,
  but if the compiler cannot statically know that the value is of the target type, a runtime cast check
  is done. Unlike coercion, a cast never changes the actual type of an object nor does it change the
  representation. Casting preserves the identity of objects.
For example, a runtime check might be needed when casting a value read from a location that is
  typed as holding a value of a particular interface. Since an interface is an incomplete description
  of the value, casting that value to be of a different interface type will usually result in a runtime
  cast check.

A: Type Conversion:

The word conversion refers to either implicitly or explicitly changing a value from one data type to another, e.g. a 16-bit integer to a 32-bit integer.
The word coercion is used to denote an implicit conversion.
The word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretation of a bit-pattern or a real conversion.

So, coercion is implicit, cast is explicit, and conversion is any of them.

Few examples (from the same source) :
Coercion (implicit):
double  d;
int     i;
if (d > i)      d = i;

Cast (explicit):
double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc; //result == 9

A: Casting is the process by which you treat an object type as another type, Coercing is converting one object to another.
Note that in the former process there is no conversion involved, you have a type that you would like to treat as another, say for example, you have 3 different objects that inherit from a base type, and you have a method that will take that base type, at any point, if you know the specific child type, you can CAST it to what it is and use all the specific methods and properties of that object and that will not create a new instance of the object.
On the other hand, coercing implies the creation of a new object in memory of the new type and then the original type would be copied over to the new one, leaving both objects in memory (until the Garbage Collectors takes either away, or both).
As an example consider the following code:
class baseClass {}
class childClass : baseClass {}
class otherClass {}

public void doSomethingWithBase(baseClass item) {}

public void mainMethod()
{
    var obj1 = new baseClass();
    var obj2 = new childClass();
    var obj3 = new otherClass();

    doSomethingWithBase(obj1); //not a problem, obj1 is already of type baseClass
    doSomethingWithBase(obj2); //not a problem, obj2 is implicitly casted to baseClass
    doSomethingWithBase(obj3); //won't compile without additional code
}

*

*obj1 is passed without any casting or coercing (conversion) because it's already of the same type baseClass

*obj2 is implicitly casted to base, meaning there's no creation of a new object because obj2 can already be baseClass

*obj3 needs to be converted somehow to base, you'll need to provide your own method to convert from otherClass to baseClass, which will involve creating a new object of type baseClass and filling it by copying the data from obj3.

A good example is the Convert C# class where it provides custom code to convert among different types.

A: Below is a posting from the following article:
The difference between coercion and casting is often neglected. I can see why; many languages have the same (or similar) syntax and terminology for both operations. Some languages may even refer to any conversion as "casting," but the following explanation refers to concepts in the CTS.
If you are trying to assign a value of some type to a location of a different type, you can generate a value of the new type that has a similar meaning to the original. This is coercion. Coercion lets you use the new type by creating a new value that in some way resembles the original. Some coercions may discard data (e.g. converting the int 0x12345678 to the short 0x5678), while others may not (e.g. converting the int 0x00000008 to the short 0x0008, or the long 0x0000000000000008).
Recall that values can have multiple types. If your situation is slightly different, and you only want to select a different one of the value's types, casting is the tool for the job. Casting simply indicates that you wish to operate on a particular type that a value includes.
The difference at the code level varies from C# to IL. In C#, both casting and coercion look fairly similar:
static void ChangeTypes(int number, System.IO.Stream stream)
{
    long longNumber = number;
    short shortNumber = (short)number;

    IDisposable disposableStream = stream;
    System.IO.FileStream fileStream = (System.IO.FileStream)stream;
}

At the IL level they are quite different:
ldarg.0
 conv.i8
 stloc.0

ldarg.0
 conv.i2
 stloc.1

ldarg.1
 stloc.2

ldarg.1
 castclass [mscorlib]System.IO.FileStream
 stloc.3

As for the logical level, there are some important differences. What's most important to remember is that coercion creates a new value, while casting does not. The identity of the original value and the value after casting are the same, while the identity of a coerced value differs from the original value; coersion creates a new, distinct instance, while casting does not. A corollary is that the result of casting and the original will always be equivalent (both in identity and equality), but a coerced value may or may not be equal to the original, and never shares the original identity.
It's easy to see the implications of coercion in the examples above, as the numeric types are always copied by value. Things get a bit trickier when you're working with reference types.
class Name : Tuple<string, string>
{
    public Name(string first, string last)
        : base(first, last)
    {
    }

    public static implicit operator string[](Name name)
    {
        return new string[] { name.Item1, name.Item2 };
    }
}

In the example below, one conversion is a cast, while the other is a coercion.
Tuple<string, string> tuple = name;
string[] strings = name;

After these conversions, tuple and name are equal, but strings is not equal to either of them. You could make the situation slightly better (or slightly more confusing) by implementing Equals() and operator ==() on the Name class to compare a Name and a string[]. These operators would "fix" the comparison issue, but you would still have two separate instances; any modification to strings would not be reflected in name or tuple, while changes to either one of name or tuple would be reflected in name and tuple, but not in strings.
Although the example above was meant to illustrate some differences between casting and coercion, it also serves as a great example of why you should be extremely cautious about using conversion operators with reference types in C#.


text:
Q: Issues with new installation of joomla 2.5 that connects to old database I want to connect our new installation of Joomla 2.5 to our old database in order to salvage content.  I'm cleaning up someone else's errors without having full nothing of what that person actually did to cause the problems.
Bottom line, our site went down because of an error in judgement by that new webmaster and instead of him restoring the site he built a new site in Wix and forgot about the old content. That was in July.
The database is still there.  So, after the new installation of Joomla 2.5,  I edited the configuration.php to point to the old database and now I can see lots more content on the admin backend but the frontend is all messed up...and the backend is not fully in tact either, despite the fact that I can see more stuff.
I'm not a trained coder.  I can make changes to coding with good instructions.  I'd like to know if anyone can help me.
On the back end, I'm getting this error when I click on an article to edit it...

Parse error: syntax error, unexpected $end, expecting T_STRING or T_VARIABLE or '{' or '$' in /home/content/08/9859108/html/libraries/joomla/application/component/controllerform.php on line 341

On the front end at  new.district79.org It shows these error messages.

Warning: Invalid argument supplied for foreach() in /home/content/08/9859108/html/components/com_content/models/articles.php on line 497
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/content/08/9859108/html/libraries/joomla/database/database/mysql.php on line 293

Thanks so much. Apologies if this is not appropriate for this forum/community.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using mysqli_change_user, or not? I am setting up a database class in my php application, and I was planning on using either PDO or MySQLi.
I was thinking of persistant connections, but I am wondering if this is the best idea. I saw, unlike PDO, MySQLi automaticly resets the state of the connection with mysqli_change_user().
However, as noted in the PHP manual, it states that the mysqli_change_user() function is expensive and could degrade performance, but that you can also disable it.
I currently have two questions:

*

*Are persistant connections a good idea? And if so, with PDO or MySQLi?

*Is the mysqli_change_user() function so expensive that it nullifies the performance increase of using a persistant connection? If so, is it such a bad idea to disable it, if you have written proper code?

A:
Are persistant connections a good idea?

Nope, as a rule, it's not. Especially given with mysqli_change_user() its benefits become close to nil.

And if so, with PDO or MySQLi?

Given only mysqli changes the user, it's is the only choice.

Is the mysqli_change_user() function so expensive that it nullifies the performance increase of using a persistant connection?

Yes, it is

If so, is it such a bad idea to disable it, if you have written proper code?

Yes, it's bad. It's not about a proper code but about fatal errors. A single script that fatally crashed and didn't release a lock or commit a transaction may wreak a havoc. That's why, exactly, mysqli_change_user() was came to be.
In all, I wouldn't bother with persistent connections at all

A: Persistent connections is generally known to actually have an adverse effect to performance. We've had a lot of trouble with it on high traffic sites.


text:
Q: Verify Username and Password onclick in Visual Studio Using a username and password text boxes, I am trying to verify that the username and password are within a table on click. Below is what I have for the button. If possible could some one review this and tell me where I am going wrong? I am new to this and could really use some advice.
Thank you for your help, It is greatly appreciated!
Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub butSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butSubmit.Click

        Dim myReader As Data.SqlClient.SqlDataReader
        Dim mySqlConnection As Data.SqlClient.SqlConnection
        Dim mySqlCommand As Data.SqlClient.SqlCommand
        'Establish the SqlConnection by using the configuration manager to get the connection string in our web.config file.

        mySqlConnection = New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ToString())
        Dim sql As String = "SELECT password FROM MyUsers WHERE username = '" & Me.logon_id.Text & "'"
        mySqlCommand = New Data.SqlClient.SqlCommand(sql, mySqlConnection)

        Try

            mySqlConnection.Open()
            myReader = mySqlCommand.ExecuteReader()

            If (myReader.HasRows) Then
                myReader.Read()
                Dim password As String = myReader("password")
                If (password = Me.user_password.Text) Then
                    'Open page with users and roles
                    Dim message As String = "Correct password"
                    Dim style As MsgBoxStyle = MsgBoxStyle.OkOnly
                    Dim title As String = "Authenticated"
                    MsgBox(message, style, title)

                End If
            End If

        Catch ex As Exception
            Console.WriteLine(ex.ToString())
        Finally
            If Not (myReader Is Nothing) Then
                myReader.Close()
            End If

            If (mySqlConnection.State = Data.ConnectionState.Open) Then
                mySqlConnection.Close()
            End If

        End Try

    End Sub
End Class

==============================================================
Update:
Thank you for your post. Thank you for your advice about creating a hash of the password. It does make sense, but this is a beginner project and I don't think that was part of the requirements.
The full project is to create three tables: MyUsers, MyRole & UserRoles. The UserRole table is suppose to link a user to multiple roles. The first column will contain a reference to a user. The second column will contain a link to a role.
I am suppose to create 2 webpages. One with a table that includes all the information about the User and there roles and a second that has a username and password that is suppose to connect to the table and verify that the entered information matches whats in the table.
Below is my SQL code:
user_description VARCHAR(100) NOT NULL,

user_password VARCHAR(50) NOT NULL,
);

INSERT INTO MyUsers (user_logon_id, user_full_name, user_description, user_password) VALUES
('mcoby', 'Mary Coby', 'Class Instructor', 'password');

CREATE TABLE MyRole
(
myrole_id INT IDENTITY(1,1)PRIMARY KEY,

role_name VARCHAR(50) NOT NULL,

role_description VARCHAR(100) NOT NULL,
);

INSERT INTO MyRole (role_name, role_description) VALUES ('administrator', ' Administrator of the web site');

INSERT INTO MyRole (role_name, role_description) VALUES ('user', ' User of the web site');

CREATE TABLE UserRoles
 (
    user_id int FOREIGN KEY REFERENCES MyUsers(id),

    role_id int FOREIGN KEY REFERENCES MyRole(myrole_id),
 );

A: Do not send/receive the clear password text from/to your database.
You should create an hash of the password and store that. When you need to check the password you reapply the hash function and checks against the database.
Also the string concatenation used in the command text it is a very bad practice. You should use Always a parameterized query to avoid sql injections and parsing problems with strings containing single quotes or decimals and dates not recognized by the database
Finally, the connection, the command, the datareader are all disposable objects and thus it is better to use the using statement
This is just an example, not tested
    Dim sql As String = "SELECT password FROM MyUsers WHERE username = @uname"
    Using mySqlConnection = New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ToString())
    Using mySqlCommand = New Data.SqlClient.SqlCommand(sql, mySqlConnection)
        mySqlConnection.Open()
        mySqlCommand.Parameters.AddWithValue("@uname", Me.logon_id.Text)
        result = mySqlCommand.ExecuteScalar()
        if result Is Nothing Then
            ' User not found
        Else
            Dim pwHash = GetHashedText(Me.user_password.Text)
            if result.ToString = pwHash Then
                'Open page with users and roles
                Dim message As String = "Correct password"
                Dim style As MsgBoxStyle = MsgBoxStyle.OkOnly
                Dim title As String = "Authenticated"
                MsgBox(message, style, title)
            Else
                ' wrong Password
            End If
        End If
    End Using
    End Using
End Sub

Private Function GetHashedText(ByVal clearText As String) As String
     Dim e As New UnicodeEncoding()
     Dim sourceBytes() As Byte = e.GetBytes(clearText)
     Dim md5 As New MD5CryptoServiceProvider()
     Dim hashedBytes() As Byte = md5.ComputeHash(sourceBytes)
     Return Convert.ToBase64String(hashedBytes)
End Function

As you can see I have removed the SqlDataReader because I suppose that you have only one user with the username provided, and so the query returns just one row (or zero) and just the password column.
Then the password typed by the user is hashed and then checked against the hashing returned by the database. No clear password text is going along the wire and in the database side the password is crypted in such a way that neither the administrator of the remote machine could recover the original text.


text:
Q: Can't show an outlet in Remix v2 Route File Naming conventions So I have this tree
routes/project.jsx
routes/project.$projectId.jsx
routes/project.$projectId.register.jsx

then
project.jsx
import { Outlet } from "@remix-run/react";

export default function Project() {
  return (
    <>

project

      <Outlet />
    </>
  );
}

projectId.jsx
import { Outlet } from "@remix-run/react";

export default function Project() {
  return (
    <>

projectId

      <Outlet />
    </>
  );
}

register.jsx
export default function Register() {
  return (

register

  );
}

if I go to http://localhost:3000/project/any-id-would-suit/register
I expect to see on my html page
project
projectId
register

but I only see
register

did I make a mistake ? sure. which one ?
[EDIT]
remix.config.js
module.exports = {
  future: {
    v2_meta: true,
    v2_routeConvention: true,
  },
  devServerPort: 8002,
};

A: I was in 1.10.1.
Juste upgrade to the minimum compatible version 1.11.1 and it's working.


text:
Q: Elasticsearch sort exact matches and fuzzy matches in different sets This is my first ever question here so I apologize if I make any mistakes.
I'm trying to make a fuzzy search (match query with fuzziness parameter) on my index that will return the results in Alphabetical order. But I need the exact matches to come first(Alphabetically ordered among themselves) and fuzzy matches later.
I have tried this to make exact matches have higher scores. But they are just being sorted by their scores:
   "query":{
      "bool":{
         "must":[
            {
               "match":{
                  "myPropertyName":{
                     "query":"myWord",
                     "fuzziness":"AUTO"
                  }
               }
            }
         ],
         "should":[
            {
               "match":{
                  "myPropertyName":{
                     "query":"myWord",
                     "boost":20
                  }
               }
            }
         ]
      }
   },
   "sort":[
      "_score",
      {
         "myProperty.keyword":{
            "order":"asc"
         }
      }
   ],
   "track_scores":true
}

Then I have tried to make the scores of all exact matches and fuzzy matches same among themselves with many methods. I can make it for fuzzy matches by using filter or constant_score but I couldn't figure a way to assign a custom score to the results of should query in my search.
How can I achieve this?

A: I've managed to achieve this by using a function score query with "boost_mode": "replace" and setting a custom value to weight parameter like: "weight": "10".
{
   "query":{
      "function_score":{
         "query":{
            "bool":{
               "filter":[
                  {
                     "match":{
                        "myPropertyName":{
                           "query":"myWord",
                           "fuzziness":"AUTO"
                        }
                     }
                  }
               ]
            }
         },
         "boost_mode":"replace",
         "functions":[
            {
               "filter":{
                  "match":{
                     "myPropertyName":{
                        "query":"myWord"
                     }
                  }
               },
               "weight":"10"
            }
         ]
      }
   },
   "sort":[
      "_score",
      {
         "myProperty.keyword":{
            "order":"asc"
         }
      }
   ],
   "track_scores":true
}

This way documents that match the match query will return with 0 score since it's also a filter query. Then among these documents the ones that match the function will return with 10 score since "boost_mode": "replace" and "weight: "10".
When it comes to sorting firstly Elasticsearch will sort the results by their score's since it comes first in "sort[]" array. Then documents with same scores will be sorted alphabetically among themselves.
This worked perfectly for me.


text:
Q: Pass hostname as argument into Fabric task I'm trying to put together a fabric script that creates a virtual instance via an API and then runs puppet on that instance. I've got a task that creates the VM, and a task that can 'bootstrap' the VM. However, I'm having difficulty linking these together, because I'm not sure how to pass the some data generated in the first task into the second task as the hostname. E.g.
def createVM():
    newhostname = local('/usr/bin/createVM')
    bootstrap(newhostname)

def bootstrap(hostname):
    env.hosts = [hostname]
    run('puppet agent -t')

This doesn't appear to work, and I get prompted for the hostname to run the fabric script on, if I just execute fab createVM.
What's the best way of doing this?

A: You can have a look at the execute() function. You can use it to override on which hosts you run a task and pass extra arguments.
You probably need something along the lines of
def createVM():
    newhostname = local('/usr/bin/createVM')
    execute(bootstrap, hosts=[newhostname])

def bootstrap():
    run('puppet agent -t')

A: You may want to set it on the environment dictionary (env), e.g:
env.newhostname = local('/usr/bin/createVM')

Or just set env.hosts:
env.hosts = [local('/usr/bin/createVM')]

Then execute fab createVM bootstrap
You can see more details here:
http://docs.fabfile.org/en/1.10/usage/env.html


text:
Q: multiple connectors in kafka to different topics are going to same node I have created two kafka connectors in kafka-connect which use the same Connector class but have different topics they listen to.
When I launch the process on my node, both the connectors end up creating tasks on this process. However, I would like one node to only handle one connector/topic. How can I limit a topic/connector to a single node? I don't see any configuration in connect-distributed.properties where a process could specify which connector to use.
Thanks

A: Kafka Connect in distributed mode can run as a cluster of one or more workers. Each worker can run multiple tasks. Depending on how many connectors and workers you are running, you will have tasks running on the same worker. This is deliberate - the idea is that Kafka Connect will manage your tasks and workload for you, across the available workers.
If you want to isolate your processing you can run Kafka Connect as separate Connect clusters, either on the same machine (make sure to use different REST ports), or separate machines.
For more info, see architecture and config for steps to configure separate clusters. Note that a cluster can actually be a single worker, but then you don't have any redundancy in the event of failure.


text:
Q: RKHS Analog for Non-symmetric Kernel I'm looking for any theoretical work/paper/development where the notion of Reproducing kernel Hilbert space (RKHS), defined via positive definite symmetric kernel $k(x,y) = k(y,x)$, is extended towards non-symmetrical kernels.
Basically, I'm looking for a similar notion to kernel learning/regression, which is where RKHS is mainly used, but that is based on non-symmetric similarity function $k(x,y) \neq k(y,x)$. Does such mathematical structure exist? Can anyone share a link for any relevant material?
Thanks

A: RKHS have been generalized to Reproducing Kernel Banach spaces (RKBS). In RKBS the inner product is replaced by a semi-inner product which is not necessarly symmetric anymore or more recently by Bilinearform on a pair of Banach spaces:
Definition Reproducing Kernels for RKBS (Lin et al, 2019, On Reproducing Kernel Banach Spaces: Generic Definitions and Unified Framework of Constructions, p. 3):
Let $B_1$ be an RKBS on a set $Ω_1$. If there exists a Banach space $B_2$ of functions on another set $Ω_2$, a continuous bilinear form $\langle ·, ·\rangle_{B1×B2}$, and a function K on $Ω_1 \times Ω_2$ such that K(x, ·) ∈ $B_2$ for all x ∈ $Ω_1$ and $f(x) = \langle f, K(x, ·)\rangle_{B_1×B_2}$ for all x ∈ $Ω_1$ and all f ∈ $B_1$, then we call K a reproducing kernel for $B_1$.
If, in addition, $B_2$ is also an RKBS on $Ω_2$ and it holds K(·, y) ∈ B1 for all y ∈ $Ω_2$ and g(y) = $\langle K(·,y), g\rangle_{B_1×B_2}$ for all y ∈ $Ω_2$ and all g ∈ $B_2$, then we call $B_2$ an adjoint RKBS of $B_1$ and call $B_1$ and $B_2$ a pair of RKBSs.
In this case, $\tilde{K}(x, y) := K(y, x)$, x ∈ $Ω_2$, y ∈ $Ω_1$, is a reproducing kernel for $B_2$.
The construction with a semi inner product has been applied to machine learning (see Zhang et al, Reproducing Kernel Banach Spaces for Machine Learning). There exist also constructions of this kind where the representer theorem can be applied: G. Song, H. Zhang, and F. J. Hickernell, Reproducing kernel Banach spaces with the ℓ1 norm.


text:
Q: OR operators and Ruby where clause Probably really easy but im having trouble finding documentation online about this
I have two activerecord queries in Ruby that i want to join together via an OR operator
@pro = Project.where(:manager_user_id => current_user.id )
@proa = Project.where(:account_manager => current_user.id)

im new to ruby but tried this myself using ||
@pro = Project.where(:manager_user_id => current_user.id || :account_manager => current_user.id)

this didnt work, So 1. id like to know how to actually do this in Ruby and 2. if that person can also give me a heads up on the boolean syntax in a ruby statement like this altogether.
e.g. AND,OR,XOR...

A: You should take a look at the API documentation and follow conventions, too. In this case for the code that you might send to the where method.
This should work:
@projects = Project.where("manager_user_id = '#{current_user.id}' or account_manager_id = '#{current_user.id}'")

This should be safe since I'm assuming current_user's id value comes from your own app and not from an external source such as form submissions. If you are using form submitted data that you intent to use in your queries you should use placeholders so that Rails creates properly escaped SQL.
# with placeholders
@projects = Project.where(["manager_user_id = ? or account_manager_id = ?", some_value_from_form1, some_value_from_form_2])

When you pass multiple parameters to the where method (the example with placeholders), the first parameter will be treated by Rails as a template for the SQL. The remaining elements in the array will be replaced at runtime by the number of placeholders (?) you use in the first element, which is the template.

A: You can't use the Hash syntax in this case.
Project.where("manager_user_id = ? OR account_manager = ?", current_user.id, current_user.id)

A: Metawhere can do OR operations, plus a lot of other nifty things.


text:
Q: How to allow only process page to work if it was accessed from form? On the form page I am using:
<input type="hidden" value="3490" name="test">

Then on the process page i am doing this to check:
<?php
if (isset($_POST['test']) ) {
    echo "error";
}
?>

For some reason it doesn't work.  When i go to process page the page is printing no errors.

A: I think what you want is to reverse the boolean result of isset() to detect if it's empty:
<?php
if (!isset($_POST['test']) ) {
    echo "error";
}
?>

http://codepad.org/ClJ9vDIv
Note the !, which in this case turns the false outcome (no/false, it isn't set) into a true outcome (yes/true, it isn't set).


text:
Q: Import all projects from gitlab 11 to gitlab 14 I've just created a brand new instance of Gitlab v.14.
I need to import all my projects (more than 100) from the old gitlab 11 to the new gitlab 14.
Do you have any suggestion or experience?

A: GitLab 14.x cannot import projects exported by GitLab 11.x (see version compatibility requirements.) Though you don't necessarily need to export your projects to import them to GitLab (as I'll suggest below).
Ideally, you should follow the upgrade path then migrate the two instances as a whole.
But if you must do this by creating a new GitLab instance without being on the same version, there might be a few ways to do this.
Group import
If you upgrade your original GitLab instance to at least version 13.7, you can use the group migration tool.
Project imports
If you can't upgrade your original instance, the easier way to import your projects is to have both instances running and import projects by URL. You don't need to export each project first.
Import automation
If you have GitLab Premium or Ultimate, you can use import automation.

A: Regarding projects, GitLab 15.0 (May 2022) allows for a more complete import

Migration support for project releases milestones
We continue to add support for more release metadata to GitLab migration.
In GitLab 15.0, we've added project releases milestone.
This metadata will help you migrate more of the release data without needing to manually copy over missing release attributes.
See Documentation and Issue.

That will apply to your next migration (from your current instance to a new GitLab 15 one).

GitLab 15.8 (January 2023) further improves the process:

Migrating GitLab projects by direct transfer Beta
Now, you can migrate group and project resources together when using direct transfer.
You can use direct transfers to migrate between GitLab instances or
within the same GitLab instance.
Migrating projects when migrating groups using direct transfer is a major
improvement from migrating groups and projects using file exports because:

*

*You don't need to manually export each project to a file and then import all those export files to a new location.
Now all projects
within a top-level group are migrated automatically, making your work more efficient.

*When migrating from self-managed GitLab to GitLab.com, user associations (such as comment author) are not changed to the user who is importing the projects.
Migration using direct transfer maps users and their contributions correctly, provided a few conditions are met.

This feature is available on GitLab.com. You can migrate from a self-managed GitLab to GitLab.com right now!
To enable it on GitLab self-managed instances, see the linked documentation.
Learn more about migrating GitLab projects by direct transfer Beta and what's coming next in our recent blog post.

See Documentation and Epic.


text:
Q: How to align the checkbox and label in same line in html? Within li tags, I am placing a checkbox and label input.
If label text is larger than label, the text goes to the next line.
I wrapped the label text but it's not aligning the checkbox and label in the same line if label text is too long.

    <input id="checkid" type="checkbox" value="test" />
    testdata

Thanks,

A: None of these suggestions above worked for me as-is.  I had to use the following to center a checkbox with the label text displayed to the right of the box:

<input type="checkbox" id="checkbox1" name="checked" value="yes" class="checkboxes"/>
Check the box.

A: I had the same problem, but non of the asweres worked for me.
I am using bootstap and the following css code helped me:
label {
 display: contents!important;
}

A: Wrap the checkbox with the label and check this
HTML:

        <input id="checkid"  type="checkbox" value="test" />testdata

CSS:
[type="checkbox"]
{
    vertical-align:middle;
}

http://jsfiddle.net/pKD9K/1/

A: Another approach here:
.checkbox-wrapper {
  white-space: nowrap
}
.checkbox {
  vertical-align: top;
  display:inline-block
}
.checkbox-label {
  white-space: normal
  display:inline-block
}

  <input type="checkbox" id="terms" class="checkbox">
  I accept whatever you want!

A: You should use  for the checkboxes or radios, and to align checkboxes vertical-align is enough
Try changing your markup to this

    <input id="checkid" type="checkbox" value="test" />
    testdata

    <input id="checkid2" type="checkbox" value="test" />
    testdata 2

And set CSS like
input[type="checkbox"]
{
    vertical-align:middle;
}

In case of long text
label,input{
    display: inline-block;
    vertical-align: middle;
}

Side note: In label, value of for must be  the id of checkbox.
Fiddle
Updated Fiddle

A: Use below css to align Label with Checkbox
    .chkbox label
            {
                position: relative;
                top: -2px;
            }

<asp:CheckBox ID="Ckbox" runat="server" Text="Check Box Alignment"/>

A: If you are using bootstrap wrap your label and input with a div of a "checkbox" or "checkbox-inline" class.

        <input type="checkbox" value="">Option 1

Reference:
https://www.w3schools.com/bootstrap/bootstrap_forms_inputs.asp

A: Please try it

<input id="checkid" type="checkbox" value="test">
testdata

li input {float: left;}
li label {word-wrap: break-word; line-height: 16px; float: left;}

A: Just place a div around the input and label...

        <input id="checkid"  type="checkbox" value="test" />

        testdata

A: If you are using bootstrap then use this class in the holding div
radio-inline

Example:
Active

    <input type="checkbox" name="active" value="1">

Here the label Active and the checkbox will appear to be aligned.

A: This worked for me
CSS
input[type="checkbox"] {
    display: inline-block;
    width: auto;
  }

HTML

    <input type="checkbox">
    test data

A: This code worked for me

[type="checkbox"] { vertical-align: middle; word-wrap: break-word;margin-left:1% }

But I had to add margin-left:1% to ensure the checkbox aligns with my other form controls.

A: Use this in your li style.
style="text-align-last: left;"


text:
Q: Formulas won't calculate automatically I have a big sheet with a lot of formulas that have a dependency hierarchy between them. It starts with a cell with a date value. Then, cell x:y (and others), has formula depending on this date. Then cell w:z (and others) has a formula depending on cell x:y. And so on...
This main cell with a date value is filled using apache poi.
And now my problem: when I open the generated excel file, the date is there, but none of the formulas are calculated. They all have the error "A value used in the formula is of the wrong data type". It seems that when the formula try to evaluate it self the date isn't there yet.
Solutions:
1) If I click in the cell, and just press ENTER, the formula is correctly evaluated. But then I would have to do this for all cells.
2) I click in the date cell, copy it, and then paste it in the same place, and all formulas in the sheet are evaluated!
3) I could iterate in all cells in my application, evaluating each one with evaluateFormulaCell method from FormulaEvaluator class. But I have a lot of formulas and the performance of this is terrible.
Does someone have a solution for this?
Thanks!!

A: Your date value isnt recognized by the excel formulas as a date, what you could do is have another cell dat will first take the datevalue DATEVALUE() of the cell filled using Apache poi.
Then direct your first level formulas to that cell instead of the one filled using Apache poi

A: Because Excel don't calculale automatically, so just change this.
Excel 2010: File -> Options -> Formulas: Find Workbook calculation, and change to Automatically.
It worked for me.

A: To solve this, I changed all formulas in my template, to use instead of the regular formula sintax (=SUM(A:D)) the following sintax:
$[SUM(A:D)]
http://jxls.sourceforge.net/reference/formulas.html


text:
Q: Mapping bad JSON RestKit I developing some app with HTTP requests. All responses from server was great. And easy to mapping. But the last one is very bad.
 "positions": {
                   "google": {
                              "some not mutable key1": 3,
                              "some not mutable key2": 12,
                              "some not mutable key3": 5,
                              "some not mutable key4": 7
                              }
                  }
     }

I need to mapping this response in the NSArray or NSDictionary to work with them, but I can't write something like this:
    NSDictionary *mappingDictionary = @{

                                    @"attrs.positions.google" : @"googleArray"

                                    };

    RKObjectMapping *taskMapping = [RKObjectMapping mappingForClass:[SMPosition class]];
    [taskMapping addAttributeMappingsFromDictionary:mappingDictionary];


text:
Q: JAXB Unmarshall without annotation I am trying to unmarshall a marshalled object which didn't had annotations in it.
This is my object class.
class Student {
    private String name;
    private int age;

    public Student() {
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

This is what I used to marshall the object.
public String marshall(Student student){
        StringWriter writer = new StringWriter();
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(Student.class);
            Marshaller m = context.createMarshaller();

            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            JAXBElement<Student> rootElement = new JAXBElement<Student>(new QName("student"), Student.class, student);
            m.marshal(rootElement, writer);
            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

This is what I used to unmarshall the object.
public Student unMarshall(String input){
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(Student.class);
            Unmarshaller m = context.createUnmarshaller();
            return (Student) m.unmarshal(new StringReader(input));
        } catch (JAXBException e) {
            e.printStackTrace();
            return null;
        }
    }

When I try to unmarshall, I get the bellow error
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"student"). Expected elements are (none)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:648)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:236)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:231)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:105)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1051)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:484)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:465)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:135)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:400)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:626)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3104)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:921)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:647)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:200)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:173)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:194)
    at noannotation.Main.unMarshel(Main.java:49)
    at noannotation.Main.main(Main.java:22)

How can I resolve this error?

A: You just need to use one of the unmarshal methods that take a Class parameter.
public Student unMarshall(String input){
    JAXBContext context;
    try {
        context = JAXBContext.newInstance(Student.class);
        Unmarshaller m = context.createUnmarshaller();
        StreamSource source = new StreamSource(new StringReader(input))
        return m.unmarshal(source, Student.class).getValue();
    } catch (JAXBException e) {
        e.printStackTrace();
        return null;
    }
}

For More Information
You can find out more information about this use case in my blog:

*

*http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html


text:
Q: Flyway DB migration - how to access application services (Spring configured) Main question - this may seem like a basic flyway question and I might have (somehow) missed this during my research but - is it possible to access an applications services (spring configured) when attempting to migrate data using flyway? Few details below -
Additional details -

*

*I know we cannot inject spring data services etc. (learnt from this
SO question). And I understand this from a data access point of
view.

*But can we not use (by injection) any other application services
either while using flyway (I searched for examples - but without
luck, and no  details given on flyway documentation either)

*Let us say we cannot use any Spring services (and I find some way to
work around that), can we access properties declared in
application.properties / .yml (this does not appear possible either).

Putting the above in context of our requirement - we have added a couple of new fields to few tables and as part of the release we want to populate those columns with data. This requires us (or flyway) to execute the following algorithm -

*

*Get data from first table.

*Using some of the data from each row, lookup more data with an API
call.

*The URL of the API is environment specific (hence the third point
above).

*Update the data returned from the API into the newly added columns.

*Repeat steps above for next table.

P.S. - I know, adding columns that depend on other columns in the same table is not in accordance with 3rd normal etc. but for reasons outside this post, it is required.
Tech Stack -

*

*Spring boot 1.3.x

*Flyway 4.0.3

*Using Java migration

Few examples I tried as below -
My flyway migration class is as below.
public class R__MigrationYeah implements SpringJdbcMigration {

  @Value("${mypath.subpath}") // this does not work !
  private String someStringIwannaUse;

  @Inject // this does not work either (even with Autowired or Const. injection)!
  private MyService myService;

}

I have seen some posts / blogs that have complicated details on how to configure flyways MigrationResolver or ConfigurationAware etc. - and not sure if they solve this problem (even if they do - it is a LOT of work just to write a quick migration script - is this the only way?).
Finally - I know I'm missing something because if we have to write flyway Java code without being able to use ANY existing application classes thru Spring, then it is no different than writing an independent migration project (therefore no value added by flyway other than making a DB connection available) - I'm sure this cannot be the case.
Any help would be great on this !

A: It is not possible to use dependency injection in a flyway migration.
The next version from flyway will support dependency injection from spring beans. See the Github issue for more details. On Stack Overflow is a workaround for the current version available.

A: I think you want to use flyway more dynamically than it's designed for.
Basically it's just for DB-Schema, you can do anything sql can do, but since
it does it job in a repeatable, reliable, step-by-step way you wouldn't want
any real business data in it. Flyway uses static scripts you provide, you
can't have them dynamically change over time (it would protest by checksum not matching) or with "API-Calls".

A: For that kind of stuff you can create your own Spring Boot app and use Flyway through it's Java API. Something along this lines.
@SpringBootApplication
@Import(ServiceConfig.class)
public class FlyWayApp implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(FlyWayApp.class, args);
    }

    @Value("${mypath.subpath}")
    private String someStringIwannaUse;

    @Autowired
    private MyService myService;

    @Override
    public void run(String... args) throws Exception {
        // Create the Flyway instance
        Flyway flyway = new Flyway();

        // Point it to the database
        flyway.setDataSource("jdbc:h2:file:./target/foobar", "sa", null);

        //Fetch data and create migration scripts needed by Flyway
        myService.createMigrationScripts();

        // Start the migration
        flyway.migrate();
    }
}


text:
Q: Delete all files in a directory on remote server How would I delete all files in a directory on a remote server?  I have very limited python experience. I assume first i need to connect to the other machine? When running this below i get an error stating.
paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 'Host IP'
import paramiko

command = "df"

#declare credentials
host = 'host'
username = 'username'
password = 'password'

client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password)
_stdin, _stdout,_stderr = client.exec_command("df")
print(_stdout.read().decode())
client.close()


text:
Q: How to prevent JQuery method .html() from changing case? I am creating a website, on which I also want to display some Java Code. I am using an AJAX request to get HTML content from the server. Then the content is inserted in a specifiv div element with the id content.
To insert the HTML content, which also contains the Java Code, I am using JQuery's .html(htmlString) method. However, the Java-Code is changed like this:
When there is a usage of generics in Java, JQuery thinks it's a tag! For whatever reason, the .html method suddenly changes all text in between < and > to lower case letters.
How do I avoid this behavior? Is there any parameter I can set to stop it from doing that? It shouldn't even do that, because first of all it's unexpected and second it doesn't matter if the characters are lower or upper case, browsers will still understand, probably because they are lower casing them themselves at some point internally.
EDIT#1:
.empty() and then .append() results in the same behavior.
EDIT#2:
There is the problem, that I do not only have Java code inside the result of the AJAX response, but also true HTML content, which would get escaped as well, if I use escape().
EDIT#3:
One of the comments mentioned, that maybe I should refactor the AJAX response, so that text and HTML content are separated from each other. This sounds like a good idea in general and maybe I'll go with that.
I wonder however, if there is any method to set HTML content, which doesn't make the content go though unwanted changes.

A: You can just use jQuery's .text().

A: Before using .html(htmlString) method, replace < and > with < and >.
Hope this helps you.
Thanks
Anurag

A: You need to escape the string using the escape() function. So
.html(escape(javaBlock));

A: You need to call escape() on the htmlString, specifically .html(escape(htmlString)). See MDN for more details.
You can also use jQuery's .text() method, which will do this for you automatically, such as .text(htmlString).

A: you can use the createTextNode()function which will escape the special chars for you:
So this will do what you want:
escapedText = document.createTextNode(yourJavaCodeSnippetText)
$("#yourElementId").html(escapedText)

A: Javascript doesn't have an HTML entity conversion function, but you can roll your own. Example:
if(typeof escapeHtmlEntities == 'undefined') {
        escapeHtmlEntities = function (text) {
            return text.replace(/[\u00A0-\u2666<>\&]/g, function(c) {
                return '&' +
                (escapeHtmlEntities.entityTable[c.charCodeAt(0)] || '#'+c.charCodeAt(0)) + ';';
            });
        };

        // all HTML4 entities as defined here: http://www.w3.org/TR/html4/sgml/entities.html
        escapeHtmlEntities.entityTable = {
            34 : 'quot',
            38 : 'amp',
            39 : 'apos',
            60 : 'lt',
            62 : 'gt',
        };
}

Then call
.html(escapeHtmlEntities(javaBlock));


text:
Q: How to set up SCSS in WebStorm I am trying to work with SCSS and compile it as CSS in WebStorm, so I set a file watcher for that but unfortunate I got this error:
Failed to run File Watcher 'SCSS'.
            The watcher has been disabled.
            Error: Invalid executable

So I google it and I found out that there as some steps that needs to be done first like in this link but I can't find this path :
In the Program field, specify the path to the compiler archive depending on the chosen predefined template.

lessc for Less.
sass for Sass/SCSS.
If you followed the standard installation procedure with npm, JetBrains Rider locates the required files itself and fills in the field automatically. Otherwise, type the path manually or click the Browse button and choose the file location in the dialog that opens.

I don't know if this even would solve my problem or not.


text:
Q: Hidden syntax errors in MYSQL procedure I'm new to MYSQL and this is my first time creating a procedure so bear with me. I'm trying to loop through information_scheme.tables and populate a new table with info taken from some of the tables found there. I cannot save the procedure in workbench because of 'syntax errors'. I cannot figure out what those errors are however.

CREATE PROCEDURE `populate` ()
BEGIN
DECLARE thisDay varchar(100);
DECLARE i int;
DECLARE n int;
DECLARE cur CURSOR FOR SELECT table_name FROM (information_schema.tables);
SET i=0;
SELECT COUNT(table_name) FROM information_schema.tables INTO n;
OPEN cur;
    getDay: LOOP
     IF cur LIKE 'transactions_20%' THEN
     FETCH cur INTO thisDay;

     INSERT INTO days_totals
     (date,num_of_ppl,punches,admission_total,pass_total,misc_total,food_total,drink_total,grand_total)
     VALUES(
     (SELECT SUBSTRING(thisDay,14,23)),
     (SELECT COUNT(amount) FROM thisDay WHERE name = 'adult admission' OR name = 'punch a pass' OR name = 'child admission'),
     (SELECT COUNT(amount) FROM thisDay WHERE name = 'punch a pass'),
     (SELECT SUM(total) FROM thisDay WHERE name = 'adult admission' OR name = 'child admission'),
     (SELECT SUM(total) FROM thisDay WHERE name = 'ten visit pass'),
     (SELECT SUM(total) FROM thisDay WHERE type = 'misc' AND name != 'adult admission' AND name != 'child admission' AND name != 'ten visit pass'),
     (SELECT SUM(total) FROM thisDay WHERE type = 'food'),
     (SELECT SUM(total) FROM thisDay WHERE type = 'drink'),
     (SELECT SUM(total) FROM thisDay WHERE type = 'misc' OR type = 'food' OR type = 'drink')
     );
     SET i = i + 1;
     ELSE IF
        i < n AND cur NOT LIKE 'transactions_20%' THEN SET i = i + 1;
     ELSE
     LEAVE getDay;

     END IF;
     END LOOP getDay;
     CLOSE cur;
END

A: There are numerous problems with your procedure code.

*

*You need to set the DELIMITER, even when using MySQL Workbench. See https://dev.mysql.com/doc/refman/8.0/en/stored-programs-defining.html

*You can't use a variable in place of the table name. To make the table name dynamic, you must format the table name into an SQL query string, and then use PREPARE. See https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html

*You are comparing the cursor to a string, but you should compare the value fetched by the cursor.

*You don't need a condition anyway, because you should just use a WHERE clause in your query against information_schema.tables.

*Your cursor has no way of continuing. You don't declare a continue handler, and you just LEAVE the loop during the first iteration. Read examples more carefully: https://dev.mysql.com/doc/refman/8.0/en/cursors.html

*Your i and n variables appear to have no purpose. You count up, but the value you count is not used.

I made the following version and tested it on MySQL 8.0. I used MySQL Workbench to create the procedure.
DELIMITER $$
CREATE PROCEDURE test.`populate`()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE thisDay varchar(100);
  DECLARE cur CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_name LIKE 'transactions_20%';
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cur;

  getDay: LOOP
     FETCH cur INTO thisDay;
     IF done THEN
       LEAVE getDay;
     END IF;

     SET @sql = CONCAT(
       'SELECT
         COUNT(CASE WHEN name IN (''adult admission'', ''punch a pass'', ''child admission'') THEN amount END),
         COUNT(CASE WHEN name IN (''punch a pass'') THEN amount END),
         SUM(CASE WHEN name IN (''adult admission'', ''child admission'') THEN total END),
         SUM(CASE WHEN name IN (''ten visit pass'') THEN total END),
         SUM(CASE WHEN name IN (''ten visit pass'') THEN total END),
         SUM(CASE WHEN type = ''misc'' AND name NOT IN (''adult admission'', ''child admission'', ''ten visit pass'') THEN total END),
         SUM(CASE WHEN type = ''food'' THEN total END),
         SUM(CASE WHEN type IN (''misc'', ''food'', ''drink'') THEN total END)
       FROM `', thisDay, '`
       INTO @v_num_of_ppl, @v_punches, @v_admission_total, @v_pass_total, @v_misc_total, @v_food_total, @v_drink_total, @v_grand_total'
     );

     PREPARE stmt FROM @sql;
     EXECUTE stmt;
     DEALLOCATE PREPARE stmt;

     INSERT INTO days_totals
     SET date = SUBSTRING(thisDay, 14, 23),
         num_of_ppl=COALESCE(@v_num_of_ppl, 0),
         punches=COALESCE(@v_punches, 0),
         admission_total=COALESCE(@v_admission_total, 0),
         pass_total=COALESCE(@v_pass_total, 0),
         misc_total=COALESCE(@v_misc_total, 0),
         food_total=COALESCE(@v_food_total, 0),
         drink_total=COALESCE(@v_drink_total, 0),
         grand_total=COALESCE(@v_grand_total, 0);

   END LOOP;
   CLOSE cur;
END

By using CASE expressions inside the aggregation, this collects all the subtotals in one pass of reading the transactions table.

Frankly, I would not use a stored procedure at all. This task would be easier in virtually any other application programming language. There is no advantage to using a stored procedure in this case, and it's a language you are not accustomed to.


text:
Q: Can I run the Android Emulator within (or on top of) the Android Studio window? I use Android Studio on macOS in full screen (maximised). When launching the Android Emulator, its window is shown on the regular desktop. This requires switching from one window to another. I'd like to be able to look at both windows at the same time, without leaving full screen mode in Android Studio.
Is there a way to move the Android Emulator window to within (or on top of) my Android Studio window?

A: With Android Studio 4.1 and above you can run the Android Emulator directly in Android Studio.
To run the emulator in Android Studio, make sure you're using Android Studio 4.1 with version 30.0.10 or higher of the Android Emulator, then follow these steps:

*

*Click File > Settings > Tools > Emulator (or Android Studio > Preferences > Tools > Emulator on macOS), then select Launch in a tool window and click OK.

*If the Emulator window didn't automatically appear, open it by clicking View > Tool Windows > Emulator.

*Start your virtual device using the AVD Manager or by targeting it when running your app.
For more info: Run the Android Emulator directly in Android Studio

A: This is not a 100% answer, but near to it and since it doesn't fit in comments, I'll write it here. Hopefully we can turn it into a 100% answer.
It is possible to do this with applications that supports full screen mode. Unfortunately the Android emulator does not do this. Genymotion does.
There seem to be hacks to activate full screen mode for applications that don't support it natively. For example, for the iOS simulator, you have to run this on a terminal:
defaults write com.apple.iphonesimulator AllowFullscreenMode -bool YES

A Google search returns several results to do this with the Android Emulator: https://www.google.com/search?q=how+to+run+android+emulator+full+screen&rlz=1C5CHFA_enDE822DE822&oq=how+to+run+android+emulator+full+screen&aqs=chrome..69i57.6269j0j9&sourceid=chrome&ie=UTF-8
I've not tested any of them, so that's left as an exercise to the reader. If you do successfully please write it in the comments (or directly edit this post with the steps).
It may also make sense to make a feature request on the emulator to enable full screen mode.
Once you have an emulator/simulator that supports full screen mode, you can use MacOS's split view feature. In order to do this:

*

*Press and hold the full screen button on Android Studio (while not in full screen mode).

*Move it to the left part of the screen.

*Now in the right part you will see "candidates" to share the full screen with. Your simulator/emulator should appear here. Click on it. It should expand to fill the right half of the screen.

*Drag the handle between the left and right part to the right, such that Android Studio occupies more space.

See https://support.apple.com/en-au/HT204948

A: I also looked into this and there doesn't seem to be any support for this. Perhaps you could write a plugin that somehow wraps an external window inside a panel, I don't know if the IntelliJ API supports it though.
The closest thing you got on macOS is the split-screen mode with full-screen apps.


text:
Q: how to get http request detail in laravel? I have an http client request like this?
        try {
           $request = json_encode($data);
           $result = $this->pendingRequest->{$method}('http://test.local/general/wallets/1000000', $data);
           // this is my request detail
           $request = $result->transferStats ? Message::toString($result->transferStats->getRequest()) : $request;
           $result->throw();
           $this->setLog($provider, $step, $request, $result->body(), $url, $result->status());
           return $result;
         } catch (RequestException $exception) {
          // I need to http request detail
         } catch (ConnectionException $exception) {
          // I need to http request detail
         }

I need to get my request param and headers and token and every thing that send to third party in cache exceptions. I can get detail in try via: Message::toString($result->transferStats->getRequest())

A: you can @dd($request);
on blade OR
dd($request); on controllers etc..

A: Illuminate\Http\Client\Request
headers() : array

*

*Get the request headers.

parameters() : array

*

*Get the request's form parameters.

body() : string

*

*Get the body of the request.

data() : array

*

*Get the request's data (form parameters or JSON).

A: You can take it as
$request->all();

if you want to see more regular. you can try
dd($request->all());


text:
Q: Overlap in date range grouped dataframe How can i know if two rows have overlap in their date range??
Input Dataframe:

A
B
Start
End
Timestamp

A1
B1
2022-01-15
2022-02-15
2021-05-17

A1
B1
2021-07-15
2021-10-17
2021-05-17

A1
B1
2021-07-30
2021-10-02
2021-05-16

A1
B2
2022-01-01
2023-01-01
2021-05-17

A1
B2
2021-06-02
2021-06-04
2021-05-16

A2
B3
2021-05-10
2021-05-12
2021-05-17

A2
B3
2021-04-10
2021-06-12
2021-05-16

A2
B4
2021-06-02
2021-06-04
2021-05-17

I want to know how I could identify if there is overlap between two rows of the same group (A and B). For example in rows 0, 1 and 2 they belong to the same group (A1 and B1) but there is only overlap between rows 1 and 2 since they share a part of the date range and therefore what I want is to keep the row that has the highest timestamp if there is overlap. But for example in rows 3 and 4, although they belong to the same group (A1 and B2) since there is no overlap between their dates, I want to keep both dates. How could it be done?
Expected Dataframe:

A
B
Start
End
Timestamp

A1
B1
2022-01-15
2022-02-15
2021-05-17

A1
B1
2021-07-15
2021-10-17
2021-05-17

A1
B2
2022-01-01
2023-01-01
2021-05-17

A1
B2
2021-06-02
2021-06-04
2021-05-16

A2
B3
2021-05-10
2021-05-12
2021-05-17

A2
B4
2021-06-02
2021-06-04
2021-05-17

A: You can use:

*

*Optionally convert dates to datetime if not already in datetime

df['Start'] = pd.to_datetime(df['Start'])
df['End'] = pd.to_datetime(df['End'])
df['Timestamp'] = pd.to_datetime(df['Timestamp'])

*Sort values to facilitate date comparison between consecutive rows

df = df.sort_values(['A', 'B', 'Start', 'End'])

*Set group number within the same A and B for non-overlapping date ranges:  By comparing Start date in a sorted row is larger than End date of previous row (this will be non-overlapping date range).  All group numbers are relative to within same groups of A and B.

group = (df['Start'] >  df.groupby(['A', 'B'])['End'].shift()).groupby([df['A'], df['B']]).cumsum()

*Group by A and B and overlapping group number (by newly created group) and   get the index for highest Timestamp by idxmax().  Use .loc to filter for such rows (with highest Timestamp in groups) to retain.   Finally .sort_index() to restore the sequence of original dataframe before sorting.

df.loc[df.groupby([df['A'], df['B'], group])['Timestamp'].idxmax()].sort_index()

Result:
    A   B      Start        End  Timestamp
0  A1  B1 2022-01-15 2022-02-15 2021-05-17
1  A1  B1 2021-07-15 2021-10-17 2021-05-17
3  A1  B2 2022-01-01 2023-01-01 2021-05-17
4  A1  B2 2021-06-02 2021-06-04 2021-05-16
5  A2  B3 2021-05-10 2021-05-12 2021-05-17
7  A2  B4 2021-06-02 2021-06-04 2021-05-17

A: Panda arrays will be of your help
And it goes like this... array(data[, dtype, copy])...
For more info read docs.... I am still looking for stable answer for this.
Panda docs


text:
Q: get values separated by random spaces in lines from text file in shell I have text file with about a 100 lines. Here's an example.
2.2  1.0 Flow DEV1 f06c6ba8-5201-0000-0080-a6ced6fdded7 CAPPA
0.9  2.2 Flow DEV1 7d702aa8-5201-0000-0080-dff8707d04a5 PART
0.7  1.6 Flow DEV1 f19d2aa8-5201-0000-0080-e4f1da3f1eb7 PARTREL
0.7  1.5 Flow DEV1 67cc2aa8-5201-0000-0080-e1e7bf540f80 PARTTRAIN
0.6  2.9 Flow DEV1 8bc628a8-5201-0000-0080-bbf00e3c6b25 CUSTOMER
0.6  1.6 Flow DEV1 344229a8-5201-0000-0080-ca7e456e1a13 GENERAL
0.4  2.3 Flow DEV1 1cfe2ca8-5201-0000-0080-8039b85b1161 DEALER
0.4  1.7 Flow DEV1 3f552ba8-5201-0000-0080-d17d8da987d3 LINK3
0.3  1.7 Flow DEV1 50dd2ba8-5201-0000-0080-e392a91798c5 LINKREL
0.3  1.5 Flow DEV1 c60e2ca8-5201-0000-0080-f640a9c17a0f LINKTRAIN

I am trying to get an output as
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=CAPPA,%CPU=2.2,%MEM=1.0
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=PART,%CPU=0.9,%MEM=2.2
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=PARTREL %CPU=0.7,%MEM=1.6
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=PARTTRAIN %CPU=0.7,%MEM=1.5
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=CUSTOMER %CPU=0.6,%MEM=2.9
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=GENERAL %CPU=0.6,%MEM=1.6
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=DEALER %CPU=0.4,%MEM=2.3
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=LINK3 %CPU=0.4,%MEM=1.7
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=LINKREL %CPU=0.3,%MEM=1.7
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=LINKTRAIN %CPU=0.3,%MEM=1.5

I tried using awk and cut but no luck. What am i doing wrong?
awk -v jvm="DEV1" -v hstnm="server1" -v environment="DEVL" '
  {
    gsub(/ /, "", $1)
    gsub(/ /, "", $2)
    gsub(/ /, "", $6)
    print    "was,host="                         hstnm       \
             ",environment="                     environment \
             ",jvm="                             jvm         \
             ",objecttype=process,processname="  $6          \
             " %CPU="                            $1          \
             ",%MEM="                            $2          \
  }' FIELDWIDTHS="11 7 11" < stats.txt

A: awk does the parsing for you on white space, replace hard coded values with variables if you got the main idea.
$ awk '{print "was,host=server1,environment=DEVL,jvm=" $4
              ",objecttype=process,processname=" $6 ",%CPU=" $1 ",%MEM=" $2}' file

was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=CAPPA,%CPU=2.2,%MEM=1.0
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=PART,%CPU=0.9,%MEM=2.2
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=PARTREL,%CPU=0.7,%MEM=1.6
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=PARTTRAIN,%CPU=0.7,%MEM=1.5
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=CUSTOMER,%CPU=0.6,%MEM=2.9
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=GENERAL,%CPU=0.6,%MEM=1.6
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=DEALER,%CPU=0.4,%MEM=2.3
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=LINK3,%CPU=0.4,%MEM=1.7
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=LINKREL,%CPU=0.3,%MEM=1.7
was,host=server1,environment=DEVL,jvm=DEV1,objecttype=process,processname=LINKTRAIN,%CPU=0.3,%MEM=1.5


text:
Q: Creating Graph class in C# I have a task to create Graph class in C#, that would have following properties:
private List<string> vertices;
private List<List<int>> adjacencyMatrix;
private int n;

n is the number of nodes, the rest is self explanatory I believe.
The class should also have two methods that look like this:
Add(string vertex){}
AddConnection(string vertex1, string vertex2, int value){}
So far, I figured out the Add method (assuming that 0 represents no connection between vertices):
public void Add(string vertex)
{
     this.vertices.Add(vertex);
    List<int> temp = new List<int>();
    foreach(List<int> element in this.adjacencyMatrix)
    {
        element.Add(0);
    }
    foreach(string element in vertices)
    {
        temp.Add(0);
    }
    this.adjacencyMatrix.Add(temp);

    this.n++;
}

But I still dont know how to add connection.
Any help would be appreciated

A: Okay, so despite the negative comments I managed to solve it. I know that this approach doesn't make much sense but I haven't chosen it. If anyone interested, below both Add and AddConnection method, additionally with SaveMatrix method that writes it nicely in txt file.
   public void Add(string vertex)
{
    this.vertices.Add(vertex);
    List<int> temp = new List<int>();

    foreach(List<int> element in this.adjacencyMatrix)
    {
        element.Add(0);
    }
    foreach(string element in vertices)
    {
        temp.Add(0);
    }
    this.adjacencyMatrix.Add(temp);

    this.n++;
}

  public void AddConnection(string vertex1, string vertex2, int value)
{
   if(this.vertices.Contains(vertex1) && this.vertices.Contains(vertex2))
    {
       int index1= this.vertices.IndexOf(vertex1);
        int index2 = this.vertices.IndexOf(vertex2);

        this.adjacencyMatrix[index1][index2] = value;
        this.adjacencyMatrix[index2][index1] = value;
    }
    else
    {
        Console.WriteLine("Graph doesn't contain passed vertex/vertices.");
    }
}

public void SaveMatrix(string filename)
{
    // save matrix with nice formatting
    // works if the names of the vertices are shorter than 16 chars and if edge weights are shorter than 100 (and positive)
    try
    {
        StreamWriter sw = new StreamWriter(filename);
        sw.Write("".PadRight(16)); // pad a string with white spaces to get exactly the specified length in chars
        foreach (string s in vertices) sw.Write(s.PadRight(16)); // write first row with names
        sw.WriteLine();
        int counter = 0;
        foreach (List<int> column in adjacencyMatrix) // other rows
        {
            sw.Write(vertices[counter].PadRight(16)); // start with vertex name
            counter++;
            foreach (int i in column)
            {
                if (i >= 10) sw.Write(i + "".PadRight(15)); // two digits
                else if (i > 0) sw.Write("0" + i + "".PadRight(15)); // one digit
                else sw.Write("--" + "".PadRight(15)); // no connection
            }
            sw.WriteLine();
        }
        sw.Close();
    }
    catch (IOException e)
    {
        Console.WriteLine("Error - the file could not be read");
        Console.WriteLine(e.Message);
    }
}


text:
Q: Inserted link to MatSnackBar not added to Angular tree This is a follow-up question to this thread related thread
I have the problem that the link is not working in the MatSnackBar. I already had a custom component which is pretty much looking like the working example above. However, Login is the same in the DOM. As I understand it, it should have been transformed by Angular to something like
Login

Could it be that I have to add the component via ViewContainerRef to the Angular tree?
Angular 5.0.3, angular/material 5.0.0
Snackbar.component.html

    {{message}}

popup.service excerpt
this.snackbar = this.popup.openFromComponent(SnackbarComponent, { panelClass: ['popup-error'] });
this.setSnackbarMessage(message);


text:
Q: How do you echo a SQL SELECT statement from a PHP file called by AJAX? There's a lot of code in each file, too much to post, so I'm giving you a general idea of what's happening in each file.
index.php
    [html dropdown menu code etc.]
scripts.js
    [AJAX detects user selection from dropdown, grabs fetch.php which pulls database to generate html code for secondary dropdown selections to put in index.php]
fetch.php
    [Generates secondary dropdown code based on user selection and query of the database]
I need to see what exactly is being queried to debug, so I'd like to echo the sql select statement:
$query = "SELECT * FROM databasename WHERE.."

That is in fetch.php when user makes a selection from index.php - How do I do this?

A: When I deal with AJAX, that I return as JSON, one trick I use is to take advantage of output buffering.  You can't just echo or output anything you want because it will mess up the JSON data so for an example,
ob_start(); //turn on buffering at beginning of script.

.... other code ...

print_r($somevar);

.... other code ...

$debug = ob_get_clean();  //put output in a var
$data['debug'] = $debug;

header('Content-Type: application/json');
echo json_encode($data); //echo JSON data.

What this does, is wrap any output from you script into your JSON data so that it's format is not messed up.
Then on the javascript side you can use console.log
$.post(url, input, function(data){
   if(data.debug) console.log(data.debug);
});

If you are not used to debugging with console.log(), you can usually hit F12 and open the debugger in most browsers.  Then in there the output will be sent to the "console".  IE9 had a bit of an issue with console.log() if I recall, but I don't want to go to far off track.
NOTE: Just make sure to not leave this stuff in the code when you move it to production, its very simple to just comment this line out,
//$data['debug'] = $debug;

And then your debug information wont be exposed in production.  There are other ways to automatically do this, but it depends on if you do development local then publish to the server.  For example you can switch it on the $_SERVER['SERVER_ADDR']; which will be ::1 or 127.0.0.1 when it's local.  This has a few drawbacks, mainly the server address is not available from the Command Line Interface (CLI).  So typically I will tie it into a global constant that says what "mode" the site is in (included in the common entry point, typically index.php).
if(!defined('ENV_DEVELOPMENT')) define('ENV_DEVELOPMENT','DEVELOPMENT');

if(!defined('ENV_PRODUCTION')) define('ENV_PRODUCTION','PRODUCTION');

if(!defined('ENVIRONMENT')) define('ENVIRONMENT',ENV_DEVELOPMENT);
//site is in Development mode, uncomment for production
//if(!defined('ENVIRONMENT')) define('ENVIRONMENT',ENV_DEVELOPMENT);

Then it is a simple matter to check it:
if(ENVIRONMENT == ENV_PRODUCTION ) $data['debug'] = $debug;

If you know how to use error reporting you can even tie into that using
 if(ini_get('display_errors') == 1) $data['debug'] = $debug;

Which will only show the debug when display errors is on.
Hope that helps.
UPDATE
Because I mentioned it in the comments, here is an example of it wrapped in a class (this is a simplified version, so I didn't test this)
class LibAjax{
    public static function respond($callback, $options=0, $depth=32){
        $result = ['userdata' => [
              'debug' => false,
              'error' => false
        ]];

        ob_start();

         try{

             if(!is_callable($callback)){
                //I have better exception in mine, this is just more portable
                throw new Exception('Callback is not callable');
             }

             $callback($result);
         }catch(\Exception $e){
              //example 'Exception[code:401]'
             $result['userdata']['error'] = get_class($e).'[code:'.$e->getCode().']';
            //if(ENVIRONMENT == ENV_DEVELOPMENT){
            //prevents leaking data in production
                $result['userdata']['error'] .= ' '.$e->getMessage();
                $result['userdata']['error'] .= PHP_EOL.$e->getTraceAsString();
            //}
         }

         $debug = '';
         for($i=0; $i < ob_get_level(); $i++){
             //clear any nested output buffers
             $debug .= ob_get_clean();
         }
         //if(ENVIRONMENT == ENV_DEVELPMENT){
             //prevents leaking data in production
              $result['userdata']['debug'] = $debug;
        //}
         header('Content-Type: application/json');
         echo self::jsonEncode($result, $options, $depth);
   }

   public static function jsonEncode($result, $options=0, $depth=32){
       $json = json_encode($result, $options, $depth);
       if(JSON_ERROR_NONE !== json_last_error()){
           //debug is not passed in this case, because you cannot be sure that, that was not what caused the error.  Such as non-valid UTF-8 in the debug string, depth limit, etc...
           $json = json_encode(['userdata' => [
              'debug' => false,
              'error' => json_last_error_msg()
           ]],$options);
       }
       return $json;
   }

}

Then when you make a AJAX response you just wrap it like this (note $result is pass by reference, this way we don't have to do return, and in the case of an exception we update $result in "real time" instead of on completion)
LibAjax::respond( function(&$result){
     $result['data'] = 'foo';
});

If you need to pass additional data into the closure don't forget you can use the use statement, like this.
$otherdata = 'bar';

LibAjax::respond( function(&$result) use($otherdata){
     $result['data'][] = 'foo';
     $result['data'][] = $otherdata;
});

Sandbox
This handles catching any output and puts it in debug, if the environment is correct (commented out). Please pleas make sure to implement some kind of protection so that the output is not sent to clients on production, I cant stress that enough. It also catches any exceptions puts it in error.  And it also handles the header and encoding.
One big benefit to this is consistent structure to your JSON, you will know (on the client side) that if if(data.userdata.error) then you have an exception on the back end.  It gives you one place to tweak your headers, JSON encoding etc...
One note in PHP7 you'll have to or should add the Throwable interface (instead of Exception). If you want to catch Error and Exception classes Or do two catch blocks.
Let's just say I do a lot of AJAX and got sick of re-writing this all the time, my actual class is more extensive then this, but that's the gist of it.
Cheers.
UPDATE1

One thing I had to do for things to display was to parse the data variable before I console.log() it

This is typically because you are not passing the correct header back to the browser.  If you send (just before calling json_encode)
header('Content-Type: application/json');

This just lets the browser know what type of data it is getting back.  One thing most people forget is that on the web all responses are done in text.  Even images or file download and web pages. It's all just text, what makes that text into something special is the Content-Type that the browser thinks it is.
One thing to note about header is you cannot output anything before sending the headers.  However this plays well with the code I posted because that code will capture all the output and send it after the header is sent.
I updated the original code to have the header, I had it in the more complex class one I posted later.  But if you add that in it should get rid of the need to manually parse the JSON.
One last thing I should mention I do is check if I got JSON back or text, you could still get text in the event that some error occurs before the output buffering is started.
There are 2 ways to do this.
If Data is a string that needs to be parsed
$.post(url, {}, function(data){
    if( typeof data == 'string'){
        try{
            data = $.parseJSON(data);
        }catch(err){
            data = {userdata : {error : data}};
        }
    }
    if(data.userdata){
          if( data.userdata.error){
               //...etc.
          }
    }
    //....
}

Or if you have the header and its always JSON, then its a bit simpler
$.post(url, {}, function(data){
    if( typeof data == 'string'){
        data = {userdata : {error : data}};
    }
    if(data.userdata){
          if( data.userdata.error){
               //...etc.
          }
    }
    //....
}

Hope that helps!
UPDATE2
Because this topic comes up a lot, I put a modified version of the above code on my GitHub you can find it here.
https://github.com/ArtisticPhoenix/MISC/blob/master/AjaxWrapper/AjaxWrapper.php

A: Echo the contents and do a die() or exit; afterwards... then in the Network tab of your browser, start it recording, run the Ajax request (it'll fail) but check the resource/name and then view the Response, and it'll show you what was echo'd in the script
Taken from: Request Monitoring in Chrome
Chrome currently has a solution built in.
Use CTRL+SHIFT+I (or navigate to Current Page Control > Developer > Developer Tools.
In the newer versions of Chrome, click the Wrench icon > Tools > Developer Tools.) to enable the Developer Tools.
From within the developer tools click on the Network button. If it isn't already, enable it for the session or always.
Click the "XHR" sub-button.
Initiate an AJAX call.
You will see items begin to show up in the left column under "Resources".
Click the resource and there are 2 tabs showing the headers and return content.

Other browsers also have a Network tab, but you will need to use what I commented to get the string value of the query.
ArtisticPhoenix solution above is delightful.


text:
Q: How to create an application that can be minimized to Windows XP taskbar? I want to create an application that user can minimize to taskbar on Windows XP.
Like

*

*iTunes

*Windows Media Player

*Google search

A: You are looking to create an Application Desktop Toolbar A simple example on doing so in C# with a Band Object is available here:
http://www.codeproject.com/KB/shell/dotnetbandobjects.aspx

A: It is known as DESK BAND


text:
Q: Gradient fill in linear vertical objective c FSCalender I am trying to do bezier path fill on selected dates. What I attained is
What I need is like
Here is my code
[super layoutSubviews];
[self.titleLabel sizeToFit];
self.titleLabel.center = self.contentView.center;

self.backgroundView.frame = CGRectInset(self.bounds, 5, 5);
self.circleImageView.frame = self.backgroundView.frame;

CGRect Fr_bounds = self.backgroundView.frame;
Fr_bounds.origin.x = self.bounds.origin.x;
Fr_bounds.origin.y = self.bounds.origin.y;
Fr_bounds.size.height = self.bounds.size.height;
Fr_bounds.size.width = self.bounds.size.width;

self.selectionLayer.frame = Fr_bounds;

UIBezierPath *path_layer;

if (self.selectionType == SelectionTypeMiddle) {

    path_layer = [UIBezierPath bezierPathWithRect:self.selectionLayer.bounds];

} else if (self.selectionType == SelectionTypeLeftBorder) {

    path_layer = [UIBezierPath bezierPathWithRoundedRect:self.selectionLayer.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft cornerRadii:CGSizeMake(self.selectionLayer.fs_width/2, self.selectionLayer.fs_width/2)];

} else if (self.selectionType == SelectionTypeRightBorder) {

    path_layer = [UIBezierPath bezierPathWithRoundedRect:self.selectionLayer.bounds byRoundingCorners:UIRectCornerTopRight|UIRectCornerBottomRight cornerRadii:CGSizeMake(self.selectionLayer.fs_width/2, self.selectionLayer.fs_width/2)];

} else if (self.selectionType == SelectionTypeSingle) {

    CGFloat diameter = MIN(self.selectionLayer.fs_height, self.selectionLayer.fs_width);
    path_layer = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(self.contentView.fs_width/2-diameter/2, self.contentView.fs_height/2-diameter/2, diameter, diameter)];

}

self.selectionLayer.path = path_layer.CGPath;

CAShapeLayer *gradientMask = [CAShapeLayer layer];
gradientMask.fillColor = [[UIColor blackColor] CGColor];
gradientMask.frame = CGRectMake(0, 0, self.fs_width, self.selectionLayer.frame.size.height);
gradientMask.path = path_layer.CGPath;

CAGradientLayer *gradientLayer = [CAGradientLayer layer];

gradientLayer.startPoint = CGPointMake(1.0, 0.0);
gradientLayer.endPoint = CGPointMake(0.0, 1.0);

gradientLayer.frame = CGRectMake(0, 0, self.fs_width, self.selectionLayer.frame.size.height);

gradientLayer.colors = @[(id)[UIColor colorWithRed:0.39 green:0.42 blue:0.85 alpha:1.0].CGColor,(id)[UIColor colorWithRed:0.38 green:0.80 blue:0.85 alpha:1.0].CGColor];

[gradientLayer setMask:gradientMask];
[self.selectionLayer addSublayer:gradientLayer];

I am using FSCalender and am customizing the DIY cell to attain this. I am not able to get selected cells in DIY Cell also the Beizer path of selected cells if selection type is middle
Thanks in Advance


text:
Q: Call SharePoint REST service then send email summary first post here. I'm a frequent visitor to the site but haven't posted until now. Now I'm facing an issue that has almost beaten me and I need your help.
My scenario (using SharePoint Designer and SharePoint Online):
I have a list that I need to retrieve item info from using a SharePoint 2013 workflow and calling the SharePoint REST api to then create an email summary if you like of the last 5 items created.
My issue is that when I set an index variable to 0 and then make sure the loop includes a calculation of index plus 1 to increment, it counts up just fine and logs to the history list as expected but what I need is for it to start from the highest item result number (using a count of items variable) and inserting a calculation of count minus 1 which I then output to a calculation result variable and set that to my item result number in my get action to then count down the last 5 items created. I set this up and no results log to the history list. I'm calling from _api/web/lists/getbytitle('listname')/items.
Also there aren't many clear articles on sending the summary email. When I insert a result variable in to a send email action it only returns the last item in the loop but returns all items to the history list using the index plus 1 method.
Apologies if this is really long winded but trying to as specific as possible.
I'd appreciate any help I can get and will post screenshots if needed.

A: You can do following steps in your workflow

Basically, you start the index from the length of items and minus the 1 every loop and read the items from last to first.
Also, you can change the API query to include the order by clause and go with forwarding loop.
Example:
_api/web/lists/getbytitle('listname')/items/$orderby=Id desc

In the above query use your own order by field.
I hope this helps you to proceed further and let me know if I miss anything here.


text:
Q: Insert Shell Command Output in Sed and replace existing file line I am trying to create a shell script, which needs to run on boot of new VPS Created. New VPS will be created with cPanel/WHM Panel pre-installed on CentOS 7 64bit template. Shell script needs to change the IP address of the VPS, with new IP address assigned to VPS while creation and reboot the cpanel service.
#!/bin/bash
echo -e "\e[1;36;40m Modifying parameters in cpanel shared IP configuration \e[0m"
ipchange="$(ip addr show | grep 'venet0:0' | awk '{ print $2}')"
echo "$ipchange"
sed -i -e 's/"ADDR 127.0.0.1$"/"ADDR $ipchange"/g' /etc/wwwacct.conf
echo -e "\e[1;36;40m Restarting cPanel \e[0m"
systemctl restart cpanel.service  > /dev/null 2>&1
echo -e "\e[1;36;40m Restart cpanel completed \e[0m"

I need to know how can I insert a partial output of below command
ip addr show | grep 'venet0:1' | awk '{ print $2}'

Example OUTPUT
bbb.bbb.bbb.bbb/32

Only need to copy bbb.bbb.bbb.bbb and insert in /etc/wwwacct.conf file by removing existing
ADDR 127.0.0.1

With new IP
ADDR bbb.bbb.bbb.bbb

Save the existing file and restart the cpanel services.

A: for your ip change you can use cut :
ip addr show | grep 'venet0:1' | awk '{ print $2}' | cut -d'/' -f1

And your sed should use double quotes to make the shell expand the $ipchange variable :
sed -i -e "s/ADDR 127.0.0.1/ADDR $ipchange/g" /etc/wwwacct.conf


text:
Q: Datadog python api error INFO No agent or invalid configuration file found I'm trying to use the datadog api but the initialize method keeps giving the error 'INFO No agent or invalid configuration file found'.
The datadog agent is running:
(PYTHON) daphnepaparis@Daphnes-MBP-2 ~ $ /usr/local/bin/datadog-agent status
Datadog Agent (supervisor) is running all child processes
And the configuration file permissions look alright:
(PYTHON) daphnepaparis@Daphnes-MBP-2 ~ $ ls -l ~/.datadog-agent/datadog.conf
lrwxr-xr-x  1 daphnepaparis  staff  35 Mar 22 12:58 /Users/daphnepaparis/.datadog-agent/datadog.conf -> /opt/datadog-agent/etc/datadog.conf
Original commands I'm running:
In [1]: from datadog import initialize, api
In [2]: options = {'api_key': '***'}
In [3]: initialize(**options)
2017-03-22 13:24:20 INFO No agent or invalid configuration file found
Anyone able to help?

A: So from that log line, it appears as though this try is excepting in the library's hostname.py. So either...

*

*(A) The hostname line is where it's excepting, and (weirdly) the
library requires that a hostname option be set in your
datadog.conf file. Maybe worth setting a hostname there if you
haven't already. Or,

*(B) The get_config() line is where it's excepting, and so the
library isn't able to correctly identify the configuration file
location (or access it, possibly related to permissions). Based on
the directory structure in your question, I think you're working on
an OSX / mac environment, which means the library will be using the
function _mac_config_path() in config.py to try to identify the
configuration path, which from this line in the function would
make it seem as though the library were looking for the
configuration file in ~/.datadog-agent/agent/datadog.conf instead
of the appropriate ~/.datadog-agent/datadog.conf. Which might be a
legitimate bug...
So if I were you, and if all this seemed right, I'd try adding a hostname in the datadog.conf to see if that helped, and if it didn't, then I'd try making a ~/.datadog-agent/agent/ directory and copying your datadog.conf file there as well, just to see if that got things working.
This answer assumes you are working in an OSX / mac environment, and will likely not be correct otherwise.
If either (A) or (B) are the case, then that's a problem with the library and should be updated--it would be kind of you to open an issue on the library itself to bring this up so the Datadog team that supports that library can be made aware. I suspect not many people end up this library in OSX / mac environments to begin with, so that could explain all this.