text:
Q: How to Iterate over grouped items and compare them? I'm having a hard time with this approach since I am new to Entity Framework. I actually don't know if there is something special related to EF or if the limitation is on me.
I would like to group some records from my database and after that, I'd like to iterate over the groups, then iterate over the elements on each group comparing it with all the other elements in the same group.
I have created two simple classes to illustrate the scenario:
public class MyContext : DbContext
{
    public DbSet<MyClass> MyClass { get; set; }
}

And:
public class MyClass
{
    public int Id { get; set; }
    public int Value { get; set; }
}

What I have so far with a context injected is:
this.MyContext.MyClass
            .GroupBy(x => x.Value)
            .ToList() // need to materialize here
            .ForEach(grp =>
            {
                // compare each item with all the other
                // items in the current group
            });

But I don't know how to iterate over the items and then compare with the others in the same group.

A: With the following code, the quesiton becomes what type is grp?
this.MyContext.MyClass
  .GroupBy(x => x.Value)
  .ToList() // need to materialize here
  .ForEach(grp =>
  {
    // compare each item with all the other
    // items in the current group
  });

Well the grp variable is of type IGrouping<TKey, TElement>. That type derives from IEnumerable<TElement> so each grp is a list of TElement so you can foreach or do whatever you want to all the items in the grp.
DotNetFiddle Example.

A: Your variable grp is an IGrouping<int, MyClass>. You can treat it as an IEnumerable<MyClass>. For instance, you can get the item with the biggest Id like this:
this.MyContext.MyClass
    .GroupBy(x => x.Value)
    .ToList() // need to materialize here
    .ForEach(grp =>
    {
         MyClass itemWithMaxId = grp.FirstOrDefault();
         foreach (MyClass item in grp)
         {
             if (item.Id > itemWithMaxId.Id)
             {
                 itemWithMaxId = item;
             }
         }
    });

Note, however, that the ForEach method does not return anything, it only performs the specified action on each element of the list. If you want to get something, for instance the item with the biggest Id of each group, I suggest you to use the Select method provided by Linq, like in this example:
var itemsWithMaxIdByGroup = this.MyContext.MyClass
    .GroupBy(x => x.Value)
    .ToList() // need to materialize here
    .Select(grp =>
    {
         MyClass itemWithMaxId = grp.First();
         foreach (MyClass item in grp.Skip(1))
         {
             if (item.Id > itemWithMaxId.Id)
             {
                 itemWithMaxId = item;
             }
         }

         return itemWithMaxId;
    });


text:
Q: Cannot read property 'setBounds' of undefined When I click on autocomplete input I am getting;

Cannot read property 'setBounds' of undefined

<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" />

    <input id="autocomplete" placeholder="Enter your address"
        onfocus="geolocate()" type="text"></input>

<table id="address" <%--style="visibility: hidden;"--%>>

        Street address

            <input class="field" id="street_number"
                disabled="true"></input>

            <input class="field" id="route"
                disabled="true"></input>

        City

            <input class="field" id="locality"
                disabled="true"></input>

        State

            <input class="field"
                id="administrative_area_level_1" disabled="true"></input>
        Zip code

            <input class="field" id="postal_code"
                disabled="true"></input>

        Country

            <input class="field"
                id="country" disabled="true"></input>

A: Your code IS working.
A reference to jQuery is missing, add it with :

just before the inclusion of Google Maps Places library

A: You shoud write like this :
jQuery(document).ready(function () {
        initialize(); });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generate Random Middle Initial in TSQL How could I write a program in TSQL to go through each row of the table and generate a random letter for the middle initial column?

A: You could use a simple UPDATE statement instead of writing a program for it. An example would be (using the table/field names from your answer);
UPDATE Contact SET conMName = CHAR(ABS(CHECKSUM(NEWID()))%26+65)

A: Assuming your Identity column held integers that incremented by one, the identity column was called conID, your table was called EDI.Contact and column that held middle names was called conMName, the folowing code would work;
DECLARE
    @Counter INT = '1'
    , @GeneratedLetter CHAR(1)
    , @NumberOfRows INT = (SELECT COUNT(*) FROM EDI.Contact) -- Replace with your table name
    , @LetterNumber INT
WHILE (@Counter < @NumberOfRows +1)
BEGIN
SET @LetterNumber = (CAST(RAND(CHECKSUM(NEWID())) * 26 as INT) + 1)
IF @LetterNumber = '1'
SET @GeneratedLetter = 'A'
ELSE IF @LetterNumber = '2'
SET @GeneratedLetter = 'B'
ELSE IF @LetterNumber = '3'
SET @GeneratedLetter = 'C'
ELSE IF @LetterNumber = '4'
SET @GeneratedLetter = 'D'
ELSE IF @LetterNumber = '5'
SET @GeneratedLetter = 'E'
ELSE IF @LetterNumber = '6'
SET @GeneratedLetter = 'F'
ELSE IF @LetterNumber = '7'
SET @GeneratedLetter = 'G'
ELSE IF @LetterNumber = '8'
SET @GeneratedLetter = 'H'
ELSE IF @LetterNumber = '9'
SET @GeneratedLetter = 'I'
ELSE IF @LetterNumber = '10'
SET @GeneratedLetter = 'J'
ELSE IF @LetterNumber = '11'
SET @GeneratedLetter = 'K'
ELSE IF @LetterNumber = '12'
SET @GeneratedLetter = 'L'
ELSE IF @LetterNumber = '13'
SET @GeneratedLetter = 'M'
ELSE IF @LetterNumber = '14'
SET @GeneratedLetter = 'N'
ELSE IF @LetterNumber = '15'
SET @GeneratedLetter = 'O'
ELSE IF @LetterNumber = '16'
SET @GeneratedLetter = 'P'
ELSE IF @LetterNumber = '17'
SET @GeneratedLetter = 'Q'
ELSE IF @LetterNumber = '18'
SET @GeneratedLetter = 'R'
ELSE IF @LetterNumber = '19'
SET @GeneratedLetter = 'S'
ELSE IF @LetterNumber = '20'
SET @GeneratedLetter = 'T'
ELSE IF @LetterNumber = '21'
SET @GeneratedLetter = 'U'
ELSE IF @LetterNumber = '22'
SET @GeneratedLetter = 'V'
ELSE IF @LetterNumber = '23'
SET @GeneratedLetter = 'W'
ELSE IF @LetterNumber = '24'
SET @GeneratedLetter = 'X'
ELSE IF @LetterNumber = '25'
SET @GeneratedLetter = 'Y'
ELSE IF @LetterNumber = '26'
SET @GeneratedLetter = 'Z'
UPDATE EDI.Contact -- Replace with your table name
SET conMName = @GeneratedLetter -- Replace with column that holds middle names
WHERE conId = @Counter -- Replace with identity column name
SET @Counter = (@Counter + 1)
END


text:
Q: gem swagger-docs not generating apropriate json files to be displayed on swagger-ui swagger-ui is not displaying my docs and o dont know why. I'm using swagger-docs gem, i generated the api-docs.json, i created a route to access the index.html of swagger-ui, i passed as parameter the path of api-docs.json the result was that:
swagger-ui index.html
Could anyone help me?
config/initializers/swagger-docs.rb
Swagger::Docs::Config.base_api_controller = ActionController::API

Swagger::Docs::Config.register_apis({
  "1.0" => {
    # the extension used for the API
    :api_extension_type => :json,
    # location where our api doc files will be generated, as of now we will store files under public directory
    :api_file_path => "public/docs",
    # base path url of our application
    # while using production mode, point it to production url
    :base_path => "http://localhost:3000",
    # setting this option true tells swagger to clean all files generated in api_file_path directory before any files are generated
    :clean_directory => true,
    # As we are using Rails-API, our ApplicationController inherits ActionController::API instead of ActionController::Base
    # Hence, we need to add ActionController::API instead of default ActionController::Base
    # :base_api_controller => ActionController::API,
    # parent_controller needs to be specified if API controllers are inheriting some other controller than ApplicationController
    :parent_controller => ActionController::API,
    :attributes => {
      :info => {
        "title" => "Todos API Demo",
        "description" => "This documentation is related to Todos API",
        "contact" => "silva.danilo.nobre@gmail.com",
        "license" => "Apache 2.0",
        "licenseUrl" => "http://www.apache.org/licenses/LICENSE-2.0.html"
      }
    }
  }
})

public/docs/api-docs.json
{
  "apiVersion": "1.0",
  "swaggerVersion": "1.2",
  "basePath": "http://localhost:3000",
  "apis": [
    {
      "path": "/v2/todos.{format}",
      "description": "Todos Management"
    },
    {
      "path": "/v1/items.{format}",
      "description": "Item Management"
    },
    {
      "path": "/v1/todos.{format}",
      "description": "Todos Management"
    }
  ],
  "authorizations": null,
  "info": {
    "title": "Todos API Demo",
    "description": "This documentation is related to Todos API",
    "contact": "silva.danilo.nobre@gmail.com",
    "license": "Apache 2.0",
    "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0.html"
  }
}

public/docs/v1/todos.json
{
  "apiVersion": "1.0",
  "swaggerVersion": "1.2",
  "basePath": "http://localhost:3000",
  "resourcePath": "todos",
  "apis": [
    {
      "path": "/todos.json",
      "operations": [
        {
          "summary": "Returns all Todos",
          "notes": "Implementation notes, such as required params, example queries for apis are written here.",
          "responseMessages": [
            {
              "code": 200,
              "responseModel": null,
              "message": "Ok"
            }
          ],
          "nickname": "V1::Todos#index",
          "method": "get"
        }
      ]
    },
    {
      "path": "/todos.json",
      "operations": [
        {
          "summary": "Create a new Todo item",
          "notes": "Notes for creating a new Todo item",
          "responseMessages": [
            {
              "code": 401,
              "responseModel": null,
              "message": "Unauthorized"
            },
            {
              "code": 406,
              "responseModel": null,
              "message": "Not Acceptable"
            },
            {
              "code": 422,
              "responseModel": null,
              "message": "Unprocessable Entity"
            }
          ],
          "parameters": [
            {
              "paramType": "form",
              "name": "todo[title]",
              "type": "string",
              "description": "Title",
              "required": true
            },
            {
              "paramType": "form",
              "name": "todo[created_by]",
              "type": "string",
              "description": "Created By",
              "required": true
            }
          ],
          "nickname": "V1::Todos#create",
          "method": "post"
        }
      ]
    },
    {
      "path": "/todos/{id}.json",
      "operations": [
        {
          "summary": "Fetches todo by id",
          "notes": "Find todo by id",
          "responseMessages": [
            {
              "code": 401,
              "responseModel": null,
              "message": "Unauthorized"
            },
            {
              "code": 406,
              "responseModel": null,
              "message": "The request you made is not acceptable"
            },
            {
              "code": 500,
              "responseModel": null,
              "message": "Requested Range Not Satisfiable"
            }
          ],
          "parameters": [
            {
              "paramType": "path",
              "name": "id",
              "type": "integer",
              "description": "Todo Id",
              "required": false
            }
          ],
          "nickname": "V1::Todos#show",
          "method": "get"
        }
      ]
    },
    {
      "path": "/todos/{id}.json",
      "operations": [
        {
          "summary": "Updates an existing Todo item",
          "responseMessages": [
            {
              "code": 401,
              "responseModel": null,
              "message": "Unauthorized"
            },
            {
              "code": 404,
              "responseModel": null,
              "message": "Not Found"
            },
            {
              "code": 406,
              "responseModel": null,
              "message": "Not Acceptable"
            }
          ],
          "parameters": [
            {
              "paramType": "path",
              "name": "id",
              "type": "integer",
              "description": "User Id",
              "required": true
            },
            {
              "paramType": "form",
              "name": "todo[title]",
              "type": "string",
              "description": "Title",
              "required": true
            },
            {
              "paramType": "form",
              "name": "todo[created_by]",
              "type": "string",
              "description": "Created By",
              "required": true
            }
          ],
          "nickname": "V1::Todos#update",
          "method": "patch"
        }
      ]
    },
    {
      "path": "/todos/{id}.json",
      "operations": [
        {
          "summary": "Deletes an existing Todo item",
          "responseMessages": [
            {
              "code": 401,
              "responseModel": null,
              "message": "Unauthorized"
            },
            {
              "code": 404,
              "responseModel": null,
              "message": "Not Found"
            }
          ],
          "parameters": [
            {
              "paramType": "path",
              "name": "id",
              "type": "integer",
              "description": "User Id",
              "required": false
            }
          ],
          "nickname": "V1::Todos#destroy",
          "method": "delete"
        }
      ]
    }
  ],
  "authorizations": null
}

A: I decided to remove swagger-docs gem from the project and create an api-docs.json manually. Thus, i can decide exactly what resources my API can provide and it become easier to do. Choose this gem, for me, was not a good idea


text:
Q: "unsupported operand type(s) for %" when building SQL query I am using PASSWORD in SQL to hash user passwords.
sql = text('insert into account values("%s", "%s", "%s", PASSWORD("%s"), "1" )'%(fname, lname, user_name, password))

When I try to log in using the password it wont allow me to access the account.
sql = text('select * from account where account.user_name = "%s"  and account.password = PASSWORD("%s") and account.active = ' + '"' + '1' + '"')%(user_name, password)

I get the error:
 unsupported operand type(s) for %: 'TextClause' and 'tuple'

What am I doing wrong when trying to access the encrypted password?

A: The immediate error is that in the first example you used string formatting % on the string, and then enclosed the result in text, while the second one tries to use string formatting on the text object.
The more severe problem is that you've opened yourself to injection attacks by formatting user input directly into the SQL string rather than passing them separately.
It looks like you are using Flask-SQLAlchemy.  In that case, write a parameterized query and pass the parameters to be properly escaped to execute.
db.engine.execute(
    'insert into account values(?, ?, ?, PASSWORD(?), ?)',
    (fname, lname, user_name, password, True)
)

db.engine.execute(
    'select * from account where account.user_name = ?  and account.password = PASSWORD(?) and account.active = ?,
    (user_name, password, True)
)

The parameterized concept is similar for any other database driver.

Rather than relying on the database to hash the passwords, using the passlib library is a much more robust alternative.  It contains much stronger hashes, as well as the ability to "deprecate" hashes and upgrade the stored value.
from passlib.hash import pbkdf2_sha512

# when creating a user, generate the hash with passlib
# and don't use PASSWORD() in SQL
password = pbkdf2_sha512.encrypt('secret')

# example login
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        r = engine.execute('select * from account where account.name = ? and account.active = ?', (username, True))

        if r:
            user = r[0]

            # verify the hash using passlib, not SQL
            if pbkdf2_sha512.verify(password, user.password):
                # active user, correct password, do the login
                return 'good credentials'

        # incorrect username or password
        return 'bad credentials'

    return render_template('login.html')

Pass these hashes in, rather than calling PASSWORD in SQL.


text:
Q: Coverting two uint32_varible in in one Uint8 I have a question with converting two uint32 variables and pass it as one uin8 variable. I am not sure how to exactly proceed with it ? or dont know even if it is possible.
I want it in litte endian approach.
Also is it possible to pass the array values as a one variable as unint8_t* as i need to send the value to the function
func(uint8_t *result);
example
uint32_t var1 = 1 2 3 4 5 6 7 8
uint32_t var2 = 9 A B C D E F 0

result
*uint8_t= 12 34 56 78 9A BC DE F0

I tried this approach but not sure how to use it with two uint_32 variables
uint32_t value;
uint8_t *result[4];

result[0] = (value & 0x000000ff);
result[1] = (value & 0x0000ff00) >> 8;
result[2] = (value & 0x00ff0000) >> 16;
result[3] = (value & 0xff000000) >> 24;

func(uint8_t *result);

I am getting *** stack smashing detected ***: terminated

A: the main error that you get is due to definingthe result vector as pointer array but later writing them with values. this is constructed at heap. what you want is to define an array of uint_8 of size 4 or 8 which store values corresponding to uint32_t.
since you are using uC, they could have different bytes order to represent words or datas (like int32 , int64 , etc). since you gave the example that you expect, and I am runnign the code on LSB or little endian pc (x86, arm, 64 etc ) then I have to parse it as follow. but in uC if it is Big endian (MSB first) then parse in reverse.
#include<stdio.h>
#include<stdint.h>

uint32_t var1 = 0x12345678;
uint32_t var2 = 0x9ABCDEF0;

void to_uint8_t(uint32_t value, uint8_t* result){
    for(uint16_t i = 0; i< 4;i++)
        result[3 - i] = (value >> (i * 8))& 0xff; /* little endian*/
        // result[i] = (value >> (i * 8))& 0xff; /* big endian*/
}

int main(){
    uint8_t result[8];

    to_uint8_t(var1, result);
    to_uint8_t(var2, result + 4);

    for(uint16_t i =0; i< 8;i++)
       printf("%x ", result[i]);
    printf("\n");
}

output:
12 34 56 78 9a bc de f0


text:
Q: Is $D$ well-defined? In my text there's a problem which reads as:

Consider $C[0, 1]$ with the norm $\|.\|_\infty$. Let $Y$ be the vector subspace of all differentiable functions on $[0, 1].$ Consider the linear map $D: (Y, \|.\|_\infty)\to(C[0, 1],\|.\|_\infty)$ given by $Df = f'$, the
  derivative of $f$. Show that $D$ is not continuous.

Is $D$ well-defined for what is the guarantee of the continuity of the derived function on $[0,1]$ of a continuous function on $[0,1]?$

A: As Brian M. Scott said, the map $D:Y\to C[0,1]$ is defined provided we take $Y$ to be the space of continuously differentiable functions, usually denoted $C^1[0,1]$.
Concerning the discontinuity of $D$, a standard example is $f_n(x)=n^{-1}\sin nx$. You can check that $\|f_n\|\to 0$ but $\|Df_n\|\not\to 0$.


text:
Q: Simple problem with MAX in sql I have the table with rows:
ID          CountryCode Status
----------- ----------- -----------
2           PL          1
3           PL          2
4           EN          1
5           EN          1

and by the query
    SELECT [CountryCode]
      ,MAX([Status])
  FROM [TestTable]
  GROUP BY CountryCode,Status

I want to get:
CountryCode Status
----------- -----------
PL          2
EN          1

but I get:
CountryCode Status
----------- -----------
EN          1
PL          1
PL          2

What is wrong with this query?
Best regards
EDIT
Ok, Thanx for manz answers, but I didn't add part of query, which is :
Having Status != 3

so I think I must use Status in group by :/
Script to create and fill table:
USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestTable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [CountryCode] [nvarchar](2) NOT NULL,
    [Status] [int] NOT NULL
) ON [PRIMARY]

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'PL', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'PL', -- CountryCode - nvarchar(2)
            2  -- Status - int
            )

INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'EN', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )
INSERT INTO dbo.TestTable
          ( CountryCode, Status )
  VALUES  ( 'EN', -- CountryCode - nvarchar(2)
            1  -- Status - int
            )

A: You need to get rid of the group by status.  The group by says return a new row for every unique combination of CountryCode and Status, which is not what you want.
You can add the where clause to exclude the rows that you don't want to consider in your query.
Try:
SELECT [CountryCode]
      ,MAX([Status])
  FROM [TestTable]
  WHERE status <> 3
  GROUP BY CountryCode

A: Just drop status from the group by:
   SELECT [CountryCode]
      ,MAX([Status])
  FROM [TestTable]
  GROUP BY CountryCode

A: When you add group by status it will do additional grouping within country code. Then your MAX selects maximum for country code. Remove status from group by.

A: Don't group by the Status.  Try this:
SELECT [CountryCode]
      ,MAX([Status])
  FROM [TestTable]
  GROUP BY CountryCode


text:
Q: No orientations in info.plist file , will it be rejected? I've send my first application (iOS app for iPhone) 6 days ago and it's still waiting foe review . I recognize that in info.plist file there is no supported interface orientations selected . I forgot select one of them . Is it an rejection reason ? Additionally , technically the app is using only portrait UIO , but I have implemented orientations manually (like some words are turning right 90 degree or left) with using UIDeviceOrientation , will it be a probl

A: I very highly doubt that your app would be rejected for something so trivial. Selecting supported orientations is just additional metadata and doesn't affect the function of your app. See this post for more:
Xcode 4 Supported Device Orientations
Having said that, Apple can do whatever they want. If it bothers you that much, you can always reject your own binary and resubmit it with the changes. That will probably put you at the back of the line for review, which won't matter much if you recently submitted it anyway.


text:
Q: Parallel nullable and non-null method with same name I would like to offer two methods with the same name which can accept optional or non-optional input:
class Formatter {
    fun format(input: Number?) : String? {return number?.toString()}
    fun format(input: Number) : String {return number.toString()}
}

Apparently this is not possible due to JVM limitations:
Platform declaration clash: The following declarations have the same JVM signature (test(Lorg.example.Number;)Ljava/lang/String;):
Is there a readable workaround to achieve the same goal? My current solution is to rename one method (e.g. formatNonNull(input: Number)).
Bonus: My Formatter-class is actually written in Java and looks like this:
class Formatter {
    @Nullable String format(@Nullable Number input) : String {return number != null ? number.toString(): null;}
}

It shall be extended by the non-null variant:
@NonNull String formatNonNull(@NonNull Number input) : String {return number.toString();}

Is there a way to improve this i.e. without introducing a new name (e.g. with kotlin extension)?

A: There's a neat hack to fix this on the JVM:
class Formatter {
    fun format(input: Number?) : String? {return number?.toString()}
    @JvmName("-formatNonNull") fun format(input: Number) : String {return number.toString()}
}

The reason this works is that - is a valid identifier character in the JVM bytecode, but not in the Java language. This means that the code will compile and you'll be able to call both methods in Kotlin, but you won't be able to call a method that has - in its name from Java. This also eliminates the name clash since the methods will have different names in bytecode.


text:
Q: MySQL Problems Bigger =Slower? Please bear with me, I'm not overly confident with MySQL coding.
I am running a site that is similar to twitter. However, it seems the more followers a user gets, the slower the site runs on that particular user profile.
A user with few followers has a reasonably fast page load.
Below is the "Follower" part of the MySQL, can any of you see a problem with the code or shed any light as to why this is happening?
Thanks in advance.
CODE:
CREATE TABLE IF NOT EXISTS `followers` (
    `id`        int(10)       unsigned            NOT NULL  AUTO_INCREMENT,
    `follower`  int(11)       unsigned            NOT NULL,
    `following` int(10)       unsigned            NOT NULL,
    `status`    enum('0','1') CHARACTER SET utf8  NOT NULL  DEFAULT '1' COMMENT '0 Trash, 1 Active',
    `date`      timestamp                         NOT NULL  DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `follower` (`follower`,`following`,`status`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;

A: first thing, why are you using MyISAM engine for a table that is constantly being updated, this slows down your app as MyISAM uses table level locks, meaning selects have to wait for inserts to be done for them to run, always use InnoDB for such tables.
second thing I think it would be better to use a key for each of follower and following because now any query that is like WHERE following=X won't use your index follower
If you can show a sample of your SELECTS, maybe you'll get some more suggestions.


text:
Q: jQuery, dynamically count number of elements on a page I am trying to count the number of inputs on a page with a particular class.
$(".count").click(function(){
  var named = $(this).parent().find("input").eq(1).attr('class');
  var count = $('input[name='+named+']').length;
  alert(count + ' of class ' + named);
});

The count always returns a value of zero. Have I set the 'count' variable correctly? If not, how should I do this.
thanks.

A: If you want them by class, you'd need to change this:
$('input[name='+named+']')

to this:
$('input[class='+named+']')

or this:
$('input.'+named)

If the element you get in the first line of the handler has more than one class, you'll need to change it from this:
var named = $(this).parent().find("input").eq(1).attr('class');

to this:
var named = $(this).parent().find("input").eq(1).attr('class').split(/\s+/).join('.');

so that you end up with:
someClass.anotherClass

Then use this one:
$('input.'+named)


text:
Q: [: -!eq: binary operator expected I have an issue with this Below Code
getting an error called :
[: -!eq: binary operator expected]

How do I fix this error
RC=$?
if [ $RC -eq 0 ]; then
    echo  File: $j Deletion Successfull >> $_Main/Status"_"$_date
else
    echo File: $j Deletion Failed >> $_Main/Status"_"$_date
fi

A: The source of the error: [: –le: binary operator expected might be that you are using the unicode version of "–" instead of the regular "-".
Check your keyboard settings / mappings and try to use the normal "-".

A: You code is running perfectly well. However, if i change it like that :
#!/bin/sh

RC=$?
if [ $RC eq 0 ]; then
    echo  File:
else
    echo File:
fi

I got the same error :
./test.sh: line 4: [: eq: binary operator expected
File:

This means you should check that you are using -eq and not anything else. The problem is clearly located into your condition.
In your case, seems that you tried to negate the equals condition with a !. This clearly won't work.


text:
Q: Are there commands similar to Ubuntu's 'apt-get clean' and 'apt-get autoremove' in CentOS? I think the title of my question tells it all, but once again, I'm looking for CentOS commands that do the same as those two Ubuntu's:
sudo apt-get clean
(removes packages downloaded for installation)
sudo apt-get autoremove
(removes packages that are no longer needed, including old kernels).
Thanks


text:
Q: PHP - Not able to link tables to get the required information Scenario
A user can show an interest to attend an event's dinner and the people who administer that event can choose to accept their request or not and if the request has already been accepted the "Accept" button should then be disabled.
Whats working
Everything is working till the part where the button needs to be disabled, the information is displaying right and i am having hard time linking database tables up so i can then use the information i need to disable the button.
The Attempt
This is what my query looks like
SELECT
r.id as request_id,
r.status as dinner_status,
r.dinner_id,
d.name as dinner_name,
d.date as dinner_date,
u.first_name as user_first_name,
u.last_name as user_last_name,
u.id as user_id,
u.description as user_description,
u.profile_image as user_profile_image,
c.name as user_college_name,
c.id as user_college_id,
c.slug as user_college_slug
FROM `requests` r
LEFT JOIN `college_dinners` d ON r.dinner_id = d.id
LEFT JOIN `user` u ON r.guest_id = u.id
LEFT JOIN `college` c on u.college_id = c.id
WHERE d.college_id = $collegeId
AND u.id = '77'

Now the most important part.
There is a table called invitations that keeps the guest_id and dinner_id ONLY if their request for dinner has been excepted. How can i make use of this invitations table to update my query and include information in it based on which i can enable and disable button on my view?
The PHP Attempt
I am open to solving this in PHP it self too, so I decided the use the foreach loop for the results that i get from above query and inside the foreach i am creating another query to the table invitations and then using if i am checking if the current loop's dinner_id matches the dinner_id and the same for guest_id of the second query inside the foreach but by doing that i the index gets screwed.
foreach ($invitations as $invitation) {
  $invitatedSQL=".....";

if ( $invitedResult['guest_id'] == $invitation['user_id'] && $invitedResult['dinner_id'] == $invitation['dinner_id'] ) {
  $isInvited = 'yes';
}
}

Please note that I do not need any help on the front end, its just the mysql query that I am having the problem with. I will really appreciate any help on this matter

A: Just a simple, left join. If the condition is false, there will be NULLs.
LEFT JOIN `invitations` i on r.guest_id = i.guest_id AND r.dinner_id = i.dinner_id

P.S.
Few of Your LEFT JOINs acts like a plain INNER JOINs. You should read about differences.
What is the difference between "INNER JOIN" and "OUTER JOIN"?


text:
Q: How to continually update a set of lines in manim I'm relatively new to manim and have run into a strange issue I don't understand. I'm trying to continually update a set of lines and everything seems to work fine, but then all of the lines disappear except one.  Here is a short (non) working example to demonstrate what's happening. First I create a set of arrows and also a set of lines (using always_redraw), all of which begin at a dot. Then I create a list of GrowArrow animations, which allows me to grow the entire set of arrows at the same time. This seems to work fine. Next, I create a list of ReplacementTransform animations to turn the arrows into the lines. This also seems to work fine, but after the arrows are transformed into lines, all of the lines end up disappearing except the last one. Lastly, I move the dot to show that the lines are continually updated. This seems to work fine for the single line that is left, but I don't understand why all but one of the lines are disappearing. I am using manimCE v0.7.0 on a mac.  Here is the code and the final image from the movie.  Any help would be greatly appreciated, as this is driving me nuts and I am completely stymied.
class RedrawTest(Scene):
    def construct(self):
        # Create x and y coordinates for a set of arrows
        n_arrows = 8
        length = 3
        angles = np.linspace(0,PI,n_arrows)
        x, y = length*np.cos(angles), length*np.sin(angles)

        dot = Dot()
        arrows = [Arrow(dot.get_center(), [x[i],y[i],0], buff=0) for i in range(n_arrows)] # List of arrows from dot to (x,y) coords
        lines = [always_redraw(lambda: Arrow(dot.get_center(), [x[i],y[i],0], tip_length=0.0, buff=0)) for i in range(n_arrows)] # List of (always redrawn) lines from dot to (x,y) coords

        grow_arrows = [GrowArrow(arrows[i],run_time=2) for i in range(n_arrows)] # List of GrowArrow animations
        transform = [ReplacementTransform(arrows[i],lines[i],run_time=4) for i in range(n_arrows)] # List of ReplacementTransform animations

        self.play(FadeIn(dot))
        self.play(*grow_arrows) # Grow an entire set of arrows simultaneously
        self.wait()
        self.play(*transform) # Transform entire set of arrows into (always redrawn) lines
        self.wait()
        self.play(dot.animate.shift(2*DOWN),run_time=3) # Move dot
        self.wait()


text:
Q: Run long SAS stored proc from php without hanging browser I need to call a SAS stored proc that takes about 5 minutes to run without hanging up my browser. I'm using a Yii stack and calling SAS through a url. I'd attach code, but honestly I've tried so many things at this point that there's not a version of my code that makes any sense anymore. Any direction would be greatly appreciated.
Note: I've tried exec() and that doesn't seem to work. I've tried ajax, and would prefer an async ajax call, but at this point I'll try anything. Any other information that is needed, just let me know.
UPDATE: I created a controller action in php that successfully completes the stored process if I go directly to the controller action in the url of the browser. However, if I call that controller action with an ajax get, the stored process doesn't execute.

A: ajax should work fine!  You can even try using the SASjs javascript library. More details on the website.  Example code - once configured - is as follows:
var adapter = new SASjs.default({
     appLoc: "/SASFolder/appLocation"
    ,serverType:"SAS9"
}); // Can be SAS9 or Viya

var dataObj = {tableName: [{ colName: 'colValue' }]}; // can be null
adapter.request('/subfolder/servicename',dataObj)
.then((response) => {
  //we just submitted a request, now deal with response
  alert(response);
  // all code here will execute AFTER the STP / JES is finished
});
// all code here will execute immediately

A: If you are calling the SAS Stored Procedure successfully from php then you just need to call your php service asynchronously from javascript.
$.ajax({
    type: "POST",
    url: url + '&_action=background',
    data: data, // additional parameters
    async:true,
    success: function(response){
     alert(response);
     // all code here will execute AFTER the PHP/STP is finished
    }
});
// all code here will execute immediately

credit to @angel
Edit: adding _action=background to URL following @quentin's suggestion


text:
Q: Mapping between T --> IHandler I have the following interface
public interface IHandler<T>
{
    void Handle(T myObject);
}

I'd like to have a HandlersManager class with holds a mapping between object types to their corresponding handler, but I'm not sure how I'm supposed to define the object that hold this mapping.
For example, what I'd like to have is this:
typeof(string)  --> instance of IHandler<string>
typeof(MyClass) --> instance of IHandler<MyClass>

The best thing I got so far was to define Dictionary<Type, object> for the mapping, but in this case I would have to cast the value to IHandler<T> every time I get it.
Is there a better solution or something that I have completely missed?

A: That's as good as it can get with only a generic IHandler<T> interface.
In order to explore more options, we could define a non-generic version of the interface:
public interface IHandler
{
    void Handler(object myObject);
}

Then you could also define a generic abstract base class that implements both IHandler<T> and IHandler:
public abstract class BaseHandler<T> : IHandler, IHandler<T>
{
    public abstract void Handle(T myObject);

    void IHandler.Handle(object myObject)
    {
        ((IHandler<T>)this).Handle((T) myObject);
    }
}

At this point you can have an IDictionary<Type, IHandler> and you can directly call IHandler.Handle on the values you pull out of it:
var obj = /* whatever */
dictionary[obj.GetType()].Handle(obj);

On the other hand we now have an additional interface and an abstract base class just to hide a cast from "user" code, which doesn't sound very impressive.

A: I suspect you're using this to resolve dependencies. Instead, use a dedicated container that will handle these issues for you.
If you don't want to do that, you want something like this:
Dictionary<Type, object> dictionary;

IHandler<T> Resolve<T>() {
    return (IHandler<T>)dictionary[typeof(T)];
}

There isn't any other way with generics.

Is there a better solution or something that I have completely missed?

No, but manager classes are generally code smells. Be careful.


text:
Q: run command lxrun failed I use the command(cmd) "lxrun /uninstall /full /y" to uninstall my sublinux in my Windows 10.Then,I use the cmd "lxrun /install /y" to reinstall,but there is problem I encountered as flows:
- Beta features -
This will install Ubuntu distributed by Canonical on Windows Under the terms of its license, see this link:
https://aka.ms/uowterms
Downloading from the Windows app store ...
Error: 0x80072f7d
Downloading from the Windows app store ...
Error: 0x80072f7d
Downloading from the Windows app store ...
Error: 0x80072f7d
Can not be downloaded from the Windows app store. Please check the network connection.
I ensure that other applications include Windows App Stor can access the Internet,becase I tried and successed just now.
so,I have no idea and has anyone ever encountered this problem?


text:
Q: vscode didn't close all django processes when comment "--noreload" VSCode Version: 1.42.1
OS Version: Ubuntu 18.04
Steps to reproduce:

*

*Comment "--noreload" in launch.json

*Press Ctrl + F5 to run the django process.

*Click "stop(Shift + F5)" button to stop all django processes.

*But there is still a process (pid 23069) that has not been closed.

*And its parent process become 1 from 23064


text:
Q: C# / vb.net winforms app cannot communicate with SQL server when client is running a VPN (such as NordVPN, TunnelBear) I have a winforms app that communicates perfectly with the SQL server until the user is using a VPN (such as NordVPN, TunnelBear) to hide their public IP address.
The exception is "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible."
I have tried to edit the SQL connection string to use the IP address instead of the SQL server name, but that did not seem to help.


text:
Q: kafka offset and log retention configuration at topic level We have a topic with 5 partitions. We are defining the partition based on the checksum of the key. There are cases where there are no key resolving to partition 3 and so there are no commits made. Hence after the configured number of days for offset retention, the consumer current offset starts showing unknown. We will need to resolve this, hence thought we will have to set log and offset retention at topic level.
In the config, I see that we have config:retention.ms is for log retention but did not find corresponding offset retention configuration. Can someone please help on the same.
Edit:
bin/kafka-topics.sh --zookeeper XXX --alter --topic XXXX --config retention.ms=86400000
The above is used to set the log retention time specific to the topic. But how can we specify the offset retention in the query.

A: Committed consumer offsets for all consumers and all topics are stored in a single internal "__consumer_offsets" topic. Therefore you cannot control offset retention individually per topic, I'm afraid.
NB. I see this can be problematic for the case when there are no messages for prolonged periods of time on one of your topics' partitions.
I found the following ticket that can be of help:
https://issues.apache.org/jira/browse/KAFKA-3806
The first comment suggests to commit offsets even in the case the consumer is making no progress (there are no new messages arriving for a given partition), to avoid this exact problem:

you would want to keep committing the offsets even though they are not changing

A: I think you're looking for log.retention.bytes.
That there is no data at all within the retention period is however something you should fix. Either by decreasing the number of partitions or use another algorithm to create the key.

A: You can configure offset retention in server.properties using the parameter "offsets.retention.minutes". Default value is 1440
Offset retention is system wide so you cannot set it on an individual topic level


text:
Q: Manifest malformed? Ive got error "manifest malformes" when I install app. How to repair this?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.barwnikk.android.l2sd"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="11" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:label="@string/app_name"
        android:name=".MainActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver
        android:process=".OnModifyApp" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
</application>
</manifest>

A: You need android:name="something" in the <receiver />.

A: Change:
 <receiver
        android:process=".OnModifyApp" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

to
<receiver
        android:name=".OnModifyApp" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

A: I think you need     android:name field instead of android:process in the receiver tag

A: For me it was the problem with the meta-data, where I added the 'usb.attached' thingy. Deleting that line fixed the error.


text:
Q: I/flutter (12815): NoSuchMethodError: Class 'AuthResult' has no instance getter 'uid' i have an error to have the user's Id .
the Code is:
import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/cupertino.dart';
class UserManagement {

  Firestore db = Firestore.instance;
  var ui = db.currentUser();

  storeNewUser(user, context) {
    db.collection('/users').add({
    'email': 'thee',
    'uid': ui;
    }).then((value) {
      Navigator.pushNamed(context, 'Home');
    }).catchError((e) {
      print(e);
    });
  }
}

A: The Firestore singleton instance doesn't have a property or method call currentUser.  You might be thinking of Firebase Authentication instead.

*

*https://pub.dev/documentation/firebase_auth/latest/firebase_auth/FirebaseAuth/currentUser.html

*How to get the current user id from Firebase in Flutter

*https://medium.com/@nils.backe/firebase-authentication-in-flutter-4b7aa9627046


text:
Q: In Qgrid, is there a way to apply a default row filter when displaying the table I cannot find in the documentation a way to show the qgrid table associated with my dataframe pre-filtered
Imagine I have a dataframe like:
df_types = pd.DataFrame({
'A' : 1.,
'B' : pd.Series(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
           '2013-01-05', '2013-01-06', '2013-01-07', '2013-01-08', '2013-01-09'],index=list(range(9)),dtype='datetime64[ns]'),
'C' : pd.Series(randn(9),index=list(range(9)),dtype='float32'),
'D' : np.array([3] * 9,dtype='int32'),
'E' : pd.Categorical(["washington", "adams", "washington", "madison", "lincoln","jefferson", "hamilton", "roosevelt", "kennedy"]),
'F' : ["foo", "bar", "buzz", "bippity","boppity", "foo", "foo", "bar", "zoo"] })

and initially when displaying the table I only want to show the rows with column "F" equal to fooor bar instead of all (but still have the possibility to choose the others in the qgrid header)

A: After read some test file on qgrid github. The code below might help. However, the visible row looks different comparing to clicking filter.
qw = qgrid.show_grid(df_types, show_toolbar=True)
qw._handle_qgrid_msg_helper({
        'type': 'show_filter_dropdown',
        'field': 'F',
        'search_val': 'bar'
    })
qw._handle_qgrid_msg_helper({
        'field': "F",
        'filter_info': {
            'field': "F",
            'selected': [0],
            'type': "text",
            'excluded': []
        },
        'type': "change_filter"
    })


text:
Q: Displaying input on JTable I want to display the data on JTable for every button press. Before that, the button will create and store data to the List and should display the data on the table. But, only the creation and data storing is working and the data is not displayed. What should I do to display the data on the table.
This is the abstract model I made to fill my table.
import javax.swing.JList;
import javax.swing.table.AbstractTableModel;
import com.main.Products;
import java.util.List;

public class CartTableModel extends AbstractTableModel{
    List<Products> productList;

    private final String[] columnNames = new String[] {
            "Product:", "ID:", "Variant:", "Size:","Unit Price:","Quantity:","Unit Total:"
    };
    private Class[] columnClass = new Class[] {
        String.class, Integer.class, String.class, String.class, Double.class, Integer.class, Double.class
    };

    public CartTableModel(List<ProductInfo> productList)
    {
        this.productList = productList;
    }
   public String getColumnName(int column)
    {
        return columnNames[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex)
    {
        return columnClass[columnIndex];
    }

    @Override
    public int getColumnCount()
    {
        return columnNames.length;
    }

    @Override
    public int getRowCount()
    {
        return productList.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex)
    {
        Products row = productList.get(rowIndex);
        if(0 == columnIndex) {
            return row.getProductName();
        }
        else if(1 == columnIndex) {
            return row.getProductID();
        }
        else if(2 == columnIndex) {
            return row.getVariant();
        }
        else if(3 == columnIndex) {
            return row.getSize();
        }
        else if(4 == columnIndex){
            return row.getUnitPrice();
        }
        else if(5 == columnIndex){
            return row.getQuantity();
        }
        else if(6 == columnIndex){
            return row.getTotal();
        }
        return null;
    }

     @Override
    public boolean isCellEditable(int rowIndex, int columnIndex)
    {
        return true;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    {
        Products row = productList.get(rowIndex);
        if(0 == columnIndex) {
            row.setProductName((String) aValue);
        }
        else if(1 == columnIndex) {
            row.setProductID((int) aValue);
        }
        else if(2 == columnIndex) {
            row.setVariant((String) aValue);
        }
        else if(3 == columnIndex) {
            row.setSize((String) aValue);
        }
        else if(4 == columnIndex){
            row.setUnitPrice((double) aValue);
        }
        else if(5 == columnIndex){
            row.setQuantity((int) aValue);
        }
    }

}

This is how the JTable is created:
CartTableModel model = new CartTableModel(productList);
JTable cartTable = new JTable(model);

Also, This is how the data is created:
public void actionPerformed(ActionEvent e) {
        if(e.getSource() == coconutPieBtn){
            cart.addProduct(new Product("Coconut Creamy Pie", 101,"Pastry","Med",79.99));

        }
    }

A: fireTableCellUpdated(productList.size(), columnNames.length)

The row/column values you specify are wrong for two reasons:

*

*you always use the same value no matter what cell you update and

*java indexes are 0 based, so you are referring to a row/column that doesn't exist.

Just use:
fireTableCellUpdated(rowIndex, columnIndex)

Also:
cart.addProduct(new Product("Coconut Creamy Pie", 101,"Pastry","Med",79.99));

is wrong. Once the model is created you need to add the new Product to the CartTableModel, NOT the List.
So you need to create a method in your CartTableModel to dynamically add products.
The basic code would be:
public void addProduct(Product product)
{
    insertProduct(getRowCount(), product);
}

public void insertProduct(int row, Product product)
{
    products.add(row, product);
    fireTableRowsInserted(row, row);
}

Check out Row Table Model for a complete example of creating your own custom TableModel with methods for dynamically updating the model.


text:
Q: OpenCart - Form character limit OpenCart 1.5.1.3 I have tried putting some suggestion into play, but they do not seem to work with OpenCart<?php } elseif ($field['type'] == 'textarea') { ?>
                            <textarea name="<?php echo $key; ?>" style="width: 40%; height: 50px"><?php echo ${$key}; ?></textarea><br />
It's complicated by the factor there are more than one textarea, and I want to be able to set the limit for specific one "message"

A: have a look here:

*

*http://unwrongest.com/projects/limit/

*http://www.ajaxray.com/blog/2007/11/09/interactive-character-limit-for-textarea-using-jquery/

*limit how many characters can be pasted in textarea


text:
Q: go-sqlite3 compiler arguments for cross compile OSX to linux https://github.com/mattn/go-sqlite3/
Can't find the correct go build compiler arguments for OSX to linux using the clang compiler, help greatly appreciated thx
% env GOOS=linux CGO_ENABLED=1 go build -ldflags "-linkmode external -extldflags -static"
# runtime/cgo
ld: unknown option: --build-id=none
clang: error: linker command failed with exit code 1 (use -v to see invocation)

% env GOOS=linux CGO_ENABLED=1 go build
# runtime/cgo
ld: unknown option: --build-id=none
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Note that a plain go build without cross compiling works


text:
Q: Select parent rows and include cost of children I have a WORKORDER table that has parent and child WOs in it:
with workorder as (
select 'WO37342' as wonum,      null as parent, 297.36 as actlabcost, 200 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
union all
select 'WO37427' as wonum, 'WO37342' as parent,  99.12 as actlabcost,   0 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
union all
select 'WO37429' as wonum, 'WO37342' as parent,  99.12 as actlabcost, 100 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
)
select
    *
from
    workorder

 WONUM   PARENT  ACTLABCOST ACTMATCOST ACTSERVCOST ACTTOOLCOST
 ------- ------- ---------- ---------- ----------- -----------
 WO37342             297.36        200           0           0
 WO37427 WO37342      99.12          0           0           0
 WO37429 WO37342      99.12        100           0           0

I want to select the parent rows and include the cost of the children in the parents:
 WONUM    ACTLABCOST ACTMATCOST ACTSERVCOST ACTTOOLCOST
 ------- ----------- ---------- ----------- -----------
 WO37342       495.6        300           0           0

Is there a concise way of doing this with Oracle 18c SQL?

A: That ability was available in Oracle 7; maybe earlier. ( doc )

*

*Use a hierarchical query (in a CTE/sub-query) to find the children and grandchildren.

*SUM() the values when you GROUP BY the parent wonum.

with workorder as (
    select 'WO37342' as wonum,      null as parent, 297.36 as actlabcost, 200 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
    union all
    select 'WO37427' as wonum, 'WO37342' as parent,  99.12 as actlabcost,   0 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
    union all
    select 'WO37429' as wonum, 'WO37342' as parent,  99.12 as actlabcost, 100 as actmatcost, 0 as actservcost, 0 as acttoolcost from dual
), hier as (
    select connect_by_root( wonum ) parent_wonum
        ,level lv
        ,a.*
    from workorder a
    start with a.parent is null
    connect by a.parent = prior(a.wonum)
)
select parent_wonum
    ,listagg(wonum,',') within group (order by lv, wonum) list_wo
    ,sum( actlabcost ) actlabcost
    ,sum( actmatcost ) actmatcost
    ,sum( actservcost ) actservcost
    ,sum( acttoolcost ) acttoolcost
from hier
group by parent_wonum


text:
Q: PHP Form Validation and POST variables I'm new to PHP and I'm trying some form validation. I have the following code:
I submit a form and submit the data to an SQL statement if it passes validation.  If the form is valid, it redirects to an external success page.
What I can't do is get the original post variables onto the success page. How could I do this please?  My code is below:
PHP:

<?php

$firstnameErr = $emailErr = $lastnameErr = $gradeErr = $roleErr = "";
$firstname = $email = $lastname = $grade = $role = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["firstname"])) {
        $firstnameErr = "First name is required";
    } else {
        $firstname = user_input($_POST["firstname"]);
    }

    if (empty($_POST["lastname"])) {
        $lastnameErr = "Last mame is required";
    } else {
        $lastname = user_input($_POST["lastname"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = user_input($_POST["email"]);
    }

    if (empty($_POST["grade"])) {
        $gradeErr = "Grade is required";
    } else {
        $grade = user_input($_POST["grade"]);
    }

    if (empty($_POST["role"])) {
        $roleErr = "Role is required";
    } else {
        $role = user_input($_POST["role"]);
    }

    if($firstnameErr == '' && $emailErr == '' && $lastnameErr == '' && $gradeErr == '' && $roleErr == ''){

        $stmt = $conn->prepare("INSERT INTO `Tom`.`staff_details` (`first_name`, `surname`, `role`, `grade`,`email`) VALUES ('$firstname', '$lastname','$role', '$grade','$email');");
        $stmt->execute();
        header('Location: staff_added.php');
        exit();
    };

}

function user_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>

HTML:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <fieldset>

* required field

        First name:<input type="text" name="firstname" />
        * <?php echo $firstnameErr;?>

        Last name:<input type="text" name="lastname" />
        * <?php echo $lastnameErr;?>

        Role:<input type="text" name="role" />
        * <?php echo $roleErr;?>

        Grade:<input type="text" name="grade" />
        * <?php echo $gradeErr;?>

        Email:<input type="text" name="email" />
        * <?php echo $emailErr;?>

        <input class="standard_submit" type="submit" value="Save" id="submit_search_button">
    </fieldset>

</form>

I would like those variables to move across to the staff_added.php page so that I can print them back to the user.  I've done some reading over this but as far, it's not making much sense.
Any help would be appreciated.
Thank you

A: Using prepared statements you should be looking at an approach like this perhaps rather than directly embedding variables in the sql.
<?php
    function user_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    $firstname = $email = $lastname = $grade = $role = false;

    if( $_SERVER["REQUEST_METHOD"] == "POST" ) {
        $errors=array();

        if( empty($_POST["firstname"])) $errors[] = "First name is required";
        else $firstname = user_input( $_POST["firstname"] );

        if( empty($_POST["lastname"])) $errors[] = "Last mame is required";
        else $lastname = user_input($_POST["lastname"]);

        if( empty($_POST["email"])) $errors[] = "Email is required";
        else $email = user_input($_POST["email"]);

        if( empty($_POST["grade"]) ) $errors[] = "Grade is required";
        else $grade = user_input($_POST["grade"]);

        if( empty($_POST["role"])) $errors[] = "Role is required";
        else $role = user_input( $_POST["role"] );

        if( empty( $errors ) ){

            $stmt = $conn->prepare("INSERT INTO `Tom`.`staff_details` (`first_name`, `surname`, `role`, `grade`,`email`) VALUES (?,?,?,?,?);");
            if( $stmt ){
                $stmt->bind_param('sssss',$firstname,$lastname,$role,$grade,$email);
                $stmt->execute();

                exit( header( 'Location: staff_added.php' ) );
            } else { echo 'statement failed'; }

        } else {
            foreach( $errors as $error )echo $error . '
';
        }

    }
?>

A: You can store the variables in a SESSION object and then will be available from everywhere :
<?php
session_start();
//other code...
$_SESSION["role"] = $role;
//other code...
?>


text:
Q: LaunchDarkly: multi-platform feature flagging and branching questions Looking at LaunchDarkly for feature flagging across our enterprise apps.
Two questions:
1) I'm concerned about being able to effectively flag features across our Java back end and React front ends (2 of them). What are some strategies that people use to define features appropriately so that they are easy to manage across multiple applications/platforms?
2) Have you replaced most/all of your git / Bitbucket / ?? branching workflow with feature flags and purely trunk - based development? If not, have you made significant changes to your existing git / Bitbucket branching strategy?

A: Disclamer: I work at DevCycle
I'm a few years late, but, I really wanted to make sure anyone finding their way to this question has a little more information.
1) While levlaz provided an answer explaining that you should put your management as far up the stack as possible, I don't necessarily agree that this is the best approach to consider first.
Consider this: A simple setup of a single feature across multiple platforms
Within DevCycle (and others), when you create a Feature, it is available across all platforms and the API.
You simply request the features for a user on any platform, and if the user qualifies, you'll receive it. There is no extra setup necessary to enable it on various platforms.
This means that if a feature is meant to be accessed on either your Java backend or React frontend, you can be guaranteed that the feature will be available at the correct times for the correct user/service regardless of where you call it from.
In short: one single Feature is managed across all platforms in one spot, with one toggle (if desired).
Another Approach: A single feature across multiple platform with different toggles or use cases.
You could very easily simply create multiple flags for each individual platform a feature is meant to be available on, and manage each individually. However, this isn't entirely necessary!
Within a feature setup, you can simply have two separate rules defining different variations being delivered to each platform. For example, you can set up a simple rule which ensures that Java will receive the feature, but React would not.

A unique DevCycle approach: Managing multiple platforms independently.
Here is something DevCycle offers that would may handle your use case in a unique way:
Imagine every single time you create a feature, both a Java and React version of that feature are created.
These platforms would be managed separately within each feature, meaning that there is no potential of any accidental feature data bleeding between platforms in event that a feature doesn't exist on one platform but it does on another.

You can set up each platform as an entirely separate entity, meaning they would use different SDK keys, and all targeting will always be separate.
In the example above for example, the feature would be entirely disabled and not available in any Java SDKs calling out to DevCycle, but it would be available in React.
tl;dr
It's up to you how you want to manage things across platforms. DevCycle makes it easy to do this however you'd like: have all features across all platforms, splitting up your platforms, or just choosing to target differently depending on the feature.
2) Like levlaz said, that is the ideal, but you'll likely never want to achieve fully trunk-based nirvana, as there are a lot of use cases for having various environments and paths for your team to take in various scenarios.
That said, we've seen a lot of folks successfully get REALLY close by using Feature Flags.
I wouldn't suggest removing your build pipelines and CI/CD in favor of feature flags, instead, feature flags enhance those.
For example, with feature flags, you can remove the concept of feature branches and large feature pull requests. Instead, ensure that everything that ever gets put into production is always behind a feature flag. To ensure this happens, you can use workflow tools like github actionsthat do these safety checks for you. With these guards in place, you should now always be able to simply push through to prod without any concerns and run your deploy scripts on each merge. Then you can just target your internal / QA users for testing, and not worry about things hitting prod users!
You may still want to have some sort of disaster recovery environment and local environments, so never truly hitting a pure trunk, but you can get close!

A: [Disclamer: I work at LaunchDarkly]
For your first question, my general recommendation is to put flags as "high up on the stack" as possible. At the end of the day, you are making a decision somewhere. Where you put that decision point is entirely up to you. Within LaunchDarkly the flags are agnostic to the implementation so a single flag can live on the server, mobile, and client-side without any issues. Keep things simple.
For your second question, in practice, it is very rare to see teams fully make the switch to trunk-based development. This is the goal of 99% of the teams that I work with but depending on if you have a greenfield or a brownfield project the complexity of making the switch can be not worth the effort.
Lastly, Our CTO wrote a book this year called "Effective Feature Management"[1]. If you have not heard of this, I would recommend you take a look. I think you'll find some great insights there.
https://launchdarkly.com/effective-feature-management-ebook/


text:
Q: Play: How to validate Json Let's suppose we have the following JSON snippet...
{
  "name": "Joe",
  "surname": "Cocker",
  "email": "joe.cocker@gmail.com"
}

... and want to validate it:
object MyObject {

  def validate(jsValue: JsValue) = myReads.reads(jsValue)

  private val myReads: Reads[(String, String, String)] = (
    (__ \ 'name).read[String] ~
    (__ \ 'surname).read[String] ~
    (__ \ 'email).read(email)
  ) tupled
}

myReads.reads(jsValue) returns either JsFailure or JsSuccess(("Joe", "Cocker", "joe.cocker@gmail.com"))... but in case of success I don't want my input JSON be transformed into a tuple... I just want to validate it and keep as is. Is that possible?

A: So, it sounds like you want a Reads[JsValue]?
object MyObject {

  def validate(jsValue: JsValue) = myReads.reads(jsValue)

  private val myReads: Reads[JsValue] =
    (__ \ 'name).read[String] ~>
    (__ \ 'surname).read[String] ~>
    (__ \ 'email).read(email) ~>
    implicitly[Reads[JsValue]]
}

To explain what's happening here, the ~> operator is an alias for andKeep, which essentially means "if the previous operation was successful, apply the following operation and keep its result, but not the result of the previous one".  It differs from ~, which is an alias for and, in that and combines the two results together with a function (in your case, converting it to a tuple).
Another thing that and does is it merges failures.  This may actually be useful to you, in which case, you may want to do this:
object MyObject {

  def validate(jsValue: JsValue) = myReads.reads(jsValue)

  private val myReads: Reads[JsValue] = (
    (__ \ 'name).read[String] ~
    (__ \ 'surname).read[String] ~
    (__ \ 'email).read(email)
  ).tupled ~> implicitly[Reads[JsValue]]
}

This differs from the above, in that failures from parsing name, surname and email, are all combined together, so if for example, you only sent a name property, the failure object will say that surname and email were missing, whereas in the other solution, it would stop parsing as soon as it found that surname was missing and just return that as the message.

A: If you don't want to define the extra reader needed to implement James' answer, you can do what Chris suggests in the comments with a simple :
def validate(jsValue: JsValue) = myReads.reads(jsValue) map(_=>jsValue)


text:
Q: Exception in servicemix while i try to make javax.ws.rs.core.Response I hope on your help with that question. I use servicemix to work with my jar.
With my dependency
       <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxrs</artifactId>
        <version>3.1.4</version>
        <scope>provided</scope>
       </dependency>

my xml looks like
<bean name="controller" class="first.rest.service.TestService"></bean>

<jaxrs:server id="server" address="http://0.0.0.0:9001/">
    <jaxrs:serviceBeans>
        <ref bean="controller"/>
    </jaxrs:serviceBeans>
</jaxrs:server>

I try to make simple class with 1 method
@POST
@Path("/1")
public Response test(@HeaderParam("Content-Length") int size) {

    Response response = Response.status(Response.Status.BAD_REQUEST).entity("unknown method").build();
    return response;
}

And I get Exception on the line before "return response";
org.apache.cxf.interceptor.Fault: java.lang.ClassNotFoundException: org.glassfish.jersey.internal.RuntimeDelegateImpl not found by javax.ws.rs-api [497]
at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:162)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:128)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:200)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:99)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:251)
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:234)
at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:70)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1088)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1024)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.glassfish.jersey.internal.RuntimeDelegateImpl not found by javax.ws.rs-api [497]
at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:154)
at javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:121)
at javax.ws.rs.core.Response$ResponseBuilder.newInstance(Response.java:864)
at javax.ws.rs.core.Response.status(Response.java:592)
at javax.ws.rs.core.Response.status(Response.java:603)
at first.rest.service.TestService.test(TestService.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
... 26 more
Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.internal.RuntimeDelegateImpl not found by javax.ws.rs-api [497]
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1532)
at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1955)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at javax.ws.rs.ext.FactoryFinder.newInstance(FactoryFinder.java:111)
at javax.ws.rs.ext.FactoryFinder.find(FactoryFinder.java:209)
at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:136)
... 37 more

While I was testing my code only with SpringBoot, I haven`t any error, but now, when I try to use it on Servicemix with cxf I get exceptions.
Even if I add any  The exception is generated anyway.
I try my service with Postman. On the server I had javax.annotation-api-1.2 , so ... error happens too

A: It is strange but the error stopped to appear after I added getter in me controller TestService.class.  It seems that cxf use getter to get some information from class


text:
Q: While click on button from one row of datagrid hide buttons on other row I have one DataGrid and each row of DataGrid contains four buttons.
My screen looks like this. Suppose I click on the start button of Add then I Want all buttons on other rows like Remove, Update and Delete hide until I click on the done button of Add and remove that Add row from DataGrid after processing finished.
My other functionality working fine but the only problem like I click on Add row then also other buttons on other row is clickable so I want to hide that.
Please help me to solve this problem
 <DataGrid Grid.Row="3" Grid.ColumnSpan="2" Name="gridview" Background="#b5d2fc" IsReadOnly="True" ItemsSource="{Binding}" HorizontalScrollBarVisibility="Auto"
         SelectionMode="Single" SelectionUnit="FullRow" VerticalScrollBarVisibility="Auto" Loaded="gridview_Loaded"
        CanUserDeleteRows="False" CanUserAddRows="False" CanUserResizeRows="False"  VerticalAlignment="Top"  AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn MaxWidth="155" Width="155" Binding="{Binding [Task]}" Header="Name"  />
            <DataGridTemplateColumn MaxWidth="30" MinWidth="30">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button x:Name="Start" Content="Play" Click="Button_Click" IsEnabled="{Binding IsEnableButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" VerticalAlignment="Top" Foreground="Black" Background="White"  Height="25"  Width="30" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn >
            <DataGridTemplateColumn MaxWidth="30" MinWidth="30">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button x:Name="Pause" Content="Pause" Click="Button_Click" IsEnabled="{Binding IsEnableButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" VerticalAlignment="Top" Foreground="Black" Background="White"  Height="25"  Width="30" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn MaxWidth="30" MinWidth="30">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button x:Name="Stop" Content="Stop"   Foreground="Black" Click="Button_Click" IsEnabled="{Binding IsEnableButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" VerticalAlignment="Top" Background="White" Height="25"  Width="30" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn MaxWidth="30" MinWidth="30">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button x:Name="Finish" Content="Finish"   Foreground="Black" Click="Button_Click" IsEnabled="{Binding IsEnableButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" VerticalAlignment="Top" Background="White" Height="25"  Width="30" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

This is my xmal code

A: You can achieve this by binding IsEnabled property in button control.
xaml snippet:
<DataGrid Name="MyGrid"  AutoGenerateColumns="False" Loaded="MyGrid_Loaded" Height="250"  >
<DataGrid.Columns>
    <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
    <DataGridTemplateColumn Header="B1">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Content="Start" x:Name="Play" Click="Button_Click" IsEnabled="{Binding IsEnableButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Height="20" Width="80"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTemplateColumn Header="B2">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Content="Pause"  x:Name="Pause" Click="Button_Click" IsEnabled="{Binding IsEnableButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Height="20" Width="80"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTemplateColumn Header="B3">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Content="Stop"  x:Name="Stop" Click="Button_Click" IsEnabled="{Binding IsEnableButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Height="20" Width="80"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTemplateColumn Header="B4">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Content="Finish"  x:Name="Finish" Click="Button_Click" IsEnabled="{Binding IsEnableButton, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Height="20" Width="80"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

xaml.cs
                public partial class MainWindow : Window
                {
                    List<TestEnableButton> objtestEnableButton = new List<TestEnableButton>();
                    public MainWindow()
                    {
                        InitializeComponent();
                        this.DataContext = this;
                    }
                    private void MyGrid_Loaded(object sender, RoutedEventArgs e)
                    {
                        objtestEnableButton.Add(new TestEnableButton("A1", true, false));
                        objtestEnableButton.Add(new TestEnableButton("A2", true, false));
                        objtestEnableButton.Add(new TestEnableButton("A3", true, false));
                        objtestEnableButton.Add(new TestEnableButton("A4", true, false));
                        MyGrid.ItemsSource = objtestEnableButton;
                    }

                    bool butFlg = false;
                    private void Button_Click(object sender, RoutedEventArgs e)
                    {
                        var getButtonName = (sender as Button).Name;
                        var currentItem = MyGrid.CurrentItem as TestEnableButton;
                        foreach(var items in objtestEnableButton)
                        {
                            if (items.Name == currentItem.Name)
                            {
                                if (getButtonName == "Play")
                                {
                                    MessageBox.Show("Let's enjoy music...!)");
                                    butFlg = false;
                                }
                                else if (getButtonName == "Pause")
                                {
                                    MessageBox.Show("Pause the music for few minutes...!)"); butFlg = false;
                                }
                                else if (getButtonName == "Stop")
                                {
                                    MessageBox.Show("Stop the music...!)"); butFlg = false;
                                }
                                else if (getButtonName == "Finish")
                                {
                                    MessageBox.Show("End...!)");
                                    items.IsCheckFinish = true;
                                    butFlg = true;
                                }
                            }
                            else
                            {
                                items.IsEnableButton = false;
                            }
                        }

                        if (butFlg)
                        {
                            var itemsCollection = objtestEnableButton.RemoveAll(x => x.IsCheckFinish == true);
                            objtestEnableButton.ForEach(x => x.IsEnableButton = true);
                            MyGrid.ItemsSource = null;
                            MyGrid.ItemsSource = objtestEnableButton;
                        }
                    }
                }
                public class TestEnableButton : INotifyPropertyChanged
                {
                    private string _name;
                    public string Name
                    {
                        get { return _name; }
                        set
                        {
                            _name = value;
                            OnPropertyChanged("Name");
                        }
                    }

                    private bool _IsEnableButton;
                    public bool IsEnableButton
                    {
                        get { return _IsEnableButton; }
                        set
                        {
                            _IsEnableButton = value;
                            OnPropertyChanged("IsEnableButton");
                        }
                    }

                    private bool _IsCheckFinish;
                    public bool IsCheckFinish
                    {
                        get { return _IsCheckFinish; }
                        set
                        {
                            _IsCheckFinish = value;
                            OnPropertyChanged("IsCheckFinish");
                        }
                    }
                    public TestEnableButton(string name, bool isB, bool isCheck)
                    {
                        Name = name;
                        IsEnableButton = isB;
                        IsCheckFinish = isCheck;
                    }

                    public event PropertyChangedEventHandler PropertyChanged;
                    public void OnPropertyChanged(string propertyName)
                    {
                        if (PropertyChanged != null)
                        {
                            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                        }
                    }
                }


text:
Q: Capturing traffic on TCP port programmatically I'm writing a mac application what should record the traffic on the port 37265 of localhost.
While recording the traffic the port 37265 is used by calabash to run automated test of iPhone apps in iPhone simulator.
Calabash tests are generating http communication on port 37265 and I would like to process that communication after the test finish.
Can you give me hints how to code such a port traffic recorder?
It is very important that I need to capture the communication programmatically not by Wireshark or other software!

A: If I understand you correctly, you want to process the HTTP communication when testing with calabash.
Instead of coding this functionality, you could use a packet sniffer for this, e.g. WireShark.
After completing your testing with calabash, you can stop the network capture and you can filter on your specified port, e.g. with DisplayFilters.

A: So far it looks the best solution will be to call tcpdump from my code with a filter on the port 37265 and on TCP packets.
The final solution looks like this:
_dumpTask = [[NSTask alloc] init];
[_dumpTask setLaunchPath: @"/usr/sbin/tcpdump"];
[_dumpTask setArguments: @[@"-i", @"lo0", @"-s", @"0", @"-B", @"52428", @"-w", @"/Users/user/Desktop/dump.pcap", @"-v", @"port", @"37265", @"and", @"tcp"]];

NSPipe *pipe;
pipe = [NSPipe pipe];
[_dumpTask setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[_dumpTask launch];

NSData *data;
data = [file readDataToEndOfFile];
NSString *response =  [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"%@", response);


text:
Q: Using \only<#> to change text color causes spacing issues Hello and thank you in advance for your help!
I'm comparing the following two commands:

*

*This is a \only<1>{test}\only<2>{\textcolor{red}{test}}.

*$\only<1>{\max_{(x,y)}}\only<2>{\textcolor{red}{\max_{(x,y)}}}$
The first one works fine, and makes the text turn red.
The second one also makes the text turn red. However, it causes a small shift in the spacing. I can't figure out what is causing this shift, has anyone else run into this problem before?
Is it problems with the math environment?

A: Please always post complete documents not just fragments.
The whatsit nodes needed for \only cause math atoms in math mode that can affect the spacing. Easiest is to put an empty math atom {} before the \max in both cases.
\documentclass{beamer}
\begin{document}

\begin{frame}{}

    This is a \only<1>{test}\only<2>{\textcolor{red}{test}}.

    $\only<1>{{}\max_{(x,y)}}\only<2>{\textcolor{red}{{}\max_{(x,y)}}}$

\end{frame}

\end{document}

A: Another option is to use math mode for each expression separately (this seems (at least to me) more syntactically correct):
\documentclass{beamer}
\begin{document}

\begin{frame}

This is a \only<1>{test}\only<2>{\textcolor{red}{test}}.

\only<1>{$\max_{(x,y)}$}\only<2>{\textcolor{red}{$\max_{(x,y)}$}}

\end{frame}

\end{document}


text:
Q: Is there a bijection between $\mathbb{Q}$ and $\mathbb{Q}_{>0}$?
Is there a bijection between $\mathbb{Q}$ and $\mathbb{Q}_{>0}$?

For $\mathbb{R}$, we have the exponential function. Is there also a bijection $f: \mathbb{Q} \to \mathbb{Q}_{>0}$ or to $\mathbb{Q}_{\geq 0}$?

A: The function $f:\mathbb Q\to\mathbb Q_{\gt0}$ defined by $f(x)=x+1$ if $x\geqslant0$ and $f(x)=1/(1-x)$ if $x\lt0$, sends $0$ to $1$ and sends bijectively $\mathbb Q_{\gt0}$ to $\mathbb Q_{\gt1}$ and $\mathbb Q_{\lt0}$ to $\mathbb Q\cap(0,1)$. Thus, $f$ is bijective.
For a bijection $g:\mathbb Q_{\gt0}\to\mathbb Q_{\geqslant0}$, consider $g(x)=x-1$ if $x$ is an integer and $g(x)=x$ otherwise.
For a bijection from $\mathbb Q$ to $\mathbb Q_{\geqslant0}$, consider $h=g\circ f$, that is, $h(x)=1/(1-x)$ if $x$ is negative, $h(x)=x$ if $x$ is a nonnegative integer and $h(x)=x+1$ if $x$ is positive and not an integer.

A: EDIT: If $x\ge0$, then $f(x)=x+[x]$; if $x\lt0$, then $f(x)=x-3[x]-1$. Here, $[x]$ is the integer part of $x$, the largest integer not exceeding $x$ (also known as the "floor" of $x$).
The following, incorrect answer is kept so as not to make the comments look odd:
If $x=a/b$, $b\gt0$, let $f(x)=a/(2b+1)$ if $a\ge0$, $f(x)=(2|a|-1)/2b$ if $a\lt0$.

A: The Stern-Brocot tree $\mathcal T$ is an infinite binary search tree containing all positive rationals. It's easy to create its counterpart $\mathcal T^{-}$ for all negative rationals.
Create a tree with 0 as root, $\mathcal T^{-}$ as the left subtree and $\mathcal T^{+}$ as the right subtree. This is also an infinite binary search tree, which is trivially isomorphic to $\mathcal T$, so there's an order isomorphism between $\mathbb Q^{+}$ and $\mathbb Q$.

A: A bijection from $\mathbb N$ to $\mathbb Q_{\ge0}$ :

*

*$f(0)=0$

*$f(1)=1$

*$f(2n)=f(n)+1$

*$f(2n+1) = \frac{1}{f(2n)}$

You obtain $0,1,2,\frac{1}{2},3,\frac{1}{3},\frac{3}{2},\frac{2}{3},4,\frac{1}{4},\frac{4}{3},\frac{3}{4},\frac{5}{2},\frac{2}{5},\dots$
A bijection from $\mathbb N$ to $\mathbb Q$ :

*

*$g(0)=0$

*$g(2n+1)=f(n+1)$

*$g(2n+2)=-f(n+1)$

You obtain $0,1,-1,2,-2,\frac{1}{2},-\frac{1}{2},3,-3,\dots$
Compose those two bijections : $f \circ g^{-1}$ to obtain a bijection from $\mathbb Q$ to $\mathbb Q_{\ge 0}$
Or consider $x\mapsto f(g^{-1}(x)+1)$ to obtain a bijection from $\mathbb Q$ to $\mathbb Q_{>0}$

A: It is well known that there is an injection of $\mathbb Q$ into $\mathbb N$ (Cantor diagonal argument) while the inclusion $\mathbb N \subset \mathbb Q_+ \subset \mathbb Q$ is an injection in the opposite direction. By Cantor-Bernstein theorem there exist bijection between the three sets (i.e. all three sets have the same cardinality).


text:
Q: installing packages on Mac OS X Hi I'm currently on Mac OS X Lion. I had a question that when I install a package like "pip" or "node", which are command line applications or packages. I cannot run them by simply type "pip" or "node'. I have to sudo to run them. Without sudo, it doesn't even find the commands. Is there solutions to this?
I was using Ubuntu before and I didn't have issues like this.

A: You need to alter your PATH in order to point at the directory holding the new executables.  For command-line apps, the best place to quickly change your PATH is to edit your .bash_profile file in your user home directory.


text:
Q: Sum of two irrational numbers being rational or irrational I am currently doing a project on irrational and transcendental numbers and part of this project requires me to look at sums and products of irrational numbers.
I am aware that the sum of 2 irrational numbers can be rational or irrational but was wondering if anyone knew of a definite way to look at the numbers and say if their sum/product will be rational/irrational. Is there some sort of theorem than can be applied or is the only way of knowing just working it out?
Thanks in advance for any help.

A: "requires me to look at sums and products of irrational numbers."
so you don't ask for transcendental?
The sum or product of two irrational algebraic numbers is not necessarily irrational. Counterexamples:
$$
(2 +\sqrt 2)+(2 -\sqrt 2)= 4\\
(2 +\sqrt 2)(2 -\sqrt 2)= 2
$$

A: No, there is not. If there was, we would know whether $e+\pi$ is rational or not. But, in fact, that's an open problem.


text:
Q: Can a project adopt AngularJS as its template engine while being a non-MVC project? I use Pure as the template engine for my current project. It is, however, rather minimal in terms of what it offers. I am in need for a template engine that allows "conditional statements". AngularJS is a candidate that I am interested in. I have been reading a lot about the MVC framework lately and it seems quite interesting. If I have the resources to spare later on, I would definitely want to try to apply AngularJS on my project. For now, I just want to use AngularJS's template engine without converting my project to MVC. Is this viable? If so, please suggest any good resources for me to learn its template language. Thanks.

A: You can choose to only use the template bit in angular, yes. Check the angular website for tutorials. It's quite straight forward.


text:
Q: canvas background image is getting stretched I want this image in my canvas but it is getting stretched and not fitting the box properly. What am I missing?
Here is my code:
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

var img = new Image();
img.src = "my image url";

img.onload = function(){
    ctx.drawImage(img,0,0);
}

Please check this image: http://i.stack.imgur.com/RMZM2.png
What I want is my logo fit in the canvas box.
Here is my whole logo: http://i.stack.imgur.com/4jFjM.png

A: If you want to your image to fit with in the canvas-
ctx.drawImage(img,0,0,imgWidth,imgHeight,x,y, canvas.width, canvas.height);

where x and y is the top left position where you want to display your logo. imgWidth and imgHeight are the width and height of your logo respectively.

Refer this image. http://www.html5canvastutorials.com/tutorials/html5-canvas-image-crop/


text:
Q: Updating existing data using PATCH API call I am trying to update some existing data using an API call as shown below:
import requests

url = "https://apisandbox.paylocity.com/api/v2/companies/ABC/employees/123/?grant_type=client_credentials&scope=WebLinkAPI&client_id=client_id&client_secret=client_secret"

payload = {'firstName' : 'Kevin'}
headers = {'Authorization': 'Bearer ACCESS TOKEN'}

response = requests.request("PATCH", url, headers=headers, data=payload)

print(response.text)

This returns back the below message.
{"message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}

What do I need to change to ensure I am able to update the existing data


text:
Q: Move all files / folder within SmartFinderFolder to destination w/ serial / single consecutive operation with AppleScript MacOS Serria Objective: Move all files and files in folders to destination folder and maintain the file structure [files and named folders]. Important for music files in albums.
Functional: Move all listed files in SmartFolder [named] to destinationFolder with serial / consecutive move operation and maintain the same file structure and copy of dataFiles listed in SmartFolder.
Key: All files were obtained for transfer. Normal CMD + A, CMD + C, CMD + V hangs up the computer and the transfer does not initiate. The AppleScript to move each dataObject to destinationPath is all.
Facts: How to reference objects [files, folders] and their proper reference format and accepted path syntax; path or POSIX, and use of alias. Basic operations. I ran an AppleScript to move filePath to pathDestination, and was otherwise successful, and would be nice to known the formalization syntax for path reference.
tell application "Finder"
    move allFiles to destinationFolder
    // recursive/repeat code to loop through all listed files and folder
end tell

Reference: Applescript, show all files with tag
[Moving / selecting listed files from 'smartfolder' containers as active windows and displayLists. It was an alt. solution since AppleScript will not reference the SmartFolder as an object, nor will it dynamically call the listProperty of the SmartFolder object unless called by an unknown or un-reference method or command.

A: Since your main issue, as far as I can tell, seems to be dealing with SmartFolders in AppleScript, which—as you said—cannot be referenced as folder objects, this little snippet might be of help:
    set SmartFolder to "/Users/CK/My Smart Folder.savedSearch"

    tell application "System Events" to get value of property list file SmartFolder
    set {[Scope], Query} to {SearchScopes, RawQuery} of RawQueryDict of result

    set AppleScript's text item delimiters to tab

    set Command to {"mdfind -onlyin", ¬
        quoted form of Scope as text, ¬
        quoted form of Query as text} as text

    set SearchResults to paragraphs of (do shell script Command)
        --> returns a list of posix files
        --> e.g. {"/Users/CK/Downloads/This is file one.txt", ...}

This will return a list of POSIX paths to files that match the search criteria.
I would recommend using System Events rather than Finder to deal with large numbers of files.  It can also handle posix paths without the need to manually coerce them into aliases or whatever.  So, given a posix path, such as the ones returned in the list using the above code snippet, you simply do this:
    set myfile to item 1 of SearchResults
    tell application "System Events" to move myfile to "/Users/CK/Desktop"

Without knowing more details of what your smart folder contains (since some searches could easily return a folder plus the contents of that folder, which you'd have to bear in mind when getting your AppleScript to recurse through the search results), I can't give you more than that.  But, you said your main problems were being unable to handle SmartFolders and not knowing how to reference files/folders.

A: This works for me using the latest version of Sierra.
Set the value of  property moveToNewFolderto the destination folder of your choice
This script creates a "Choose From List" Dialog, allowing you to choose any smart folder which resides on your system.  It will then move all of these files and folders in the chosen smart folder, to your set destination folder.
property savedSearches : (path to home folder as string) & "Library" & ":Saved Searches"
property savedSearchesSubFolders : {}
property namesOfSavedSearchesSubFolders : {}
property selectedSearchFolder : ""
property selectedSearchFolderPath : missing value
property moveTheseItems : missing value
property moveToNewFolder : (path to desktop as text) & "untitled folder" -- change this value to your preferred destination folder

tell application "Finder"
    activate
    delay 0.1 -- may need to adjust delay time value
    open savedSearches
    delay 0.1 -- may need to adjust delay time value
    reveal savedSearches
    delay 0.1 -- may need to adjust delay time value
    select savedSearches
    delay 0.1 -- may need to adjust delay time value
    set current view of Finder window 1 to column view
    delay 0.1 -- may need to adjust delay time value
    tell its Finder window (POSIX path of savedSearches)
        delay 0.1 -- may need to adjust delay time value
        set savedSearchesSubFolders to items
        set namesOfSavedSearchesSubFolders to name of items
        -- Allows to choose any smart folder from a list of all smart folders
        set selectedSearchFolder to choose from list namesOfSavedSearchesSubFolders ¬
            with title ¬
            "Smart Search Folders" with prompt ¬
            "Choose Your Folder" OK button name ¬
            "OK" cancel button name "CANCEL"
        set selectedSearchFolder to selectedSearchFolder as text
        set selectedSearchFolderPath to savedSearches & ":" & selectedSearchFolder
        set selectedSearchFolderPath to selectedSearchFolderPath as string
    end tell
    delay 0.2 -- may need to adjust delay time value
    select selectedSearchFolderPath
    tell Finder window 1
        set defaultView to current view
        set current view to list view
        delay 0.1 -- may need to adjust delay time value
        set current view to defaultView
        delay 0.5 -- may need to adjust delay time value
        tell application "System Events"
            key code 0 using command down
        end tell
    end tell
    set moveTheseItems to selection
end tell

tell application "Finder"
    set resultObject to move moveTheseItems ¬
        to moveToNewFolder ¬
        with replacing
end tell


text:
Q: Как доделать динамическое меню на React? Есть такой код в Header.js :
import React from 'react';
import menuJson from './menu.json'

export class Header extends React.Component {

    render() {

        const menu = JSON.parse(menuJson);

        return (

                //тут должны быть li'шки из menu

        )
    }
}

Никак не могу додумать, как добавить пункты из menu в .navigation.
Это menu.json :
{
  "home" : "#1",
  "pricing" : "#2",
  "about us" : "#3",
  "contact" : "#4"
}

A: Стандартный for .. in справится с этой задачей.
import React from 'react';
import menuJson from './menu.json'

export class Header extends React.Component {
    render() {
        const menu = JSON.parse(menuJson);

        let menuList = []
        for (let menuName in menu) {
            menuList.push(
{menuName}
);
        }

        return (

                {menuList}

        )
    }
}