Q: Change UIButton BorderColor in Storyboard I Set CornerRadius and BorderWidth for UIbutton in User Defined Runtime Attributes. Without adding layer.borderColor it works Well and Display border in black color. But when add layer.borderColor does not work(does not show border).

A: I got answer. Change  borderColor instead of layer.borderColor:

and add this code in .m file:
#import <QuartzCore/QuartzCore.h>
@implementation CALayer (Additions)

- (void)setBorderColorFromUIColor:(UIColor *)color
{
    self.borderColor = color.CGColor;
}

@end

Tick properties in Attribute Inspector

A: The explanation, perhaps being lost in some of the other answers here:
The reason that this property is not being set is that layer.borderColor needs a value with type CGColor.
But only UIColor types can be set via Interface Builder's User Defined Runtime Attributes!
So, you must set a UIColor to a proxy property via Interface Builder, then intercept that call to set the equivalent CGColor to the layer.borderColor property.
This can be accomplished by creating a Category on CALayer, setting the Key Path to a unique new "property" (borderColorFromUIColor), and in the category overriding the corresponding setter (setBorderColorFromUIColor:).

A: Swift 4, Xcode 9.2 - Use IBDesignable and IBInspectable to build custom controls and live preview the design in Interface Builder.
Here is a sample code in Swift, place just below the UIKit in ViewController.swift:
@IBDesignable extension UIButton {

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
        }
        get {
            return layer.cornerRadius
        }
    }

    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }
}

If you go to the Attributes inspectable of the view, you should find these properties visually, edit the properties:

The changes are also reflected in User Defined Runtime Attributes:

Run in build time and Voila! you will see your clear rounded button with border.

A: For Swift:

Swift 3:
extension UIView {

    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }

    @IBInspectable var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }

    @IBInspectable var borderColor: UIColor? {
        get {
            return UIColor(cgColor: layer.borderColor!)
        }
        set {
            layer.borderColor = newValue?.cgColor
        }
    }
}

Swift 2.2:
extension UIView {

    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }

    @IBInspectable var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }

    @IBInspectable var borderColor: UIColor? {
        get {
            return UIColor(CGColor: layer.borderColor!)
        }
        set {
            layer.borderColor = newValue?.CGColor
        }
    }
}

A: This works for me.
Swift 3, Xcode 8.3

CALayer extension:
extension CALayer {
var borderWidthIB: NSNumber {
    get {
        return NSNumber(value: Float(borderWidth))
    }
    set {
        borderWidth = CGFloat(newValue.floatValue)
    }
}
var borderColorIB: UIColor? {
    get {
        return borderColor != nil ? UIColor(cgColor: borderColor!) : nil
    }
    set {
        borderColor = newValue?.cgColor
    }
}
var cornerRadiusIB: NSNumber {
    get {
        return NSNumber(value: Float(cornerRadius))
    }
    set {
        cornerRadius = CGFloat(newValue.floatValue)
    }
}

}

A: There is a much better way to do this!  You should use @IBInspectable.  Check out Mike Woelmer's blog entry here:
https://spin.atomicobject.com/2017/07/18/swift-interface-builder/
It actually adds the feature to IB in Xcode!  Some of the screenshots in other answers make it appear as though the fields exist in IB, but at least in Xcode 9 they do not.  But following his post will add them.

A: In case of Swift, function doesn't work. You'll need a computed property to achieve the desired result:
extension CALayer {
    var borderColorFromUIColor: UIColor {
        get {
            return UIColor(CGColor: self.borderColor!)
        } set {
            self.borderColor = newValue.CGColor
        }
    }
}

A: You have set the data values for the radius and the width set to be a string, but it should properly be to be set to a number, not a string
When you get it working, this will not be visible while looking at the storyboard, but will be when the app is running unless you have taken steps to make it @IBDesigneable.


Q: How to automatically place AutoText in Word styles? I am making a screenplay in Microsoft Office Word 2007, and created various styles to quickly make formatting changes for the various aspects of the screenplay. My character style, for example, appears at the beginning of each line of dialogue in the script, naming the character who will then speak his/her lines.
I would like to insert a number at the beginning of each character line, so that during rehearsals and such, I can call out which line to start from. I don't want to use a list because it indents strangely, and would like to use autotext. In addition, I would like each numbering system to restart at the beginning of each section (scene), to make the dialogue easier. I have never used VBA in Word, but i have some programming skills in Java. How would I accomplish this?
EDIT: I figured it out by using the numbering in the styles, then adjusting the tabs.

A: I think you can use the standard Word functionality:

The screenshot is in German interface. In English, I think, it is named "Page Layout"->"Line Numbers". In the options (the last menu item) it is possible to reset the numbering on each section.


Q: How to subtract the result of a query with a result of another query in c# linq? I want to get records from investment and calculate the sum of Amount from investment_Line where investment_Line.ParentID==investment.Investment.
Subtract the Amount Calculte==d.Amount-Answer
var a = (from investment in _entities.Investments
        where investment.StatusID == 4
        select new
        {
            RefNo = investment.RefNo,
            InvestedAmount = investment.InvestedAmount,
            Amount = investment.InvestedAmount + investment.ProfitAmount,
            InvestmentID = investment.ID,
            UserID = investment.UserID,
            StatusID = investment.StatusID,

        }).ToList();

if (a.Count() != 0)
{
    foreach (var row in a)
    {
        var count = (_entities.Investment_Line.Where(x => x.ParentID == row.InvestmentID)).Count();
        if(count != 0)
        {
            var _group = _entities.Investment_Line.Where(x => x.ParentID == row.InvestmentID).GroupBy(g => g.ParentID).Select(s => new { SumAmount = s.Sum(sum => sum.Amount) });
            double answer = double.ConvertToDouble(_group.Select(x => x.SumAmount));
            var data = (from d in a
                        select new Search.ReadyInvestmentList
                        {
                            RefNo = d.RefNo,
                            InvestedAmount = d.InvestedAmount,
                            TotalAmount = d.Amount,
                            InvestmentID = d.InvestmentID,
                            UserID = d.UserID,
                            StatusID = d.StatusID,
                            Calculate = d.Amount-answer
                        }).ToList();
        }
    }
}

Investment table
+---+--------------------------+--------+-------------+----------------+--------+-------------+----------+
|ID | CreateDate               | UserID |  RefNo      | InvestedAmount | Growth%| ProfitAmount|StatusID  |
+---+--------------------------+--------+-------------+----------------+--------+-------------+----------+
|1  | 2017-01-11 16:39:06.483  | 1      |  BPWM57G2Q2 | 20000          | 30     | 6000        | 4        |
|2  | 2017-01-11 16:49:18.850  | 2      |  BPWM56H2T0 | 10000          | 30     | 3000        | 4        |
|3  | 2017-01-11 17:15:02.667  | 3      |  BPWM56G2L0 | 500            | 30     | 1500        | 1        |
|4  | 2017-01-12 20:22:02.160  | 5      |  BPWM68L2I0 | 500            | 30     | 150         | 2        |
|5  | 2017-01-12 20:25:03.160  | 5      |  BPWM63F2I5 | 2000           | 30     | 600         | 4        |
+---+--------------------------+--------+-------------+----------------+--------+-------------+----------+

Investment_Line table
+----+-------------+-----------+-----------+-------+------------+-----------+
| ID | InvestmentID| InvestorID| AssistorID| Amount| RefNo      |  ParentID |
+----+-------------+-----------+-----------+-------+------------+-----------+
| 1  | 2           | 2         | 1         | 10000 | BPWM56H2T0 |  1        |
| 2  | 3           | 3         | 1         | 5000  | BPWM56G2L0 |  1        |
| 3  | 4           | 5         | 3         | 500   | BPWM68L2I0 |  3        |
+----+-------------+-----------+-----------+-------+------------+-----------+

Required Output
+----+---------+-----------+-------+---------------+------------+-----------+
| InvestmentID | RefNo     | UserID| InvestedAmount| TotalAmount| Calculate |
+--------------+--------------------+--------------+------------+-----------+
| 1            | BPWM57G2Q2| 1     | 20000         | 26000      | 15000     |
| 2            | BPWM56H2T0| 2     | 10000         | 13000      | 0         |
| 5            | BPWM63F2I5| 5     | 2000          | 2600       | 0         |
+----+---------+-----------+-------+-------------- +------------+-----------+

What is the best way to do this?
Please help.

A: Your code will have bad performance if there will be many records in master detail table. Because you will have masterRecordCount * DetailRecordCount nested loop. So it will be better if you group and join in one query
var calculatedlist = from I in _entities.Investments
            join IL in _entities.Investment_Line on I.ID equals IL.ParentID
            group IL by new { I.ID } into g
            select new {
                InvestmentID  = g.Key,
                RefNo      = g.Max(m => m.I.RefNo),
                UserID = g.Max(m => m.I.UserID) ,
                InvestedAmount = g.Max(m => m.I.InvestedAmount) ,
                TotalAmount = g.Max(m => m.I.InvestedAmount) + g.Max(m => m.I.ProfitAmount),
                Calculate  = g.Max(m => m.I.InvestedAmount) + g.Max(m => m.I.ProfitAmount) - g.Sum(m => m.IL.Amount)
            };


Q: access vba hperling wont work  Dim dbs As DAO.Database
 Dim rst As DAO.Recordset

    Set dbs = CurrentDb
    Set rst = dbs.OpenRecordset("יומן תקלות")
    Dim str As String
   rst.MoveFirst

    Do Until rst.EOF
          If IsNull(rst!אישור) Then
               str = rst![מס' תקלה]
               rst.Edit
          rst!אישור = "C:\test\pic\" + str + ".jpg"
          rst.Update
          End If
       rst.MoveNext
    Loop

i have this code and it work perfect
but when im trying to press the hyperlink nothing heppned
the path is ok and also the file name
i tried to rightClick->hyperling->open hyperling and nothng also
please help me

A: If clicking the link throws an error, it is because the link provided is incorrect, but since nothing happens, the problem is probably caused by a wrong datatype in your table.
Go to the design view of your table, and set the datatype to Hyperlink.


Q: Setstate completes after even thou it's in a .then I'm very confused on this.  I know it has to do with the async nature but I'm not able to get this to function the way I need it to.
I need the firebase.set to run.  When that is completed then this.setstate to run, once that is completed the next then to run.
    .then(keyUid => {
      let updatedFamily = {...family, [keyUid]: [firstHousehold, lastHousehold, householdDropdown]};

      this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + keyUid ).set(
        {
            first: firstHousehold,
            last: lastHousehold,
            phone: phone,
            email: email,
            address: address,
            address2: address2,
            city: city,
            zip: zip,
            headOfHousehold: headOfHousehold,
          }, (error) => {
               if(error){
                  console.log(error);
               }
               else{
                    this.setState({ family: updatedFamily }, () => console.log(1));
                }
        })
    })
    .then(newHouseholdUid => {
      console.log(2);
      Object.keys(family).forEach(key => {
        this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + key ).update({
          family: 'howdly'
        })
      });
  })

Currently console.log(2) runs BEFORE console.log(1).  I would expect for this.setstate to resolve before it moves on to the next .then
How can achieve this?

A: React batches state updates for performance reasons.
In your case the state you are setting to updatedFammily, you can use a locally scoped object to get the intermediate results
  let res = {}
  ...

    .then(keyUid => {
  let updatedFamily = {...family, [keyUid]: [firstHousehold, lastHousehold, householdDropdown]};
  res.updatedFamily = updatedFamily;

  this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' + keyUid ).set(
    {
        first: firstHousehold,
        last: lastHousehold,
        phone: phone,
        email: email,
        address: address,
        address2: address2,
        city: city,
        zip: zip,
        headOfHousehold: headOfHousehold,
      }, (error) => {
           if(error){
              console.log(error);
           }
           else{
                this.setState({ family: updatedFamily }, () => console.log(1));
            }
    })
})
.then(() => {
  console.log(2);
  Object.keys(res.updatedFamily).forEach(key => {
    this.props.firebase.db.ref('organization/' + currentOrganization + '/members/' +
   key ).update({
      family: 'howdly'
    })
  });
  })

You can also use async await to get around this but that would require changing bit more,
Hope it helps


Q: Delete a key/value pair from an unordered_map C++ I have two questions. First I have an std::unordered_map<int,Object*> where Object looks like this:
// Object.hpp
class Object {
    public:
        Object();
        ~Object(){};
        int   Id();
        void setId(int i);
    private:
        int id;
};

This unordered_map is put in a class called DataSet which is used as a container to hold all of these objects. In DataSet I want to be able to properly erase a key/value pair given an integer id from Object.
To do this I tried to create an iterator that finds the key by id, and then deletes the pointer to the iterator, and finally erases the key/value pair. It looks like this:
int DataSet::deleteObject(int id)
{
    std::unordered_map<int,Object*>::iterator found_it = objects.find(id);
    if(found_it != objects.end()) {
        delete *found_it;
        objects.erase(found_it);
    }
    return 1;
}

However, when I compile it I get this error:
dataset.cpp:44:9: error: cannot delete expression of type 'value_type'
      (aka 'pair<key_type, mapped_type>')
        delete *found_it;

Is there a correct way to erase the Object at that location?
Second, when writing a clear() method, I realize I can't just do objects.clear(), so I was wondering if there was a way to actually clear the unordered_map.
For example when I used a std::vector I was able to do this:
std::vector<Object *>::reverse_iterator object;
for(object = objects.rbegin(); object < objects.rend(); object++)
    delete(*object);
objects.clear();

But that won't work now for an unordered_map, so what is the right way to do this? The requirements that I am under make it so I can't change Object, or how the unordered_map is set up.

A: The first part of the question is quite simple: the iterator reference the value and a given location which is of type std::pair<int const, Object*>. You can't delete such an object. You'll get the pointer using the second part of the object, e.g.:
delete found_it->second;

However, it is actually quite uncommon and error-prone to take care of this kind of maintenance. You are much better off not storing an Object* but rather a std::unique_ptr<Object>: the std::unique_ptr<Object> will automatically release the object upon destruction. That would also simplify removing an element:
int DataSet::deletObject(int id) {
    return objects.erase(id);
}

When storing std::unique_ptr<Object> you'll probably need to be a bit more verbose when inserting elements into the container, though, e.g.:
objects.insert(std::make_pair(key, std::unique_ptr<Object>(ptr)));

Given that your Object class doesn't have any virtual functions you could probably just store an Object directly, though:
std::unordered_map<int, Object> objects;

A: Dereferencing an unordered_map::iterator produces a unordered_map::value_type&, i.e. pair<const Key, Value>&.
You want
delete found_it->second;
objects.erase(found_it);

Stepping back a bit, are you sure you even need std::unordered_map<int,Object*> instead of std::unordered_map<int,Object>? If you use the latter you wouldn't have to worry about deleteing anything.
If you do need the mapped_type be an Object* you should use std::unordered_map<int,std::unique_ptr<Object>>. Again, this makes it unnecessary to manually delete the values before erasing an entry from the map.
Also, if Object is the base class for whatever types you're going to be adding to the map, don't forget that it needs a virtual destructor.


Q: CUDA atomicAdd failed The following CUDA kernel is supposed to do image slices addition for an 3D image, i.e., you collapse the 3D volume along one dimension and produce one 2D image through doing pixel-wise additions. The image_in data pointer has size 128 * 128 * 128, which was obtained from an ITK::Image using the function GetOutputBuffer(). After reading the ITK documentation, I think we can safely assume that the data pointer points to an segment of continuous memory of the image data, without padding. The image_out is just a 2D image of size 128 * 128, also produced from  an ITK::Image. I included the info about the images just for completeness but the question is more about CUDA atomic and might be very elementary. The code compute the thread id first and project the id into the range of 128 * 128, which means all pixels in the same line along the dimension we perform addition will have the same idx. Then using this idx, atomicAdd was used to update the image_out.
__global__ void add_slices(int* image_in, int* image_out) {
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    int idx = tid % (128 * 128);
    int temp = image_in[tid];

    atomicAdd( &image_out[idx], temp );

}

The way I initialized the image_out is through the following, there are two ways I tried with the similar results:
int* image_out = new int[128 * 128];
for (...) {
    /* assign image_out to zeros */
}

and the one using ITK interface:
out_image->SetRegions(region2d);
out_image->Allocate();
out_image->FillBuffer(0);
// Obtain the data buffer
int* image_out = out_image->GetOutputBuffer();

Then I setup CUDA as the following:
unsigned int size_in = 128 * 128 * 128;
unsigned int size_out = 128 * 128;
int *dev_in;
int *dev_out;
cudaMalloc( (void**)&dev_in, size_in * sizeof(int) );
cudaMalloc( (void**)&dev_out, size_out * sizeof(int));
cudaMemcpy( dev_in, image_in, size_in * sizeof(int), cudaMemcpyHostToDevice );
add_slices<<<size_in/64, 64 >>>(dev_in, dev_out);
cudaMemcpy( image_out, dev_out, size_out * sizeof(int), cudaMemcpyDeviceToHost);

Is there any problem to the above code? The reason why I am seeking help here comes from the frastration that the above code sometimes might produce the right result (once every 50 times I run the code, maybe, I swear I have seen the correct result at least twice), while the rest of the time just produced some garbages. Does the issue comes from the atomicAdd() function? At the beginning my image type was of double, which CUDA doesn't support atomicAdd(double*, double) so I used the code provided by Nvidia as the following
__device__ double atomicAdd(double* address, double val)
{
    unsigned long long int* address_as_ull =
                                          (unsigned long long int*)address;
    unsigned long long int old = *address_as_ull, assumed;
    do {
        assumed = old;
        old = atomicCAS(address_as_ull, assumed,
                        __double_as_longlong(val +
                        __longlong_as_double(assumed)));
    } while (assumed != old);
    return __longlong_as_double(old);
}

Then just for testing purpose I switched all my image to int then the situation was still the same that most of the time garbages while once in a blue moon correct result.
Do I need to turn on some compiling flag? I am using CMAKE to build the project using
find_package(CUDA QUIET REQUIRED)

for the CUDA support. The following is the way I setup the CUDA_NVCC_FLAGS
set(CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS} -arch=sm_30"),

maybe I missed something?
Any suggestion will be greatly appreciated and I will update the question if more info of the code is needed.

A: So it turns out that the solution to this problem is adding the following line to initialize the memory pointed by dev_out.
cudaMemcpy( dev_out, image_out, size_out * sizeof(int), cudaMemcpyHostToDevice );

I forgot to initialize it since I was thinking that it is a output variable and I initialized it on the host.
Just like that talonmies said, it has nothing to do with atomicAdd at all. Both int version and double version of atomicAdd works perfectly. Just remember to initialize your variable on device.


Q: ASP.NET Core 2.1 Referring to ApplicationDbContext from Class Library I have these 2 projects App.ClassLibrary and App.Data
I followed this tutorial https://garywoodfine.com/using-ef-core-in-a-separate-class-library-project/ to move my migrations and models to App.ClassLibrary. One of those steps was to create an ApplicationDbContext in the class library:
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
    public DbSet<Users> Users { get; set; }
    public DbSet<UserRoles> UserRoles { get; set; }
    public DbSet<Applications> Applications { get; set; }
    public DbSet<Roles> Roles { get; set; }
    public DbSet<EventLogs> EventLogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.HasDefaultSchema(schema: DatabaseGlobals.SchemaName);
        modelBuilder.Entity<Users>();
        modelBuilder.Entity<UserRoles>();
        modelBuilder.Entity<Applications>();
        modelBuilder.Entity<Roles>();
        modelBuilder.Entity<EventLogs>();
        base.OnModelCreating(modelBuilder);
    }

    public override int SaveChanges()
    {
        Audit();
        return base.SaveChanges();
    }

    public async Task<int> SaveChangesAsync()
    {
        Audit();
        return await base.SaveChangesAsync();
    }

    private void Audit()
    {
        var entries = ChangeTracker.Entries().Where(x => x.Entity is Users && (x.State == EntityState.Added || x.State == EntityState.Modified));
        foreach (var entry in entries)
        {
            if (entry.State == EntityState.Added)
            {
                ((Users)entry.Entity).CreatedOn = DateTime.UtcNow;
            }
        ((Users)entry.Entity).UpdatedOn = DateTime.UtcNow;
        }
    }
}

In App.Data, I am trying to reference ApplicationDbContext but so far this isn't working
private ApplicationDbContext dbContext = new ApplicationDbContext();

I used to have a similar project in ASP.NET MVC 5 with an ApplicationDBContext like this:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public virtual DbSet<AspNetUsersExtendedDetails> AspNetUsersExtendedDetails { get; set; }
    public virtual DbSet<AspNetApplications> AspNetApplications { get; set; }
    public virtual DbSet<AspNetEventLogs> AspNetEventLogs { get; set; }
    public virtual DbSet<AspNetRolesExtendedDetails> AspNetRolesExtendedDetails { get; set; }
    public virtual DbSet<AspNetUserRolesExtendedDetails> AspNetUserRolesExtendedDetails { get; set; }
    public virtual DbSet<AspNetUserAccessTokens> AspNetUserAccessTokens { get; set; }
    public ApplicationDbContext() : base("ManagementStudio")
    {

    }
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

}

I could use
private ApplicationDbContext dbContext = new ApplicationDbContext();

without any issues but now I'm guessing because of the different versions and framework its not working. Not sure what I can do to get the dbcontext.
EDIT:
This is the error I get in my .Net Core 2.1 App
There is no argument given that corresponds to the required formal parameter 'options' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions)'

A: Your DbContext is fine, but you have to register it with dependency injection and inject it into your classes instead of using new.
Your startup.cs ConfigureServices method should have your database with the connection string.
services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

Then, on the classes you want to use them (like a Controller) you inject it into the constuctor.
public class HomeController : Controller
{
    private readonly ApplicationDbContext _db;

    public HomeController(ApplicationDbContext db)
    {
        _db = db;
    }
}

A: Your ApplicationDbContext should be:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public virtual DbSet<AspNetUsersExtendedDetails> AspNetUsersExtendedDetails { get; set; }
    public virtual DbSet<AspNetApplications> AspNetApplications { get; set; }
    public virtual DbSet<AspNetEventLogs> AspNetEventLogs { get; set; }
    public virtual DbSet<AspNetRolesExtendedDetails> AspNetRolesExtendedDetails { get; set; }
    public virtual DbSet<AspNetUserRolesExtendedDetails> AspNetUserRolesExtendedDetails { get; set; }
    public virtual DbSet<AspNetUserAccessTokens> AspNetUserAccessTokens { get; set; }
    public ApplicationDbContext(DbContextOptions options) : base(options)
    {

    }
}

And your should register it like that, depending on the DB server you use, for SqlServer:
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DbContext"))


Q: Difference between physical and programmatically click on ListView I am clicking ListView item programmatically on onCreate method like below:
    // setting listener for ListView item click
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                changeView(i);
            }
        });

    // Clicking ListView first position programmatically.
    listview.performItemClick(listview.getChildAt(0), 0,
                listview.getAdapter().getItemId(0));

In above code when i debug the code changeView(i); is calling properly for both programmatic and physical click.
I am using changeView() to change colour of ListView item views (TextView and ImageView) like below:
private void changeView(int position) {
        for (int i = 0; i < adapter.getCount(); i++) {
            View v = getViewByPosition(i, listview);
            ImageView imgIcon = (ImageView) v.findViewById(R.id.icon);
            TextView txtTitle = (TextView) v.findViewById(R.id.title);
            if (i == position) {
                imgIcon.setColorFilter(ContextCompat.getColor(mActivity, R.color.app_red));
                txtTitle.setTextColor(ContextCompat.getColor(mActivity, R.color.app_red));
            } else {
                imgIcon.setColorFilter(ContextCompat.getColor(mActivity, R.color.colorWhite));
                txtTitle.setTextColor(ContextCompat.getColor(mActivity, R.color.colorWhite));
            }
        }

        lvSlideMenu.setItemChecked(position, true);
        lvSlideMenu.setSelection(position);
    }

Where getViewByPosition() method is used to get view of ListView item:
public View getViewByPosition(int pos, ListView listView) {
        final int firstListItemPosition = listView.getFirstVisiblePosition();
        final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition) {
            return listView.getAdapter().getView(pos, null, listView);
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listView.getChildAt(childIndex);
        }
    }

PROBLEM : Above code is changing colour of TextView and ImageView of list item when i click physically (by hand) but not programmatically.
Thanks in advance.

A: Try sending view in chnageView()
  changeView(view);

And in chnageView()
ImageView imgIcon = (ImageView) v.findViewById(R.id.icon);
        TextView txtTitle = (TextView) v.findViewById(R.id.title);

A: Analyzing the code, I can deduce that, when you are changing color programmatically and changeView() is called, your color change code part is not executed :
for (int i = 0; i < adapter.getCount(); i++) {
            View v = getViewByPosition(i, listview);
            ImageView imgIcon = (ImageView) v.findViewById(R.id.icon);
            TextView txtTitle = (TextView) v.findViewById(R.id.title);
            if (i == position) {
                imgIcon.setColorFilter(ContextCompat.getColor(mActivity, R.color.app_red));
                txtTitle.setTextColor(ContextCompat.getColor(mActivity, R.color.app_red));
            } else {
                imgIcon.setColorFilter(ContextCompat.getColor(mActivity, R.color.colorWhite));
                txtTitle.setTextColor(ContextCompat.getColor(mActivity, R.color.colorWhite));
            }
        }

Can you please check if for block is executed.


Q: Kafka commits transaction after LeaveGroup due to max.poll.interval.ms is exceeded I am using transaction in kafka. I have provided my consumer container with a ChainedKafkaTransactionManager which consist of JpaTransactionManager and KafkaTransactionManager.
I am trying to learn how transactions are affected when a consumer is stuck and therefore send LeaveGroup and disables heartbeat thread.
I have set max.poll.interval.ms to 10 seconds.
I have not changed session.timeout.ms. It is 10 seconds per default.
I have two applications with one consumer each. Both consumers are transactional. Consumer A is rigged to process for 30 seconds and Consumer B process it within 1 second. Both consumers read from the same topic, which as 3 partitions.

*

*Send a record to Kafka

*Consumer A receives the record.

*Consumer A starts to process the record.

*Consumer A processing time exceed max.poll.interval.ms

*Consumer A send LeaveGroup and heartbeat stops.

*Kafka rebalances. All partitions are now assigned to Consumer B.

*Consumer B receives the same record and process it.

*Consumer B commits the transaction.

*Consumer A has now finished processing(30 seconds).

*Consumer A commits the transaction.

*Kafka rebalances. Partitions are reassigned to both consumers.

The transaction is processed and committed twice. Both consumers should be idempotent to ensure processing the same record have no consequences.
My hypothesis was that Consumer A would throw an exception due to LeaveGroup and stopping the heartbeat. This is however not the case. I have tested this with unique transaction IDs and transaction ID being identical in both applications - same result.
Why does Consumer A commit the transaction after LeaveGroup has been sent?
I am not entirely sure if this is a bug. I have however submitted this odd behaviour or bug to Apache Kafka
Log for Consumer A
2018-07-11 11:59:22.365 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Received: 1 records
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager          : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Transition from state READY to IN_TRANSACTION
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager          : Created Kafka transaction on producer [brave.kafka.clients.TracingProducer@631071b0]
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Opened new EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.h.e.t.internal.TransactionImpl         : begin
2018-07-11 11:59:22.367 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@4eef56f0]
2018-07-11 11:59:22.427 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] l.a.BatchMessagingMessageListenerAdapter : Processing [GenericMessage [payload=[data], headers={kafka_offset=[34], kafka_consumer=brave.kafka.clients.TracingConsumer@1484643f, kafka_timestampType=[CREATE_TIME], kafka_receivedMessageKey=[null], kafka_receivedPartitionId=[1], kafka_receivedTopic=[trans-topic], kafka_receivedTimestamp=[1531299912221], kafka_batchConvertedHeaders=[{X-B3-SpanId=[B@1e664339, X-B3-ParentSpanId=[B@73f2c38a, X-B3-Sampled=[B@5f0ca155, X-B3-TraceId=[B@68ac877c}]}]]

...
2018-07-11 11:59:30.503 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=mygrp42] Sending Heartbeat request to coordinator localhost:9092 (id: 2147483647 rack: null)
2018-07-11 11:59:30.608 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=mygrp42] Received successful Heartbeat response
2018-07-11 11:59:32.256 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=mygrp42] Sending LeaveGroup request to coordinator localhost:9092 (id: 2147483647 rack: null)
2018-07-11 11:59:32.256 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=mygrp42] Disabling heartbeat thread
2018-07-11 11:59:37.458 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Sending offsets to transaction: {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}}
2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Begin adding offsets {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}} for consumer group mygrp42 to transaction
2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Enqueuing transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42)
2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.clients.producer.internals.Sender  : [Producer clientId=producer-1, transactionalId=transactionId420] Sending transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42) to node localhost:9092 (id: 0 rack: null)
2018-07-11 11:59:37.467 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Successfully added partition for consumer group mygrp42 to transaction
2018-07-11 11:59:37.467 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.clients.producer.internals.Sender  : [Producer clientId=producer-1, transactionalId=transactionId420] Sending transactional request (type=TxnOffsetCommitRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42, offsets={trans-topic-0=CommittedOffset(offset=408, metadata='')}) to node localhost:9092 (id: 0 rack: null)
2018-07-11 11:59:37.469 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Successfully added offsets {trans-topic-0=CommittedOffset(offset=408, metadata='')} from consumer group mygrp42 to transaction.

Log for Consumer B
2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Received: 1 records
2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager          : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Transition from state READY to IN_TRANSACTION
2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager          : Created Kafka transaction on producer [brave.kafka.clients.TracingProducer@30b6dff4]
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Opened new EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.h.e.t.internal.TransactionImpl         : begin
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@2b0eff5d]
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] l.a.BatchMessagingMessageListenerAdapter : Processing [GenericMessage [payload=[data], headers={kafka_offset=[407], kafka_consumer=brave.kafka.clients.TracingConsumer@103b53ce, kafka_timestampType=[CREATE_TIME], kafka_receivedMessageKey=[null], kafka_receivedPartitionId=[0], kafka_receivedTopic=[trans-topic], kafka_receivedTimestamp=[1531299562360], kafka_batchConvertedHeaders=[{X-B3-SpanId=[B@38658f41, X-B3-ParentSpanId=[B@2faeb13a, X-B3-Sampled=[B@29e18244, X-B3-TraceId=[B@75496432}]}]]
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Sending offsets to transaction: {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}}
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Begin adding offsets {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}} for consumer group mygrp42 to transaction
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Enqueuing transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42)
2018-07-11 11:59:33.779 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.clients.producer.internals.Sender  : [Producer clientId=producer-2, transactionalId=transactionId421] Sending transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42) to node localhost:9092 (id: 0 rack: null)
2018-07-11 11:59:33.780 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Successfully added partition for consumer group mygrp42 to transaction
2018-07-11 11:59:33.780 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.clients.producer.internals.Sender  : [Producer clientId=producer-2, transactionalId=transactionId421] Sending transactional request (type=TxnOffsetCommitRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42, offsets={trans-topic-0=CommittedOffset(offset=408, metadata='')}) to node localhost:9092 (id: 0 rack: null)
2018-07-11 11:59:33.781 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Successfully added offsets {trans-topic-0=CommittedOffset(offset=408, metadata='')} from consumer group mygrp42 to transaction.


Q: Ignore No Subdomain In htaccess RewriteCond I've got htaccess set up that redirects all subdomains except www to https. However I'd also like it to ignore http://domain.com - currently it redirects to https://domain.com which is no good for what I'm doing.
Any idea what the rewrite condition is for that?
I've tried:
RewriteCond %{HTTP_HOST} !^domain.com [NC]

RewriteCond %{HTTP_HOST} !^http://domain.com [NC]

But neither of those work.
Here's what I'm using at the minute.
# Redirect subdomains to https
RewriteCond %{SERVER_PORT} =80
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^domain.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

A: I think your problem is that you need to escape the dot in domain.com, so domain\.com.
# Redirect subdomains to https
RewriteCond %{SERVER_PORT} =80
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^domain\.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

You used a 301 (permanent) and not a 302, so you may have your browser not even trying to send requests to the http domain until you close. You should use 302 while testing and put the 301 only wen it's ok.

A: Try this:
RewriteCond %{HTTPS} =off
RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com [NC]
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


Q: React Lazy loading and infinite scoll to top I am currently working on a messaging platform and previously, we just load all the messages at once as there are not that many messages. Now that that there are many messages, it is starting to take a long time to load everything.
As such, I would like to implement lazy loading but I can't find any documentation explaining how I can do load the latest 20 messages and load more when I scroll up to view the earlier messages (Just like any messaging platform). Is there any way to implement this?


Q: $\lim_{x \to 0}|x|^{\frac{1}{x^2}}$? *I can't use LHopital.
Calculate the limit, if it exists:
$$\displaystyle \lim_{x \to 0}|x|^{\frac{1}{x^2}}$$
My attempt
$$ \lim_{x \to 0^+}|x|^{\frac{1}{x^2}} = \exp\left( \lim_{x \to 0}\ln|x|^{\frac{1}{x^2}}\right) = \exp\left( \lim_{x \to 0}\frac{1}{x^2}\ln|x|\right) =  \exp\left( \lim_{x \to 0^+}\frac{\ln x}{x^2}\right).$$
And here i am stuck.

A: We have
$\lim_{x\rightarrow 0}\frac{1}{x^2}=+\infty$ and $\lim_{x\rightarrow 0} \ln |x| = -\infty$
So the product $\lim_{x\rightarrow 0}\frac{\ln|x|}{x^2}=-\infty$
Hence the limit is 0.


Q: Keeping file permissions with FTP Is there a way I can upload my files from my computer to my server without losing the permissions? Everything is linux.
Thank you!

A: You are aware that ftp is not the program to use on the internet in 2011. The password will be send in cleartext. (In a wired or WPA Enterprise protected wireless network you might be OK as long as all your traffic stays inhouse)
sftp is the secure replacement (based on ssh). put and get commands have the -P option to preserve the permissions.

A: Basically all FTP clients (cute, filezilla, smart, yafc, etc) have the option to set file permissions.
I have not yet seen any feature / option to permanently persist the file permissions from your computer to the server. However you can in filezilla and in cuteftp ( i use these 2) set an advanced property which will auto apply a permission set of your choice to all files uploaded.
Also, i think this is not likely to ever be released as a feature since file permissions are also based on user! Different users on your computers and different users on your server all of which may or may not have differing permissions.
Hope this helped. Cheers.
PS: let me know if you can't find the option in filezilla or cuteftp

A: It depends on your FTP client. I'm sure nearly all FTP clients have this option. For example, my favorite command-line FTP client, Yafc, lets you:
put -p filename

to put while preserving file permissions.


Q: Generate unique ID of an object that stays the same across instances I am generating an object from the database using the following:
$game = $this->game_model->get_by('slug', 'some-title');

I am also using a cache library in Codeigniter where I write to a cache file by:
$this->cache->write($game, $cache);

where $game is the object and $cache is an identifier for that object.
I would like to generate a unique ID for this object to use as the cache name. Something like spl_object_hash but that will stay the same across subsequent instances.
For example if I do:
$cache = spl_object_hash($game);

// Cache object
$this->cache->write($game, $cache);

It will generate 000000006c5ce27300000000564a8706.cache as the unique ID, but if I reload the page, I get a different ID, which defeats the purpose of the cache.
How can I get a consistent unique ID for an object?

A: You can use serialize() and then hash it.
$cache = hash('sha1', serialize($game));


Q: What is the commonly accepted pronunciation of FAQ? I hear FAQ(s) pronounced like a word in "FACK(s)", while I go letter by letter. In usage, what is more common?
(Similar to SQL vs Sequel)

A: In a general sense, initialisms and acronyms are most properly pronounced as the letters, e.g. "Eye Arr Ess" or "Arr Pee Jee" rather than "Erse" or "R'pug."  Pronouncing the letters individually rather than coming up with a pronunciation for something that is not an actual word avoids misunderstandings.
That being said, especially in contexts where the given acronym or initialism will be used often (FAQ in a web context; various military acronyms) there will often be an accepted pronunciation that the community recognizes for use within the community.

A: The only reasonably objective way I can think of to gauge the relative popularity of the pronunciations "fack" and "f-a-q" is by consulting a Google Ngram Viewer chart for "a FAQ" versus "an FAQ." Here's the chart I got matching "a FAQ" (red line) against "an FAQ" (blue line) for the years 1980 through 2008 in English-language publications of all sorts:

Though historically "a FAQ" has been more common, the results for the two options are so close for the last few years included in the chart that their relative popularity in 2014 is anyone's guess.
The results for American English publications are much the same as the overall results:

But the results for British English publications are somewhat friendlier to "an FAQ" and yet at the same time seemingly more volatile:

On the strength of these charts, both pronunciations of FAQ appear to be thoroughly mainstream. As a precautionary measure, you might ask around to see whether a consensus exists in your workplace favoring one pronunciation or the other, since such a local consensus might amount to a house style on pronunciation. But if no such consensus exists, I think that you should feel free to use whichever pronunciation you prefer.

A: I believe that the more common one is "fæk". According to Wikipedia:

Since the acronym FAQ originated in textual media, its pronunciation
  varies; "fack," "fax," "facts," and "F.A.Q." are commonly heard.

Wikipedia's sources are the Jargon file and FAQs about FAQs.

A: I have only ever heard it pronounced 'Eff Ay Que'.
However it does seem to be one of those phrases that will never have a 'proper' pronunciation.

A: In order to avoid misunderstandings I think FAQ should be pronounced as an initialism (where you keep each letter separated: Eff-Ay-Kyu) rather than as an acronym (where the letters are pronounced as a word: fack).

A: Definitely articulate each letter individually...Don't say "fack" or when I was younger, in my mind FAQ = "f*** u" which made me really confused. Never heard anyone say anything besides F A Q anyways.

A: Generally, three letter acronyms are pronounced as individual letters. Acronyms of four letters or more are pronounced as words.


Q: Update Frame of Rotated UIView I am trying to update the size of rotated UIView. I tried using CGAffineTransform for rotation but whenever I tried updating the size after rotation it messed up the frame.
I somehow managed to update size of rotated view using this stackoverflow answer: rotate-uiimage-and-move which suggests:

*

*Preserving original transform and assigning .identity to the view's transform

*Updating frame of view

*Reassign original transform

Here is my final code which is working perfectly:
    func handlePinch(_ gesture: UIPinchGestureRecognizer) {
        // Preserve previous transform and assign .identity
        let transform = myView.transform
        myView.transform = .identity

        // Compute new frame
        let updatedOrigin = myView.frame.origin.applying(transform.scaledBy(x: gesture.scale, y: gesture.scale))
        let updatedSize = CGSize(width: myView.frame.width * gesture.scale, height: myView.frame.height * gesture.scale)
        myView.bounds = CGRect(origin: updatedOrigin, size: updatedSize)

        // Assign back original transform
        textView.transform = transform

        gesture.scale = 1

    }

Questions:

*

*Is this the right approach to do that? To me it seems like a hack as transform using frame's origin to compute new origin which only works fine when assigned to bounds origin.

*What is the best way to achieve resizing a rotated view?


Q: Bug in Storyboards? I'm trying to follow a YouTube tutorial on using constraints, etc and it gets you to set up a basic Storyboard along with some different coloured views. I can set them up fine, and put the widths, and heights in but as soon as I try to resize a view by the resizing arrows that appear around it's edge, all the other views disappear because their widths/heights are reset to zero. Am I causing this or is it a bug?


Q: GWT + JDO + ArrayList I'm getting a Null ArrayList in a program i'm developing. For testing purposes I created this really small example that still has the same problem. I already tried diferent Primary Keys, but the problem persists.
Any ideas or suggestions?
1-Employee class
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Employee {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
    private String key;

    @Persistent
    private ArrayList<String> nicks;

    public Employee(ArrayList<String> nicks) {
        this.setNicks(nicks);
    }

    public String getKey() {
        return key;
    }

    public void setNicks(ArrayList<String> nicks) {
        this.nicks = nicks;
    }

    public ArrayList<String> getNicks() {
        return nicks;
    }
}

2-EmployeeService
public class BookServiceImpl extends RemoteServiceServlet implements
EmployeeService {

    public void addEmployee(){

        ArrayList<String> nicks = new ArrayList<String>();
        nicks.add("name1");
        nicks.add("name2");

        Employee employee = new Employee(nicks);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(employee);
        } finally {
            pm.close();
        }
    }

    /**
     * @return
     * @throws NotLoggedInException
     * @gwt.typeArgs <Employee>
     */
    public Collection<Employee> getEmployees() {

        PersistenceManager pm = getPersistenceManager();

        try {
            Query q = pm.newQuery("SELECT FROM " + Employee.class.getName());

            Collection<Employee> list =
                pm.detachCopyAll((Collection<Employee>)q.execute());

            return list;

        } finally {
            pm.close();
        }
    }
}

A: Your Employee class did not have detachable = "true".
You should change
@PersistenceCapable(identityType = IdentityType.APPLICATION)

to
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")

A: Is it significant that in addEmployee, you obtain the persistenceManager like this:
PersistenceManager pm = PMF.get().getPersistenceManager();

but in getEmployees you call it like this
PersistenceManager pm = getPersistenceManager();

without using PMF.get().

A: I changed the code a bit, and everything is normal now, still I don't know what caused this problem.
I'm using Lists now instead of the collections**(1), I return everything as a simple array trough the RPC(2)** and I changed the way I did the query**(3)**.
(1) List results = (List) query.execute();
(2) return (Employee[]) employees.toArray(new Employee[0]);
(3) Query query = pm.newQuery(Employee.class);


Q: Show all data in a single object instead of nested object I am using sequelize ORM and for DB I am using MySQL, in which I have associated two tables and getting the data, but I want 2nd data (another table's data) should not come in like nested object instead could we show all data in a single object (both table data).
let me show the screen shot.

What I want to something like.

Ignore the keys and values of data, but my question here, could we here show the data of another table (think like inner join) in the same object, not something like in nested object.
Any suggestion would be appreciable thanks.

A: I'm not sure what you exactly want but according to your input/output I think you want to flatten the nested object(?) and for that you can use the next piece of code-
nested_obj = {"message": "Hey you", "nested_obj": {"id": 1}}

flattened_obj = Object.assign(
    {},
    ...function _flatten(o) {
      return [].concat(...Object.keys(o)
        .map(k =>
          typeof o[k] === 'object' ?
            _flatten(o[k]) :
            ({[k]: o[k]})
        )
      );
    }(nested_obj)
  )

console.log(JSON.stringify(flattened_obj));


Q: Selecting property of anonymous type using LINQ throws exception My Linq query (i want to get list of items sorted by number of orders)
var x = context.Items.Include("Item_qualities").Join(
               context.Orders,
               i => i.Id,
               o => o.Item_id,
               (i, o) => new { i, o }
               )
               .GroupBy(e => new { e.i })
               .Select(w => new { w.Key.i, c = w.Count() })
               .OrderByDescending(y => y.c)
               .ToList().Select(u=>u.i);

Last part Select(u=>u.i) throws exception

The text, ntext, and image data types cannot be compared or sorted,
  except when using IS NULL or LIKE operator.

A: That error is pretty clear:
The text data type, which is deprecated as of SQL Server 2005, is not suitable for comparison so it is not possible to do sorting on it. The same goes for image data type. Read this for more details. In other words the database engine cannot do the sorting based on the column you have specified.


Q: What's the Return of GetQueuedCompletionStatus when the I/O is cancelled via CancelIoEx? Imagine I have a thread waiting for some I/O packets with GetQueuedCompletionStatus().  Another thread uses CancelIoEx() with lpOverlapped == nullptr to cancel all of the I/Os that the first thread initiated.
Will GetQueuedCompletionStatus() return immediately, and is there an appropriate error-code with GetLastError()?  Or will CancelIoEx() prevent the I/Os from ever finishing and GetQueuedCompletionStatus() will remain pending for further I/O?

A: The answers to all of your questions are clearly stated in Microsoft's documentation.
CancelIoEx():

The CancelIoEx function allows you to cancel requests in threads other than the calling thread. The CancelIo function only cancels requests in the same thread that called the CancelIo function. CancelIoEx cancels only outstanding I/O on the handle, it does not change the state of the handle; this means that you cannot rely on the state of the handle because you cannot know whether the operation was completed successfully or canceled.
If there are any pending I/O operations in progress for the specified file handle, the CancelIoEx function marks them for cancellation. Most types of operations can be canceled immediately; other operations can continue toward completion before they are actually canceled and the caller is notified. The CancelIoEx function does not wait for all canceled operations to complete.
If the file handle is associated with a completion port, an I/O completion packet is not queued to the port if a synchronous operation is successfully canceled. For asynchronous operations still pending, the cancel operation will queue an I/O completion packet.
The operation being canceled is completed with one of three statuses; you must check the completion status to determine the completion state. The three statuses are:

*

*The operation completed normally. This can occur even if the operation was canceled, because the cancel request might not have been submitted in time to cancel the operation.

*The operation was canceled. The GetLastError function returns ERROR_OPERATION_ABORTED.

*The operation failed with another error. The GetLastError function returns the relevant error code.

GetQueuedCompletionStatus():

If the GetQueuedCompletionStatus function succeeds, it dequeued a completion packet for a successful I/O operation from the completion port and has stored information in the variables pointed to by the following parameters: lpNumberOfBytes, lpCompletionKey, and lpOverlapped. Upon failure (the return value is FALSE), those same parameters can contain particular value combinations as follows:

*

*If *lpOverlapped is NULL, the function did not dequeue a completion packet from the completion port. In this case, the function does not store information in the variables pointed to by the lpNumberOfBytes and lpCompletionKey parameters, and their values are indeterminate.

*If *lpOverlapped is not NULL and the function dequeues a completion packet for a failed I/O operation from the completion port, the function stores information about the failed operation in the variables pointed to by lpNumberOfBytes, lpCompletionKey, and lpOverlapped. To get extended error information, call GetLastError.

So, this means that CancelIoEx() will simply mark existing asynchronous operations for cancellation, and IF THE DRIVER ACTUALLY CANCELS THEM then completion statuses WILL be posted back to you indicating the operations were cancelled.
If GetQueuedCompletionStatus() returns TRUE, that means an I/O packet with a success status was dequeued.
If GetQueuedCompletionStatus() returns FALSE AND OUTPUTS A NON-NULL OVERLAPPED* pointer, that means an I/O packet with a failure status was dequeued, so all of the output values are valid, and you can use GetLastError() to get the error code for that packet.
If GetQueuedCompletionStatus() returns FALSE AND OUTPUTS A NULL OVERLAPPED* pointer, that means GetQueuedCompletionStatus() itself failed, so all of the output values are indeterminate and should be ignored, and you can use GetLastError() to get the error code for the failure.

A: GetQueuedCompletionStatus return when I/O finished.  if initial code of I/O operation was ERROR_IO_PENDING and file bind to IOCP -when I/O finished - packet will be queued to IOCP and GetQueuedCompletionStatus return (for this I/O operation).
so question better be next:
Will I/O will be completed immediately if we call CancelIoEx on file ?
this already depend from concrete diver: are it registered cancel routine (IoSetCancelRoutine) on IRP for which he return STATUS_PENDING.
are this driver immediately IofCompleteRequest when it  CancelRoutine called for IRP. any good designed driver must do both. so if you do I/O request on say some built-in windows driver - answer - yes - I/O will be completed immediately.
about error code - usually (almost always) this will be STATUS_CANCELLED - with this status driver complete canceled IRP. the GetQueuedCompletionStatus conver error NTSTATUS  to win32 errors. so STATUS_CANCELLED will be converted to ERROR_OPERATION_ABORTED.
so if in short

Will GetQueuedCompletionStatus return immediately

yes (almost always, but depend from driver, from this api - nothing depend)

is there an appropropate error-code ?

yes - almost always this will be ERROR_OPERATION_ABORTED(but again depend from driver and not depend from this api)


Q: Data-Visualization Python

*Plot 4 different line plots for the 4 companies in dataframe open_prices. Year would be on X-axis, stock price on Y axis, you will need (2,2) plot. Set figure size to 10, 8 and share X-axis for better visualization
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from nsepy import get_history
import datetime as dt
%matplotlib inline
start = dt.datetime(2015, 1, 1)
end = dt.datetime.today()
infy = get_history(symbol='INFY', start = start, end = end)
infy.index = pd.to_datetime(infy.index)
hdfc = get_history(symbol='HDFC', start = start, end = end)
hdfc.index = pd.to_datetime(hdfc.index)
reliance = get_history(symbol='RELIANCE', start = start, end = end)
reliance.index = pd.to_datetime(reliance.index)
wipro = get_history(symbol='WIPRO', start = start, end = end)
wipro.index = pd.to_datetime(wipro.index)
open_prices = pd.concat([infy['Open'], hdfc['Open'],reliance['Open'],
wipro['Open']], axis = 1)
open_prices.columns = ['Infy', 'Hdfc', 'Reliance', 'Wipro']
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
axes[0, 0].plot(open_prices.index.year,open_prices.INFY)
axes[0, 1].plot(open_prices.index.year,open_prices.HDB)
axes[1, 0].plot(open_prices.index.year,open_prices.TTM)
axes[1, 1].plot(open_prices.index.year,open_prices.WIT)

Blank graph is coming.Please help....?!??

A: Below code works fine , I have changed the following things
a) axis should be ax b) DF column names were incorrect c) for any one to try this example would also need to install lxml library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from nsepy import get_history
import datetime as dt

start = dt.datetime(2015, 1, 1)
end = dt.datetime.today()
infy = get_history(symbol='INFY', start = start, end = end)
infy.index = pd.to_datetime(infy.index)
hdfc = get_history(symbol='HDFC', start = start, end = end)
hdfc.index = pd.to_datetime(hdfc.index)
reliance = get_history(symbol='RELIANCE', start = start, end = end)
reliance.index = pd.to_datetime(reliance.index)
wipro = get_history(symbol='WIPRO', start = start, end = end)
wipro.index = pd.to_datetime(wipro.index)
open_prices = pd.concat([infy['Open'], hdfc['Open'],reliance['Open'],
wipro['Open']], axis = 1)
open_prices.columns = ['Infy', 'Hdfc', 'Reliance', 'Wipro']
print(open_prices.columns)

ax=[]
f, ax = plt.subplots(2, 2, sharey=True)
ax[0,0].plot(open_prices.index.year,open_prices.Infy)
ax[1,0].plot(open_prices.index.year,open_prices.Hdfc)
ax[0,1].plot(open_prices.index.year,open_prices.Reliance)
ax[1,1].plot(open_prices.index.year,open_prices.Wipro)
plt.show()


Q: Recommended video profile We are encoding our videos thinking about being played on Android and iOS native apps, and with bitmovin player on browsers (desktop and mobile). Which video profile should we use? Will the high profile be supported on all devices (Android 4.1+)? We are encoding on h264 and mp4 format.
Thanks a lot!

A: official documentations explains everything (for android)
You can see that H.265 main profile is supported by 5.0+ devices. Also some other profiles are supported by some devices, but their support is implemented by the manufacturers. The documentation lists the formats that are granted to be played. All other formats may be playable, or not depending on the device model and manufacturer. So if you want to support at least most part of the devices, you'll have to follow that table.


Q: Prove the regular surface with 2 geodesics from p to q, and negative curvature cannot be simply connected. What ideas/formulas are required to solve this? Exercise: If a and b are two geodesics from point p to q, how do you prove that M is not simply connected? M is a regular surface in R3 and has negative Gaussian curvature K. Points p & q are two distinct points on surface M.
I know surface is simply connected if any simple closed curve can be shrunk to a point continuously in the set. So a sphere is simply connected, and a donut is not simply connected. And I know that since the curvature is negative, and since K=det(Sp)=w*z, so eigenvalues w and z have opposite signs. I also have the formula K=(eg-f^2)/(EG-F^2) based on the 1st fundamental forms and derivatives for solving for E,F,G,e,f,g. Not sure what if anything that is used to solve. And the only geodesic equations I can think of off hand are
d/dt(E u' + F v')=1/2[E_u u'^2 + 2F_u u'v' +G_u v'^2 ], d/dt(Fu'+Gv')=1/2[E_v u'^2 +2F_u u'v' +G_v v'^2 ], and geodesic curvature c=, and Gauss-Bonnet integrals but not sure how that can be applied. If they can be applied, please let me know. Maybe the fact that the normal of any point on the geodesic arc also is on the same normal vector to the surface M at that point helps? What ideas and equations are required to solve the exercise?

A: EDIT, Thursday evening: a good illustration for the bit about negative curvature is the inner circle in the "hole" in a torus of revolution, which is a "closed geodesic" and cannot be contracted continuously to a point. The closed geodesic occurs in the (inner) part of the torus where the Gauss curvature is negative, while the outer portion has positive curvature. Meanwhile, no compact surface in $\mathbb R^3$ can have negative Gauss curvature everywhere, for which Neal gave a simple answer in comments. It is, of course, possible to have noncompact surfaces with negative curvature, such as the catenoid of revolution. However, for any such surface of revolution with negative curvature, the absolute value of the curvature goes to $0$ as we get far from the central axis. So Mariano asked whether there are any infinite surfaces in $\mathbb R^3$ with Gauss curvature that is bounded away from $0,$ and the answer is no, not for a $C^2$ surface. Link to the question MARIANO QUESTION.
ORIGINAL: This is Gauss-Bonnet for polygons on an oriented surface. The familiar case should be this: the area of a geodesic triangle on the unit sphere is $\alpha + \beta + \gamma - \pi,$ where $\alpha, \beta, \gamma$ are the angles at the vertices of the triangle. Next, we define the external angles $\theta_1 = \pi - \alpha, \; \theta_2 = \pi - \beta, \; \theta_3 = \pi - \gamma, $ according to Figure 4-25 of do Carmo:
==========

==========
The unit sphere has curvature $K=1,$ so the integral of $K$ over a polygon is just its area. Furthermore, the boundary arcs are geodesics, with geodesic curvature $k_g = 0.$ So the statement about this area is equivalent to
$$  \int \int_T \; K d \sigma \; + \theta_1 + \theta_2 + \theta_3 = 2 \pi.  $$
Compare this with Gauss-Bonnet, formula (1) here:
==========

===========
You may or may not be told this: in the simply connected hyperbolic plane of constant curvature $-1,$ the area of a triangle is $ \pi - (\alpha + \beta + \gamma),$ where $\alpha, \beta, \gamma$ are the angles at the vertices of the triangle. However, because $K = -1,$ this is once again the same as
$$  \int \int_T \; K d \sigma \; + \theta_1 + \theta_2 + \theta_3 = 2 \pi.  $$
For your exercise, you are asked about an (oriented) "diangle" $D,$ with angles $0 \leq \alpha, \beta \leq \pi.$ If an angle is equal to $0,$ that is what the author calls a "cusp," see Figure 4-26, the right half. We take the external angles as before, and get
$$  \int \int_D \; K d \sigma \; + \theta_1 + \theta_2  = 2 \pi,  $$
$$  \int \int_D \; K d \sigma \; + (\pi - \alpha) + (\pi - \beta)  = 2 \pi,  $$
$$  \int \int_D \; K d \sigma \; =  \alpha + \beta.  $$
What does this mean? We have $K < 0.$ The right hand side of the equation is nonnegative. If there is any interior to the "diangle," the integral is strictly negative. The only legal possibility is that the two geodesics are identical, both vertices are cusps, the two geodesic arcs are exactly the same, once out, once back.
Otherwise, and here is where the topology comes in, the two geodesic arcs do not bound a piece of surface as I was assuming, and the loop cannot be deformed homotopically to a single point, thus the surface is not simply connected.
Well, I hope that works for you. There is quite a bit of detail that could be added about orientation. Furthermore, I do not think a closed surface in $\mathbb R^3$ can have negative Gauss curvature. I know that a closed surface in $\mathbb R^3$ cannot have constant negative Gauss curvature.


Q: I was training an Ann machine learning model using GridSearchCV and got stuck with an IndexError in gridSearchCV My model starts to train and while executing for sometime it gives an error :-
IndexError: index 37 is out of bounds for axis 0 with size 37
It executes properly for my model without using gridsearchCV with fixed parameters

Here is my code
    from keras.wrappers.scikit_learn import KerasClassifier
    from sklearn.model_selection import GridSearchCV
    from keras.models import Sequential
    from keras.layers import Dense
    def build_classifier(optimizer, nb_layers,unit):
        classifier = Sequential()
        classifier.add(Dense(units = unit, kernel_initializer = 'uniform', activation = 'relu', input_dim = 14))
        i = 1
        while i <= nb_layers:
            classifier.add(Dense(activation="relu", units=unit, kernel_initializer="uniform"))
            i += 1
        classifier.add(Dense(units = 38, kernel_initializer = 'uniform', activation = 'softmax'))
        classifier.compile(optimizer = optimizer, loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
        return classifier
    classifier = KerasClassifier(build_fn = build_classifier)
    parameters = {'batch_size': [10,25],
                  'epochs': [100,200],
                  'optimizer': ['adam'],
                  'nb_layers': [5,6,7],
                  'unit':[48,57,76]
                 }
    grid_search = GridSearchCV(estimator = classifier,
                               param_grid = parameters,
                               scoring = 'accuracy',
                              cv=5,n_jobs=-1)
    grid_search = grid_search.fit(X_train, y_train)
    best_parameters = grid_search.best_params_
    best_accuracy = grid_search.best_score_

A: The error IndexError: index 37 is out of bounds for axis 0 with size 37 means that there is no element with index 37 in your object.
In python, if you have an object like array or list, which has elements indexed numerically, if it has n elements, indexes will go from 0 to n-1 (this is the general case, with the exception of reindexing in dataframes).
So, if you ahve 37 elements you can only retrieve elements from 0-36.

A: This is a multi-class classifier with a huge Number of Classes (38 classes). It seems like GridSearchCV isn't spliting your dataset by stratified sampling, may be because you haven't enough data and/or your dataset isn't class-balanced.
According to the documentation:

For integer/None inputs, if the estimator is a classifier and y is
  either binary or multiclass, StratifiedKFold is used. In all other
  cases, KFold is used.

By using categorical_crossentropy, KerasClassifier will convert targets (a class vector (integers)) to binary class matrix using keras.utils.to_categorical. Since there are 38 classes, each target will be converted to a binary vector of dimension 38 (index from 0 to 37).
I guess that in some splits, the validation set doesn't have samples from all the 38 classes, so targets are converted to vectors of dimension < 38, but since GridSearchCV is fitted with samples from all the 38 classes, it expects vectors of dimension = 38, which causes this error.

A: Take a look at the shape of your y_train. It need to be a some sort of one hot with shape (,37)


Q: Proving that $KL$ bisects $AJ$ in a triangle?
Let $ABC$ be an acute triangle, and its incircle touch the sides $AB$ and $AC$ at $K$ and $L$. Let $J$ be the incenter of $\triangle BCD$, where $D$ is a point on $AC$ such that $BD=AB$. Prove that $KL$ bisects $AJ$.

My idea was to draw a line parallel to $KL$ through $J$ intersecting $AC$ at $H$. It is easy to see that $\triangle CHJ \sim \triangle CIB$. I also saw that $\angle JHD=\angle JDH$, implying $JD=JH$. I wanted to prove that $CH=a-c$ using similarity which would easily prove that $AG=JG$.
However, I am not able to finish it. I think the idea of drawing a parallel is a good one, yet I am not able to draw a conclusion? Can anyone help? :)

A: Hint: introduce point $X$ - reflection of $D$ with respect to $BJ$.


Q: Is there a way to specify an editor on a git command in a one-off style As mentioned above, I am looking for something like this:

$ git commit -m "my first commit" --editor="vim"

that will allow me to one-off swap editor for a single run. Examples where this might be useful is when squashing lengthy histories or writing up messages for a feature commit.

A: You can override EDITOR environment variable just for one git execution:
EDITOR=nano git commit -a


Q: Obtain Date value from HTML form and pass it in PHP I'm trying to get a date from an HTML form into PHP, to then pass it to a MYSQL database. In PHP I get the date with a POST method.
$Data = $_POST['Data']; //Data

In HTML i made up this:
<input type="date" name="Data" id="Data" required/>

When I try to send it to my database with the mysqli_query() method, I always get this error:

Incorrect date value: '' for column 'Data' at row 1

Can you please help me?
This is the query if you are interested. All the other variables work.
INSERT INTO 'table_name' ('col1', 'col2', 'col3', Data, 'col5', 'col6')

VALUES ('$var1', '$var2', '$var3', '$Data', '$var5', '$var6')";

EDIT: (Whole Form)
    <form action="insert.php">

Prenota pasti al Podere Diamante

Nome

            <input type="text" name="Nome" placeholder="Nome" required/>

Numero Telefonico

          <input type="text" name="NTelefonico" placeholder="### ### ####" required/>

Data di prenotazione

          <input type="date" name="Data" id="Data" required/>

Orario di prenotazione

          <input type="time" name="NGruppo" required min="19:00" max="21:30" step="1800"/>

Con quante persone sarai?

          <input type="number" name="NPersone" min="1" max="150" required/>

Note aggiuntive

          <textarea rows="3" name="Note"></textarea>

          <button type="submit" href="/">Invia</button>

      </form>

A: Change
<form action="insert.php">

to
<form action="insert.php" method="post">

The default HTTP method of a form is GET. You must specify POST since you are accessing it using $_POST. Then you should be able to get the value of the Data field in $Data.
If it doesn't fix the errors, try the following:
1 Check the datatype of Data column in your MySQL table, and make sure that your $Data is in correct format.
For example: If your Data column is a DATE column, $Data should be in YYYY-mm-dd format.
Other Date - Time types and format is given here:
Date and Time Types                          Description
-----------------------------------------------------------------
 DATE                         A date value in CCYY-MM-DD format
-----------------------------------------------------------------
 TIME                           A time value in hh:mm:ss format
-----------------------------------------------------------------
 DATETIME     A date and time value inCCYY-MM-DD hh:mm:ss format
-----------------------------------------------------------------
 TIMESTAMP      A timestamp value in CCYY-MM-DD hh:mm:ss format
-----------------------------------------------------------------
 YEAR                         A year value in CCYY or YY format
-----------------------------------------------------------------

Extra Read: Methods GET and POST in HTML forms - what's the difference?http://jkorpela.fi/forms/methods.html

A: In the database you need to set the date field to  type date and in the input field of the form you need to capture the correct date format.  Or alternatively use a date picker field

        Date

              <input type="date" name="date">

A: If you need the current date just you the built-in date in php
$now = date('Y-m-d');

Else check your sql date column and make sure it's Varchar then do this
<form action="insert.php"
method="post">
//in your insert try using
'".$Data."' in place of '$Data'


Q: Changing Alpha of UITableView Section on Cell Select I have an issue when using multiple table view sections. I am trying to change the alpha for a cell when the user taps it. Each section in the table view has one row.
Here is my code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  NSIndexPath *indexPathInSection = [NSIndexPath indexPathForRow:0  inSection:indexPath.section];
  [tableView cellForRowAtIndexPath:indexPathInSection].contentView.alpha = 0.2f;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
  NSIndexPath *indexPathInSection = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
  [tableView cellForRowAtIndexPath:indexPathInSection].contentView.alpha = 1.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   MatchCell *cell = (MatchCell *)[self cellForIdentifier:tableView:@"MatchCell"];
   MatchedUser *user = (MatchedUser *)(self.matches)[indexPath.section];

  [self configureMatchCell:cell :user :tableView];

  NSIndexPath *selection = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
  if (selection.section == indexPath.section && cell.isSelected){
    cell.contentView.alpha = 0.2f;
  }else{
    cell.contentView.alpha = 1.0f;
  }
  return cell;
}

The alpha is applied to the cell that is tapped but other cells are also changed. This is because it is applied according to the row number not the section and row number. How can I specify the cell at the section and row index only?
Thanks.


Q: Jenkins - shell script - find parameter format not correct
hope one of you can help - I'm running a script in jenkins pipeline, so that I can upload source maps to rollbar, so I need to loop through the minified js files - I'm trying to do this with the FIND command but it keeps giving me an error: find parameter format not correct - script below:
stages {
    stage('Set correct environment link') {
        steps {
            script {
                buildTarget = params.targetEnv
                if(params.targetEnv.equals("prj1")){
                    linkTarget = "http://xxx.xxx.xx/xxx/"
                } else if(params.targetEnv.equals(.......)..etc.
    stage('Uploading source maps to Rollbar') {
        steps {
                sh ''' #!/bin/bash
                    # Save a short git hash, must be run from a git
                    # repository (or a child directory)
                    version=$(git rev-parse --short HEAD)

                    # Use the post_server_time access token, you can
                    # find one in your project access token settings
                    post_server_item=e1d04646bf614e039d0af3dec3fa03a7

                    echo "Uploading source maps for version $version!"

                    # We upload a source map for each resulting JavaScript
                    # file; the path depends on your build config
                    for path in $(find dist/renew -name "*.js"); do
                      # URL of the JavaScript file on the web server
                      url=${linkTarget}/$path

                      # a path to a corresponding source map file
                      source_map="@$path.map"

                      echo "Uploading source map for $url"

                      curl --silent --show-error https://api.rollbar.com/api/1/sourcemap \
                        -F access_token=$post_server_item \
                        -F version=$version \
                        -F minified_url=$url \
                        -F source_map=$source_map \
                        > /dev/null
                    done
                '''
        }
    }
    stage('Deploy') {
        steps {
            echo 'Deploying....'

From Bash CLI

A: With the help of @jeb I managed to resolve this FIND issue on jenkins by placing the absolute path for (find) in the shell script - initially it was using the windows FIND cmd, so i needed to point to cygwin find cmd
before: for path in $(find dist/renew -name "*.js"); do
and after: for path in $(/usr/bin/find dist/renew -name "*.js"); do
Thaks to all that commented


Q: How do I deal with app state in a multi-"page" application? I'm having trouble envisioning application state.
For a multi-page application, should each page only load a chunk of the app state?
For example, let's say I have an app that manages my favorite things, books, movies, and games. Each one of those domains will have their own page to manage them. Is the idea that only portions of app state are loaded based on what's needed in the current context?
My app state would look something like this, conceptually.
{
    currentUser: { id: 9, userName: 'JUtah' },
    books: {},
    movies: {},
    games: {}
}

However, if I browsed to Books Management, the app state would look like this:
{
    currentUser: { id: 9, userName: 'JUtah' },
    books: {
        1: { title: 'Kung Fu for Kittens', author: 'Dr. Meowrtin Kibble' }
    },
    movies: {},
    games: {}
}

If I browsed to Movie Management, this:
{
    currentUser: { id: 9, userName: 'JUtah' },
    books: {}
    },
    movies: {
        1: { title: 'John Wick', star: 'Keanu Reeves' }
    },
    games: {}
}

and so on.
Is this correct? I'm struggling to determine what app state holds at any given time.

A: First of all, React's local state and Redux's global state are different things.
Let's assume you don't use Redux for the moment. State management is up to you totally. But, try to construct your components as pure as possible and use the state where do you really need it. For example, think about a favorites app as you said. The decision is, do you want to show all the favorites categories in the same UI? If yes, then you need to keep all of them in one place, in the App. Then you will pass those state pieces your other components: Book, Movie, etc. Book get the book part of your state for example. They won't have any state, your App does. Here, App is the container component, others are presentational ones or dumb ones.
Is your data really big? Then you will think about other solutions like not fetching all of them (from an API endpoint or from your DB) but fetch part by part then update your state when the client wants more.
But, if you don't plan to show all of them in one place, then you can let your components have their state maybe. Once the user goes to Book component, maybe you fetch only the book data then set its state according to that. As you can see there are pros and cons, in the first method you are doing one fetch and distributing your data to your components, in the second method you are doing multiple fetches. So, think about which one suits you.
I can see you removed the Redux tag, but with Redux you will have one global state in the store. Again, in one point you are doing some fetch then update your state. Then, you will connect your components when they need any data from the state. But again, you can have container/presentational components here, too. One container connects to your store then pass the data to your components. Or, you can connect multiple components to your store. As you examine the examples, you will see best practices about those.
If you are new don't think too much :) Just follow the official documentation, read or watch some good tutorials and try to write your app. When you realize you need to extract some component do it, then think about if you need any state there or not?
So, once the question is very broad then you get an answer which is too broad, some text blocks :) You can't see so many answers like that, because here we share our specific problems. Again, don't bloat yourself with so many thoughts. As you code, you will understand it better.


Q: Uploading string value into azure storage location as a file content I want to upload a string value as file content into azure storage location but without writing any code and using azure components only. Is there any option available?

A: There are a lot of ways to do this：

*

*Write a string into .txt file and upload the file to a storage container on Azure Portal.

*Generate a long lifetime SAS token on Azure Portal:

and use blob rest API to upload it to a blob, you can do it directly in postman:

Result:

*Use Azure Logic App to do this. Let me know if you have any more questions.

Let me know if you have any more questions.


Q: Dialog dismiss animation not applying I have a DialogFragment whose only child is a StackView. The dialog is launched when a button is clicked in the parent fragment.
I tried to add animations to the fragment via getWindow().setWindowAnimations() but for some reason it was not working.
The approach that I took is to animate the Window's decorView:
public class TrailerDialogFragment extends DialogFragment {

    private static final String VIDEOS_EXTRA = "videos extra";

    private List<Video> mVideos = new ArrayList<>();

    @BindView(R.id.stack_view)
    StackView mStackView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<Video> videos = getArguments().getParcelableArrayList(VIDEOS_EXTRA);
        if (videos != null) {mVideos.addAll(videos);}
    }

    public static TrailerDialogFragment newInstance(List<Video> videos) {
        Bundle bundle = new Bundle();
        ArrayList<Video> arrayList = new ArrayList<>();
        arrayList.addAll(videos);
        bundle.putParcelableArrayList(VIDEOS_EXTRA, arrayList);
        TrailerDialogFragment fragment = new TrailerDialogFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.dialog_stackview, container, false);

        ButterKnife.bind(this, rootView);
        mStackView.setAdapter(new VideoAdapter(mVideos));

        return rootView;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();
        final View decorView = getDialog()
                .getWindow()
                .getDecorView();

        ObjectAnimator scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView,
                PropertyValuesHolder.ofFloat("scaleX", 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat("scaleY", 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat("alpha", 0.0f, 1.0f));
        scaleDown.setDuration(500);
        scaleDown.start();
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        final View decorView = getDialog()
                .getWindow()
                .getDecorView();

        ObjectAnimator scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView,
                PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.0f),
                PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.0f),
                PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f));
        scaleDown.setDuration(500);
        scaleDown.start();
        super.onCancel(dialog);
    }

    private static class VideoAdapter extends BaseAdapter {

        List<Video> mVideos = new ArrayList<>();

        public VideoAdapter(List<Video> videos) {
            mVideos.addAll(videos);
        }

        @Override
        public int getCount() {
            return mVideos.size();
        }

        @Override
        public Object getItem(int i) {
            return mVideos.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View resultView;
            if (view == null) {
                resultView = LayoutInflater.from(viewGroup.getContext()).inflate(
                        R.layout.dummy_view, viewGroup, false);
            } else  {
                resultView = view;
            }
            TextView tv = (TextView) resultView.findViewById(R.id.trailer_title);
            ImageView image = (ImageView) resultView.findViewById(R.id.trailer_image);

            tv.setText(mVideos.get(i).name());
            ViewUtil.loadThumbnail(mVideos.get(i).key(), resultView.getContext(), image);
            return resultView;
        }
    }
}

When I click outside of dialog fragment, the onCancel callback is triggered, but for some reason the animation doesn't play. The DialogFragment simply dissappears.
Do you know why this could happen?


Q: Wordpress xmlrpc SSL Certificate Error (Only On 1 Machine) I'm using the Wordpress xmlrpc Python module on Python 3.6 to automatically write and publish blog posts to my Wordpress site (hosted directly by Wordpress).
The program runs great on one of my Windows machines, but when I try to run it using my second Windows machine, with the exact same code, on the same network, I receive an SSL error. Details below:
import ssl

import wordpress_xmlrpc
from wordpress_xmlrpc import Client
from wordpress_xmlrpc import WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts
from wordpress_xmlrpc.methods.posts import NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc.compat import xmlrpc_client

wp = Client("https://website.io/xmlrpc.php", "wordpressusername", "wordpresspassword")

post = WordPressPost()
post.title = "title"
post.content = content

post.post_status = 'publish'
status_draft = 0
status_published = 1
wp.call(NewPost(post))

Here's the error:
File "C:\Python36\Lib\http\client.py", line 964, in send
    self.connect()
  File "C:\Python36\Lib\http\client.py", line 1400, in connect
    server_hostname=server_hostname)
  File "C:\Python36\Lib\ssl.py", line 401, in wrap_socket
    _context=self, _session=session)
  File "C:\Python36\Lib\ssl.py", line 808, in __init__
    self.do_handshake()
  File "C:\Python36\Lib\ssl.py", line 1061, in do_handshake
    self._sslobj.do_handshake()
  File "C:\Python36\Lib\ssl.py", line 683, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)

I've used pip list to view all installed modules on both machines and everything matches exactly. The code is stored on a synced Google Drive folder, so it's literally the exact same .py file both times. I can't understand why it works on one machine but not the other.
I've read the thread here but I don't believe it applies to the wordpress xmlrpc tool. I've read through the documentation here but I can't see anything helpful.
Is this something I have to tweak/delete/refresh the ssl certificates in Chrome or something? Any answers or insight much appreciated. Thanks in advance

A: So, 3 weeks later, I finally found a way to fix this.
I ended up completely uninstalling/deleting Python on my secondary machine and reinstalling everything (along with reinstalling all modules, and confirming via pip list) and now it works (no more SSL error).
For what it's worth, and I can't be sure this is what was causing the issue in the first place, but previously, I was running Python 3.6.1 on the working machine and python 3.6.2 on the other, non-working machine.
When I reinstalled everything, I reinstalled Python 3.6.1 (to match the working machine) and it worked on both.


Q: When to split users into several Devise models? I have an Rails app with two types of users: customers and suppliers. Each type has access to completely different controllers.
I'm in doubt know if I create one Devise model or two.
Are there any conventions when to use more than one controller in Devise?
I know that this is a general question and very subjective. Nevertheless I would like to know if there is any official guidelines for this? This question has been keeping me thinking for a long time already.
If there eis any forum on SE that is more appropriated for this question, please let me know.

A: I'm guessing that your customers and suppliers have some things in common (username and password, logging in to your site, etc), but they are just able to access different controllers/views/features etc. If you were to create two Devise models, it seems like you'd be creating a bunch of repetition.
This seems like a great fit for role-based authorization. There's a nice description of role-based authorization in the cancan docs: even if you're not using cancan, their docs give some nice examples that could be a starting point for a larger conversation.


Q: R DT datatable - conditional colour format for continuous value I would like to apply conditional formatting using the datatable function in R. Consider the following scenario:
test <- data.frame(
  var1 = sapply(1:L, function(x)
    paste("<X>",paste0(x,
                       letters,
                       LETTERS,
                       "\n",
                       collapse=" "))),
  var2 = round(rnorm(L),2)
)

test$var2 <- ifelse(test$var2 > 1, 1, test$var2)
test$var2 <- ifelse(test$var2 < -1, -1, test$var2)
test$tmp  <- test$var2*255
test$R    <- test$G <- 0
test$R    <- ifelse(test$tmp < 0, round(abs(test$tmp)), test$R)
test$G    <- ifelse(test$tmp > 0, round(test$tmp), test$G)
test$col  <- paste0("rgb(",test$R,",",test$G,",0)")

test <- test[,c("var1","var2","col")]

datatable(test)

I would like to font colour of var1 to take values from the col variables (which I don't actually need in the final data table).
Is this possible to achieve?
Many thanks in advance.

A: Take a look to the DT doc
2.9 Escaping table content
You will see that you can put HTML content to your table and by using escape=Fmake it readable in HTML.
and you can do something like this on the varibles of your dataframe.
apply(yourMatrix,2,function(x) ifelse(x>value,
paste0('',x,''),
paste0('',x,'')
)

For example if you have a vector x <- c(1,2,3,4) and want value higher than 0 be red you will have
[1] "1"
[2] "2"
[3] "3"
[4] "4"

and then
datatable(yourMatrix, escape = FALSE)


Q: HTML5 input type range is not setting to initial value of model AngularJS I am using HTML5 input type of range for slider functionality and binding it to my model.
By default my model will have a value in it, but slider is taking only min and max not value. When I go back from that screen and coming back, slider goes to left end but value remains what I gave last time only.

$scope.maxAmt = $rootScope.maxAmt;
$scope.minAmt = $rootScope.minAmt;
$scope.loanAmt = 5000;
<input type="range" min="{{minAmt}}" max="{{maxAmt}}"
                     value="{{loanAmt}}" step="500"
                     ng-model="loanAmt"
                     >
<output name="loanAmt">{{loanAmt}}</output>