text:
Q: Images are not getting uploaded from Android to Firebase I am trying to upload image to Firebase via Android app .
On pressing Upload button and after setting the image from storage, it just remains uploading all the time. In brief,uploading task is never getting successfull.
This is my MainActivity.java
package com.example.android.test3;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.internal.Storage;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.IOException;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private Button btn_upload,btn_choose;
    private ImageView imageView;
    private Uri filePath;
    private FirebaseStorage storage;
    private StorageReference storageReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_choose =(Button)findViewById(R.id.btn_choose);
        btn_upload =(Button)findViewById(R.id.btn_upload);
        imageView =(ImageView) findViewById(R.id.myImage);
        storage = FirebaseStorage.getInstance();
        storageReference = storage.getReference();

        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage();
            }

        });
        btn_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseImage();
            }
        });
    }

    private void chooseImage() {

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select Image"),1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==1 && resultCode == RESULT_OK && data!=null && data.getData()!=null){
            filePath = data.getData();

            try {
               Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filePath);
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void uploadImage() {
        if (filePath != null) {
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Uploading...");
            progressDialog.show();

            StorageReference reference = storageReference.child("images/" + UUID.randomUUID().toString());
            reference.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Toast.makeText(MainActivity.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
                            progressDialog.dismiss();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                         double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
                           progressDialog.setMessage("Uploaded "+(int)progress+"%");
                        }
                    });
        }
    }
}

I have only one activity.
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="450dp"
    android:id="@+id/myImage"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn_choose"
        android:layout_marginRight="5dp"
        android:layout_weight="1"
        android:background="@drawable/button_rounded"
        android:text="Choose"
        android:textColor="#ffffff"
        android:textSize="20sp"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btn_upload"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:background="@drawable/button_rounded"
            android:text="Upload"
            android:textColor="#ffffff"
            android:textSize="20sp"/>

    </LinearLayout>
</LinearLayout>

I just for similar problems on goolge but none of them solves my issue.'
My code works fine on Android Studio.
My Firebase is connected to my app.


text:
Q: Compre two objects I have the below entity
public class Employee
{
    public int EmpId { get; set; }
 }

How can I compare between the objects?
Thanks

A: Implement IEquatable<T> on your type (in this case Employee), and then use Enumerable.SequenceEqual:
bool equal = Enumerable.SequenceEqual(lst1, lst2);

If you cannot modify the Employee class, you can also create a custom IEqualityComparer<T> for Employee and use the other overload of Enumerable.SequenceEqual.
bool equal = lst1.SequenceEqual(lst2, new EmployeeComparer());

Note that this considers two collections equal only if they contain equal objects in the same order.
If the order of the items doesn't matter I would use something like this:
bool equal = lst1.Count == lst2.Count && lst1.Count == lst1.Intersect(lst2).Count();

You can also use an IEqualityComparer<T> with Intersect.
Update:
It seems you want to be able to compare any object even if they don't implement IEquatable<T>. Below is a sample of an equality comparer that will use IEquatable<T> if it's available, Enumerable.SequenceEqual if the type is a collection, and otherwise recursively check the public properties of the type using reflection:
class ReflectionComparer<T> : IEqualityComparer<T>
{
    public bool Equals(T x, T y)
    {
        Type type = typeof(T);
        if( typeof(IEquatable<T>).IsAssignableFrom(type) )
            return EqualityComparer<T>.Default.Equals(x, y);

        Type enumerableType = type.GetInterface(typeof(IEnumerable<>).FullName);
        if( enumerableType != null )
        {
            Type elementType = enumerableType.GetGenericArguments()[0];
            Type elementComparerType = typeof(ReflectionComparer<>).MakeGenericType(elementType);
            object elementComparer = Activator.CreateInstance(elementComparerType);
            return (bool)typeof(Enumerable).GetMethod("SequenceEqual")
                                           .MakeGenericMethod(elementType)
                                           .Invoke(null, new object[] { x, y, elementComparer });
        }

        foreach( PropertyInfo prop in type.GetProperties() )
        {
            Type propComparerType = typeof(ReflectionComparer<>).MakeGenericType(prop.PropertyType);
            object propComparer = Activator.CreateInstance(propComparerType);
            if( !((bool)typeof(IEqualityComparer<>).MakeGenericType(prop.PropertyType)
                                                   .GetMethod("Equals")
                                                   .Invoke(propComparer, new object[] { prop.GetValue(x, null), prop.GetValue(y, null) })) )
                return false;
        }
        return true;
    }

    public int GetHashCode(T obj)
    {
        throw new NotSupportedException();
    }
}

I didn't implement GetHashCode because it is not needed by Enumerable.SequenceEqual.
This should be able to do what you want (but be warned this is not exactly efficient; don't use this in performance critical code).

A: You will need to implement IEqualityComparer for your objects and then use that in Union method

A: Override Equals() and GetHashCode() methods in your Employee class
public class Employee
{
    public int EmpId { get; set; }
    public string EmpName { get; set; }
    public int EmpAge { get; set; }
    public string EmpSex { get; set; }

    public override bool Equals(object obj)
    {
        Employee other = obj as Employee;
        return null != other
               && other.EmpId == this.EmpId
               && other.EmpName == this.EmpName
               && other.EmpAge == this.EmpAge
               && other.EmpSex == this.EmpSex;
    }

    public override int GetHashCode()
    {
        return (EmpId + "_" + EmpName + "_" + EmpAge + "_" + EmpSex).GetHashCode();
    }
}

bool AreEqual<T>(IEnumerable<T> ls1, IEnumerable<T> ls2)
{
    return ls1.Count() == ls2.Count() && !ls1.Any(e => !ls2.Contains(e)) && !ls2.Any(e => !ls1.Contains(e));
}

    void Test()
    {
        Employee e1 = new Employee() { EmpAge = 20, EmpId = 123, EmpName = "XYZ", EmpSex = "M" };
        Employee e2 = new Employee() { EmpAge = 20, EmpId = 1232, EmpName = "XYZ", EmpSex = "M" };
        Employee e3 = new Employee() { EmpAge = 20, EmpId = 1232, EmpName = "XYA", EmpSex = "M" };
        Employee e4 = new Employee() { EmpAge = 20, EmpId = 1232, EmpName = "XYF", EmpSex = "M" };

        List<Employee> ls1 = new List<Employee>{e4, e3, e1, e2};
        List<Employee> ls2 = new List<Employee>{e1, e2, e3, e4};

        bool result = AreEqual(ls1, ls2); // true

        ls1 = new List<Employee>{e4, e3, e1, e3};
        ls2 = new List<Employee>{e1, e2, e3, e4};

        result = AreEqual(ls1, ls2); // false
    }

A: You might think of using reflection out here if you intended to compare two instances of any type BUT i am sure this is not the correct way , we are just taking advantage of framework.
as a hacked solution, you may see below code.
 static void Main(string[] args)
    {
        Employee e1 = new Employee() { EmpAge = 20, EmpId = 123, EmpName = "XYZ", EmpSex = "M" };
        Employee e2 = new Employee() { EmpAge = 20, EmpId = 123 , EmpName = "XYq", EmpSex = "M" };

        Person p1 = new Person() { Age = 20, name ="ABC"  };
        Person p2 = new Person() { Age = 20, name = "ABC" };

        Console.WriteLine("Employee Equality :" + IsObjectEquals(e1, e2).ToString());
        Console.WriteLine("Person Equality :" +IsObjectEquals(p1, p2).ToString());
        Console.ReadLine();
    }

    public static bool IsObjectEquals(object obj1, object obj2)
    {

       PropertyInfo[] props1 = obj1.GetType().GetProperties();
       PropertyInfo[] props2 = obj2.GetType().GetProperties();

       foreach (PropertyInfo pinfo in props1)
       {
           var val1 = pinfo.GetValue(obj1, null);
           var val2 = pinfo.GetValue(obj2, null);

           if (val1.ToString().Trim() != val2.ToString().Trim())
           {
                    return false;
           }

       }

       return true;

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: select some records and then update them simultaneuosly in asp.net c# I am developing a webservice in which I am fetching some records with select statement based on status and then I need to change the status.
Its like:
select * from tblx where status='x'

and then
update  tblx set status='y' where status='x' for the records fetched.
sample code:
 string getpaid = "select top2 * from tblfameface where img_f_p='paid'";
                con1 = new SqlConnection(conString1);
                con1.Open();
                SqlCommand cmd = new SqlCommand(getpaid, con1);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt1 = new DataTable();
                da.Fill(dt1);

                foreach (DataRow row in dt1.Rows)
                {
                    string updatepaid = "update tblfameface set img_f_p='free' where img_f_p='paid' ";
                    con1 = new SqlConnection(conString1);
                    con1.Open();
                    SqlCommand cmd1 = new SqlCommand(updatepaid, con1);
                    int temp = cmd1.ExecuteNonQuery();
                    con1.Close();
                }
}

I have no idea how to solve it.
Can I get any help??

A: Your Prototype is ok except your "Update" query.Rewrite your update query like
update tblx set status='y' where status=(select status from tblx where status='x');

As per your requirement:
string updatepaid = "update tblfameface set img_f_p='free' where img_f_p=(select top 2 img_f_p from tblfameface where img_f_p='paid')";
con1 = new SqlConnection(conString1);
con1.Open();
SqlCommand cmd1 = new SqlCommand(updatepaid, con1);
int temp = cmd1.ExecuteNonQuery();
con1.Close();

I hope it works for you.

A: Here Your update statement is wrong:
UPDATE <TABLE NAME> SET <Column> = <New Value> WHERE <Condition>

A: Here you can just execute a single update statement like below.
UPDATE YourTable
SET status='Y'
WHERE status='X'

A: Please, be more specific. Are you having problems with sql or c# ?
This could be helpful for C#:
http://msdn.microsoft.com/en-us/library/tyy0sz6b.aspx
and this for sql:
http://www.w3schools.com/sql/sql_update.asp

A: update tblx set status='y' where status='x';


text:
Q: ComInitialization property of ServerController I am new to IntraWeb. I want to make a simple application which connects and displays an access database using ADO controls. When I execute the server it gives me

"CoInitialize has not been called"

error. I searched the internet and found many text telling that

Change ComInitialization property of
  IWServerController to ciMultiThreaded.

I tried to do this in IWAppFormCreate event. Then I got compilation error:

"Undeclared Identifier ciMultiThreaded"

I put the line IWServerController.ComInitialization:=ciMultiThreaded; then the runtime error comes up:

"Access violation at address . . ."

Since I don't know what I am doing I cant find the problem. Please help me.

A: The CoInitialize error on IntraWeb using ADO gives you the correct answer.
As I catch from comments on @David answer to this question, there are two things left:

*

*Where is declared the TComInitialization type, which in turns defines the ciMultiThreaded identifier.
Answer to this is: IWServerControllerBase unit, part of Intraweb.

*Where to change the ComInitialization property of the IWServerController object to get this working.

*

*The first thing you have to know is the actual class used to construct the IWServerController object is part of your IntraWeb project.

*Next, trying to set this property on a page OnCreate event looks too late (it must be created in the thread you want to initialize COM), my guess is that altering this property at this time is forbidden and will raise an exception, or will be ignored completely.

*Using the Delphi XE VCL for the Web Application wizard I got a unit named ServerController, with the class TIWServerController.  After failing to override the constructor, I override the AfterConstruction method to initialize such property, like this

Example:
  TIWServerController = class(TIWServerControllerBase)
    procedure IWServerControllerBaseNewSession(ASession: TIWApplication;
      var VMainForm: TIWBaseForm);

  private

  protected
    //constructor Create; override;  //failed!!
  public
    procedure AfterConstruction; override;
  end;

  //..

procedure TIWServerController.AfterConstruction;
begin
  inherited;
  ComInitialization := ciMultiThreaded;  //succeded
end;

I then added a button, a label and properly configured ADOConnection (against SQL Server if that matters) and:
procedure TIWForm2.IWButton1Click(Sender: TObject);
begin
  try
    ADOConnection1.Connected := True;
    IWLabel1.Caption := 'Connected';
  except
    on E:Exception do
      IWLabel1.Caption := E.ClassName + ' ' + E.Message;
  end;
end;

Hitting the button, produces this:

Hope this is enough to you.

A: It sounds like you haven't initialized COM, which you are required to do by calling CoInitializeEx(). From the documentation:

CoInitializeEx must be called at least
  once, and is usually called only once,
  for each thread that uses the COM
  library. Multiple calls to
  CoInitializeEx by the same thread are
  allowed as long as they pass the same
  concurrency flag, but subsequent valid
  calls return S_FALSE. To close the COM
  library gracefully on a thread, each
  successful call to CoInitialize or
  CoInitializeEx, including any call
  that returns S_FALSE, must be balanced
  by a corresponding call to
  CoUninitialize.

A: If you used the IntraWeb Application Wizard in XE2, it would of created a ServerController.pas unit for you.
If you open that unit in the visual designer, and click on the "form", you'll see a slew of properties for the TIWServerController. One of those is ComInitialization, which is a dropdown containing ciMultiThreaded, ciNone, ciNormal. It defaults to ciNone.
Here is the DFM after I changed the ComInitialization property:
object IWServerController: TIWServerController
  OldCreateOrder = False
  AuthBeforeNewSession = False
  AppName = 'MyApp'
  CharSet = 'UTF-8'
  CacheExpiry = 120
  ComInitialization = ciMultiThreaded
  Compression.Enabled = False
  Compression.Level = 6
  Description = 'My IntraWeb Application'
  DebugHTML = False
  DisplayName = 'IntraWeb Application'
  Log = loNone
  EnableImageToolbar = False
  ExceptionDisplayMode = smAlert
  HistoryEnabled = False
  InternalFilesURL = '/'
  JavascriptDebug = False
  PageTransitions = False
  Port = 8888
  RedirectMsgDelay = 0
  ServerResizeTimeout = 0
  ShowLoadingAnimation = True
  SessionTimeout = 10
  SSLOptions.NonSSLRequest = nsAccept
  SSLOptions.Port = 0
  SSLOptions.SSLVersion = sslv3
  Version = '12.0.8'
  OnNewSession = IWServerControllerBaseNewSession
  Height = 310
  Width = 342
end

Hope this helps some.


text:
Q: Express module that requires express In my first NodeJS Express app, I installed express-couchUser.  From the root directory of my app I just used npm install --save express-user-couchdb and it was downloaded and installed just like I expected.  What makes me hesitate is that I now have a directory structure like this:
~/project$ find . -type directory -name "express"
./node_modules/express
./node_modules/express-user-couchdb/node_modules/express
~/project$ find . -type directory -name "express" -exec sh -c "cd {}; grep version  package.json " \;
  "version": "4.9.7",
  "version": "3.2.6",

So this seems express-user-couchdb requires express, and it uses it to server up some API routes like api/user/signup.  I get this but it seems wrong to have two different versions of express like this.  Have I gone wrong or is this normal?

A: You have not done anything wrong. Node modules can define their own dependencies and own dependency versions. If you look at the express-user-couchdb module dependencies you can see it is looking for 3.2.6 (https://github.com/twilson63/express-couchUser/blob/master/package.json#L23) So any code within that module will use the express code for it's specified version.
You application is using a later version of express, so when you interact with express code you will be using the version your application requires.
Quickly looking at the express-user-couchdb docs it seems you can use a simple express 'use' to load it up in your express application, this is supported in your version of express so you shouldn't experience an issue.


text:
Q: Polynomial and distinct roots Find all real m such that $x^3-2x^2-2x+m$ has 3 distinct rational roots.
Source: School exam paper. No idea why it seems so hard
I don't think rational root theorem works, since m is not necessarily integer (clearly it is rational though)
Assuming $m=\frac{r}{s}$, we need to check $sx^3-2sx^2-2sx+r=0$ for all $s,r$ coprime...

A: Let $a, b, c$ be the rational roots. Then we have
$$a+b+c=2,\quad ab+bc+ca=-2, \quad m=-abc.$$
Replace $c=2-a-b$,
$$a^2+b^2+ab-2(a+b)-2=0.$$
(If $a=b$, then $a$ is irrational) Thus,
$$\Delta_b=(a-2)^2-4(a^2-2a-2)=-3a^2+4a+12$$
is a square rational.
The rest is easy.
Added after diner. Since
$$-3a^2+4a+12=-3(a+\frac{2}{3})^2+4\times \frac{10}{3}$$
is a square. Let $\frac{3}{2}(a+\frac{2}{3})=\frac{p}{q}$ (suppose $\gcd(p,q)=1$), then
$$-3p^2+30 q^2$$
is a square of integer, say $3r$, thus
$$-p^2+10q^2=3r^2.$$
It is clear that $2|p-r$. If both are even, then $q$ is even too, contradicting $\gcd(p,q)=1$. So $p$ and $r$ both are odd, then $p^2+3r^2=4 \mod(8)$, therefore $q$ is even, hence $10q^2=0 \mod (8)$, this is an contradiction with $p^2+3r^2=10 q^2$.
If I didn't make mistake,  Conclusion: there is no $a, b, c$, there is  no $m$.

A: HINT:
Use Repeated Root Theorem to identify the values of $m$  giving repeated roots


text:
Q: period in string doesn't get replaced I have a string "messages.get.342" that I want to convert to "messages/get/342". Unfortunately, when I call "messages.get.342".replace('.', '/'), I get "messages/get.342". What gives?

A: Use Regular Expression
 "messages.get.342".replace(/\./g, '/')

A: You need to use a regular expression with the global flag to replace ALL instances of the period:
document.write("messages.get.342".replace(/\./g, '/'));

A: You need to use a global replace with regex like this.
"messages.get.342".replace(/\./g, '/');

Edit:
You can also do it like this; it is a little longer but can be less confusing.
var myString = "messages/get/342";
var regex = new RegExp(/\./, "g");
myString = mystring.replace(regex, myString);

You have the following three options available to you with the javascript regex object:

*

*i - case insensitive matching

*g - global matching

*m - multiline matching

You can use the other two options in replace of the g (/i or "i") or in combination with the g (/gi or "gi").

A: Do it globally:
"messages.get.342".replace(/\./g, '/')

The \. is an escaped period, and the slashes around it indicate a pattern match. You have to escape a literal period if you're doing a pattern match. The g means global, i.e., match and replace all occurrences, not just the first.

A: Don't use replace for strings. "messages.get.342".split('.').join('/') is recommended.


text:
Q: com.microsoft.azure.storage.StorageException: Server encountered an internal error. Please try again after some time Facing this Azure issue -
Storage exception occurred while getting storage containers and disks.

    com.microsoft.azure.storage.StorageException: Server encountered an internal error. Please try again after some time.

Could anyone please help me get past through this issue ? Thanks.
Researched in google, but could not find any right way to fix this.


text:
Q: SQL or operator how to use with having i have a table which i am joining with with operator. I can have 2 combinations id that table FDEL - 1 or 0 and FDVE 1 or 0, what i would like to do is to dispay if - item has fdve, or item has fdel (and count) but it doesnt work (i can see all fdve, or all fdel)
select
    lpad(purchase_id,10,0) as purchase_id,
   sum(has_label_fdel) as FDEL_count,
    case when  LABELS   like '%FDVE%' then 1 else 0 end as HAS_LABEL_FDVE,
    sum(has_label_fdve) as FDVE_count
 from
    "SRC_ORACLEIWP"."PURCHASE_ANALYSIS_RULES"
    group by
    lpad(purchase_id,10,0),has_label_fdve

having  FDVE_count>0 -- FDEL_count>0

A: You want one resut row per product, so group by product only. Use SUMfor counting and MAX for the aggregated yes/no.
select
  lpad(purchase_id,10,0) as padded_purchase_id,
  max(has_label_fdve) as has_labels_fdve,
  sum(has_label_fdve) as fdve_count,
  max(has_label_fdel) as has_labels_fdel,
  sum(has_label_fdel) as fdel_count
from src_oracleiwp.purchase_analysis_rules
group by padded_purchase_id
having has_labels_fdve = 1
    or has_labels_fdel = 1
order by padded_purchase_id;

I've changed your alias names slightly, so they are digfferent from the columns you have (because such ambiguities can sometimes lead to problems).
The check on labels like '%FDVE%' is unnecessary, because you already have the has_label_fdve flag, which is always 0 or 1. Or so it seems. If the flags can be null, use COALESCE on them or do use LIKE expressions.
If you don't have has_label_fdve and has_label_fdel yet, use the labels column instead:
select
  lpad(purchase_id,10,0) as padded_purchase_id,
  max(case when labels like '%FDVE%' then 1 else 0 end) as has_labels_fdve,
  sum(case when labels like '%FDVE%' then 1 else 0 end) as fdve_count,
  max(case when labels like '%FDEL%' then 1 else 0 end) as has_labels_fdel,
  sum(case when labels like '%FDEL%' then 1 else 0 end) as fdel_count
from src_oracleiwp.purchase_analysis_rules
group by padded_purchase_id
having has_labels_fdve = 1
    or has_labels_fdel = 1
order by padded_purchase_id;


text:
Q: How do I model group memberships in Cassandra? What would be an optimal way to implement group memberships in Cassandra? I need the following operations:

*

*Create a new group with an optional list of initial members.

*Delete a group.

*Add a user to a group.

*Delete a user from a group.

*List all members of a group.

*List all group memberships.

90%+ (maybe even 99%) of all operations on the DB would be listing all members of a group. There's the choice between using sets for maintaining the memberships of a group vs. making each member of a group a row on its own. The load is fairly significant requiring a large cluster.
Users would be just identified by their ID, which is a short string. Groups would only need to be identified by a string like a UUID. No names or other metadata needed.
The biggest challenge is how to support listing all group memberships efficiently. Any recommendations?

A: The first principle of data modelling in Cassandra is design a table for each application query. You need to list the application queries first THEN design a table for each of those app queries.
DBAs from a relational background typically do the reverse -- they tend to focus on worrying about how the data is structured on the table then later try to design queries for the app. This however does not work when it comes to Cassandra because the tables end up not being optimised for the app queries.
In your case, the application query looks something like:

Retrieve the list of user IDs for group ID X.

Rewriting this in something more SQL-like:
SELECT userid FROM table WHERE groupid = X

This app query indicates that the table needs to be partitioned by the group ID (groupid) which contains one or more rows of user IDs (userid). The design (schema) for this table looks something like:
CREATE TABLE groups (
    groupid uuid,
    userid text,
    ...
    PRIMARY KEY (groupid, userid)
)

When you query this table with:
SELECT userid FROM groups WHERE groupid = ?

it will return one or more rows of userid. Cheers!


text:
Q: Clear pageup/pagedown panning values after clear and reload content in wpf richtextbox? i am working in wpf richtextbox.use the below function use for page up.
TextRange range10 = new TextRange(txtAppendValue.CaretPosition.GetLineStartPosition(1), txtptrCaret);

                FrameworkContentElement fce1 = (range10.End.Parent as FrameworkContentElement);
                if (fce1 != null)
                {
                    fce1.BringIntoView();
                    range10 = null;
                    fce1 = null;
                }

its working.After i clear the richtextbox and load some other content,at that time the content shown where the pageup happened in last time?how to clear when i reload the document.
Updated:
public void HideTopBorder()
        {
            TextPointer currentline = txtAppendValue.CaretPosition.GetLineStartPosition(1);
            System.Windows.Rect rc = currentline.GetCharacterRect(LogicalDirection.Forward);
            System.Windows.Point upperLeftCorner = rc.Location;
            HitTestResult result = VisualTreeHelper.HitTest(txtAppendValue, upperLeftCorner);
            if (result == null)
            {

                Thickness margin = txtAppendValue.Margin;
                margin.Top = -20;
                txtAppendValue.Margin = margin;
                currentline = null;
            }
            else
            {
                currentline = null;
            }

        }

After the result null only pageup happened.at that time i clear the document and load an another document.But now show the richtextbox where the already panned point.not top of the document.
Regards
Arjun

A: Before you load a new document save the value of rtb.VerticalOffset. Then load the new document and reassign the stored value to rtb.VerticalOffset.


text:
Q: How we can update multiple tables in mysql How can update multiple tables using single query.I have to update two tables at a time. I tried this query but it fails to update
UPDATE  contact,bill SET companyid =2  WHERE  userid=1 AND companyid =20;

A: This should work.
UPDATE contact INNER JOIN bill SET companyid =2 WHERE userid=1 AND companyid =20;

Or to prevent conflicts.( Unsure of your table layout but heres the rough idea )
UPDATE contact x INNER JOIN bill y SET x.companyid =2 WHERE x.userid=1 AND y.companyid =20;

A: If the reason you "have to update two tables at a time" is to ensure that the changes don't get half done, then you may want to consider wrapping your queries in a transaction:
START TRANSACTION;
UPDATE ...
UPDATE ...
COMMIT;

(Or whatever the MySQL syntax is...)

A: You cannot update in the same time.
UPDATE contact SET companyid=2 WHERE userid=1 AND companyid =20;
UPDATE bill    SET companyid=2 WHERE userid=1 AND companyid =20;


text:
Q: Kafka Transaction with IBM MQ transaction Всем привет. Кейс следующий :
1 Открыть транзакцию Kafka
2 Открыть транзакцию MQ
3 отправить сообщение в топик кафка
4 отправить сообщениу в MQ
5 отправить сообщение в другой топик кафка
6 закрыть транзакцию Кафка
7 закрыть транзакцию МКу
Если происходит ошибка на каком-то шаге, то делаем роллбек
Как это можно осуществить ? Читал про ChainedTransaction но проблема в том что класс Deprecated. Есть какие-то другие варианты? Желательно с примерами.


text:
Q: In the Yii framework how is the situation handled where 2 independant models are to be called in a single view? I am a Yii newbie who is trying to understand how this particular situation would be handled.
If I have 2 models,
The first model contains date and other information pertaining to the model.
The second model contains date and information pertaining to the second model.
I want to have a search where I enter the date - from there the information from both the first and second model are pulled and displayed for the given date.
What is the proper way to structure this in Yii?
Would I just add an action to one of the controllers? This seems somewhat arbitrary, as neither model is really connected to the other, besides the date.
Or do I just create a controller with no related model?
Your feedback is appreciated, as I am trying to understand the idea behind Yii.
I know there is a blog example, but in that case it would seem that the "post" model is the "main" element, and "comments" would be pulled and displayed for the relevant "post". But in my situation I'm curious how it is ideally structured, where the 2 models don't really have that kind of dependancy, but instead their only connection is the date.
Thank you.

A: First, properly define relations in your table/model.
Your controller code will change a bit to process both the models.
$model1= new ModelOne;
$model2= new ModelTwo;

Do the processing, loading model data/setting attributes etc..
Pass both the models instance to view.
$this->render('view',array(
    'model1'=>$model1,
    'model2'=>$model2,
    ));

In the view you can define fields/grid etc that renders data from both the models. You have to define/specify which associates with which fields.

A: Yii is a MVC pattern. This means that a part of code stay on M (Model) and another in V (View) and another one in (C) Controller. You can find all your models in protected/models, all views in protected/views and so on.
A controller will render a view with model. Model is all the data you send to view. Model can be a variable, a record, an entire resultset. In controller you can make all query you need, and then you can put results into the view.
It's easy.
Or do I just create a controller with no related model?

Any controller has a related model. May you can be confused reading StuffController that is a controller and Stuff that is a model. This just means that Stuff model aims to work with stuff table. This also means that a controller has a lot of action that works with Stuff content.
All actions that works with post, can be putted in PostController. All action that works with a calendar, can be putted in a CalendarController. But Models and Controllers are logically separated.
So, ... an example
class DogController extends Controller {
    public function actionBark() {
        $this->render('theView', array(
            'varName' => 333
        ));
    }
}

This, in Yii's MVC, just means that:
 - Controller: is DogController
   - actionBark is an action that regards a Dog
 - Model: the model is '333'
 - View: the view is protected/views/dog/theView.php file and inside it the model is $varName that will be equals to 333. Model are data, and not necessary a record of a class that extends CActiveRecord or CModel.


text:
Q: Can I host html5shiv and respond.js on a cdn? Is it possible to host html5shiv and respond.js from a cdn or do I have to call them locally?
currently I have integrated html5shiv and respond.js from cdn and selectivizr locally, I can leave everything as it is or I have to host them locally ^
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
  <script src="js/selectivizr-min.js"></script>
<![endif]-->

A: I just wanted to know if html5shiv and respond.js worked without any problems if they are hosted by cdn


text:
Q: roots of unity with LCM
Possible Duplicate:
GCD and roots of unity

If we have some roots of unity $\zeta$ and $\rho$, in which $o(\zeta)=a$
and $o(\rho)=b$,  can we prove that  $o(\zeta\rho)=\operatorname{lcm}[a,b]$? If not, can we prove that this is not true?


text:
Q: Derivation of AdaBoost.R2 algorithm I am having difficulty understanding the derivation of the AdaBoost.R2 algorithm (AdaBoost for regression problems), as presented in this paper by Drucker (page 2), which seems to be the source that people cite when referring to it. Notably, sklearn's (the python library) implentation is based on this paper. He says it is a modification of the AdaBoost.R algorithm proposed by Freund and Schapire here (page 136).
There are 2 questions I have:

*

*Why is the final prediction of AdaBoost.R2 the weighted median of all of weak learners? This is in contrast to AdaBoost for classification problems, which takes a weighted average.

*It is my understanding (from section 10.4 in Hastie's Elements of Statistical Learning) that AdaBoost for classification can be understood as gradient boosting (Hastie, algorithm 10.2) with the exponential loss function $L=\exp(-y \,f(x))$, where $y$ is the target class and $f(x)$ is our prediction. It is a straightforward exercise to show that the AdaBoost.M1 algorithm (algorithm 10.1 in Hastie) follows from this approach. AdaBoost for regression does not use the exponential loss function, but can it, too, be derived in a similar manner?

Finally, in general, if there are any other sources that go over AdaBoost's implementations for regression problems (not necessarily just for regression trees), I would appreciate any links.
Thank you!

A: *

*The choice to use the weighted median appears to be arbitrary. According to this "the
idea of using the weighted median as the final regressor is not new. Freund [6] briefly mentions it and proves a special case of the main theorem of this paper. The ADABOOST.R algorithm of Freund and Schapire [7] returns the weighted median but the response space is restricted to [0;1] and the parameter updating steps are rather complicated. Drucker [4] also uses the weighted median of the base regressors as the final regressor but the parameter updates are heuristic and the convergence of the method is not analyzed."
That crazy formula with the logs in it is evidently only one way to solve for the median; IBM gives a different formula.

It is possible the researchers liked this evaluation method because they thought it was more robust to noise or something, but I am not sure whether their reasons were well-founded. The author of the first paper seems to just like median-based approaches because they generalize AdaBoost, not because they are by some metric better.

*Yes, in the classification case it is easy to recognize that the exponential in $(\gamma_m, G_m) = arg \min_{\gamma,G} \sum_{i=1}^n e^{-y_i(f_{m-1}(x_i) + \gamma G(x_i))}$ can be broken up to give $w_i = e^{-y_i f_{m-1}(x_i)}$ (the exponential loss of the model thus far), which blows up as y and f(x) diverge, which has famously ill effects in cases where outliers or mislabeled data are present. But in AdaBoost.R the weights are updated according to complicated formulas, and in AdaBoost.R2 the updates are given by $\beta^{1-L_i} = (\frac{\bar{L}}{1-\bar{L}})^{1-L_i}$, which has this funky shape (qualitatively, since $\bar{L}$ and $L_i$ are related but not exactly the same thing) that actually weights the examples with the greatest loss as not-as-important as the ones with slightly less error, which probably actually helps make it more resilient to outliers. These update rules do not just fall out of the loss function; they are constructed on top of the loss function. All a loss function is supposed to do is answer the question "How far away am I?" What you do once you know doesn't need to be related to how you measure. It can be a "heuristic". You might even engineer in some features like noise tolerance. It would be nice if Drucker proved his choice is a good one, but what matters to most people is that it seems to work in practice.


text:
Q: Case statement with more than one condition I need to fetch records from a table based on days visited. How can I achieve this by correcting the query below? It has syntax error(s). I know the syntax is incorrect, but it will give you an idea on what I want to achieve.
DECLARE @PatientByDate INT
 SET @PatientByDate  = 30
    SELECT * FROM Visits
     WHERE
    CASE
           WHEN(@PatientByDate = 90) then DaysVisited > 90
           WHEN(@PatientByDate = 60) then DaysVisited >= 60 AND DaysVisited < 90
           WHEN(@PatientByDate = 30) then DaysVisited >= 30 AND DaysVisited < 60
           WHEN(@PatientByDate = 25) then DaysVisited < 30
           WHEN(@PatientByDate = 0) then -500 AND <= 5000000
      END

A: Do it directly combining predicates with or:
SELECT * FROM Visits
WHERE
    (@PatientByDate = 90 and DaysVisited > 90) or
    (@PatientByDate = 60 and DaysVisited >= 60 and DaysVisited < 90) or
    (@PatientByDate = 30 and DaysVisited >= 30 and DaysVisited < 60) or
    (@PatientByDate = 25 and DaysVisited < 30) or
    (@PatientByDate in(0, -500))

A: You have to move them all to the When clause and match it to the returned value (=1):
DECLARE @PatientByDate INT
SET @PatientByDate  = 30
SELECT * FROM Visits
WHERE 1 = CASE
    WHEN(@PatientByDate = 90) AND DaysVisited > 90 then 1
    WHEN(@PatientByDate = 60) AND DaysVisited >= 60 AND DaysVisited < 90 then 1
    WHEN(@PatientByDate = 30) AND DaysVisited >= 30 AND DaysVisited < 60 then 1
    WHEN(@PatientByDate = 25) AND DaysVisited < 30 then 1
    WHEN(@PatientByDate = 0) AND -500 AND <= 5000000 then 1
END

Or simply do:
DECLARE @PatientByDate INT
SET @PatientByDate  = 30
SELECT * FROM Visits
WHERE
    ((@PatientByDate = 90) AND DaysVisited > 90) OR
    ((@PatientByDate = 60) AND DaysVisited >= 60 AND DaysVisited < 90) OR
    ((@PatientByDate = 30) AND DaysVisited >= 30 AND DaysVisited < 60) OR
    ((@PatientByDate = 25) AND DaysVisited < 30) OR
    ((@PatientByDate = 0) AND -500 AND <= 5000000)


text:
Q: CURL Post looping I am running a script which uploads a file to remote form
  //submit form
  $form_data = array("file_upload" => "@file.xml;type=text/xml","otherkey" => "overvalue");
  $ch = curl_init();
  $form_url = 'http://www.domain.com/form.php';
  curl_setopt($ch, CURLOPT_URL, $form_url);
  curl_setopt($ch, CURLOPT_POST, 1 );
  curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  $postResult = curl_exec($ch);
  echo $postResult;

The file is being uploaded perfectly, however on the remote server, after file upload and processing the page is reloaded (form.php), however the CURL post simply begins again.
I am guessing this is due to the POST data still being present? how can I do this so that the file is uploaded once, processed and then completed? I have set FOLLOWLOCATION = 0 but with no luck
Many thanks,

A: How do you know it begins again? If you infer it from your echo, it is echoed twice as you write this:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); //echoes result at init

instead of this
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //returns only result, not echoing


text:
Q: SpringBoot Autowired Exception from external JAR I have a SpringBoot Application that works with another external JAR. When I try to @Autowired classes from the JAR , the SpringApp fails to load. I got "org.springframework.beans.factory.NoSuchBeanDefinitionException". I know this has to do with SpringBoot not searching where the project classes are, but I can't figure out how to correctly tell where to look. I've added @ComponentScan, it worked with other internal classes, but not with this External JAR.
This is the class where I use the JAR methods:
package ar.com.tr.latam.care.ws.service.impl;

@Configuration

@ComponentScan({
"ar.com.tr.arz.expurgo", "ar.com.tr.arz.expurgo.logger", "ar.com.tr.arz.expurgo.logger.dao", "ar.com.tr.arz.expurgo.logger.impl","ar.com.tr.arz.expurgo.logger.model"})

@Import({ AppConfig.class, AplicacionCriteriosExpurgoServiceImpl.class, ClasificacionServiceImpl.class, ExcelReaderServiceImpl.class, ConversionServiceImpl.class})

@Service
public class ArzServiceImpl implements ArzService {

@Autowired
private ExcelReaderService excelReaderService;

@Autowired
private ConversionService conversionService;

@Autowired
private AppConfig appConfig;

...
}

And my Init.java class:
package ar.com.tr.latam.care;
@Configuration
@ComponentScan({ "ar.com.tr.latam.care.controller",
"ar.com.tr.latam.care.filtro", "ar.com.tr.latam.care",
"ar.com.tr.latam.care.model.log", "ar.com.tr.latam.care.logger.impl", })

@EnableJpaRepositories
@SpringBootApplication

public class Init extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder     application) {
    return application.sources(Init.class);
}

/**
 * Main method.
 *
 * @param args String[].
 * @throws Exception Exception.
 */
public static void main(String[] args) throws Exception {
    SpringApplication.run(Init.class, args);
}
}

The JAR structure starts with "ar.com.tr.arz.expurgo" , but I can't find how to properly tell Springboot to check for those files there.
The error is "Could not autowire field: private ar.com.tr.arz.expurgo.services.ClasificacionService"
I've also tried adding the external JAR classes in the @ComponentScan Init class, but it also didn't work.
Any suggestions?

A: I was able to solve it.
First I remove the @ComponentScan from the @Service, and only called it in my Init.java class (Start of the application)
THen I changed my Init packagein order to be on an upper level of the jar classes :
My Init.java was under package ar.com.tr.latam.care, the External JAR package classes were under: package ar.com.tr.expurgo. So, I changed my Init.java to be in package ar.com.tr, and every worked!


text:
Q: Using 'GROUP BY' while preferring rows associated in another table I have a table tbl_entries with the following structure:
+----+------+------+------+
| id | col1 | col2 | col3 |
+----+------+------+------+
| 11 |    a |    b |    c |
| 12 |    d |    e |    a |
| 13 |    a |    b |    c |
| 14 |    X |    e |    2 |
| 15 |    a |    b |    c |
+----+------+------+------+

And another table tbl_reviewlist with the following structure:
+----+-------+------+------+------+
| id | entid | cola | colb | colc |
+----+-------+------+------+------+
|  1 |    12 |    N |    Y |    Y |
|  2 |    13 |    Y |    N |    Y |
|  3 |    14 |    Y |    N |    N |
+----+-------+------+------+------+

Basically, tbl_reviewlist contains reviews about the entries in tbl_entries. However, for some known reason, the entries in tbl_entries are duplicated. I am extracting the unique records by the following query:
SELECT * FROM `tbl_entries` GROUP BY `col1`, `col2`, `col3`;

However, any one of the duplicate rows from tbl_entries will be returned no matter they have been reviewed or not. I want the query to prefer those rows which have been reviewed. How can I do that?
EDIT: I want to prefer rows which have been reviewed but if there are rows which have not been reviewed yet it should return those as well.
Thanks in advance!

A: Have you actually tried anything?
A hint: The SQL standard requires that every column in the result set of a query with a group by clause must be either

*

*a grouping column

*an aggregate function — sum(), count(), etc.,

*a constant value/literal, or

*an expression derived solely from the above.

Some broken implementations (and I believe MySQL is one of them) allow other columns to be included and offer their own...creative...behavior. If you think about it, group by essentially says to do the following:

*

*Order this table by the grouping expressions

*Partition it into subsets based on the group by sequence

*Collapse each such partition into a single row computing the aggregate expressions as you go.

Once you've done that, what does it mean to ask for something that isn't uniform across the collapsed group partition?
If you have a table foo containing columns A, B, C, D and E and say something like
select A,B,C,D,E from foo group by A,B,C

per the standard, you should get a compile error. Deviant implementations [usually] treat this sort of query as the [rough] equivalent of
select *
from foo t
join ( select A,B,C
       from foo
       group by A,B,C
     ) x on x.A = t.A
        and x.B = t.B
        and x.C = t.C

But I wouldn't necessarily count on that without review the documentation for the specific implementation that your are using.
If you want to find just reviewed entries, then something like this:
select *
from tbl_entries t
where exists ( select *
               from tbl_reviewlist x
               where x.entid = t.id
             )

will do you. If, however, you want to find reviewed entries that are duplicated on col1, col2 and col3 then something like this should do you:
select *
from tbl_entries t
join ( select col1,col2,col3
       from tbl_entries x
       group by col1,col2,col3
       having count(*) > 1
     ) d on d.col1 = t.col1
        and d.col2 = t.col2
        and d.col3 = t.col3
where exists ( select *
               from tbl_reviewlist x
               where x.entid = t.id
             )

Since your problem statement is rather unclear, another take might be something along these lines:
select t.col1            ,
       t.col2            ,
       t.col3            ,
       t.duplicate_count ,
       coalesce(x.review_count,0) as review_count
from      ( select col1 ,
                   col2 ,
                   col3 ,
                   count(*) as duplicate_count
            from tbl_entries
            group by col1 ,
                     col2 ,
                     col3
          ) t
left join ( select cola, colb, colc , count(*) as review_count
            from tbl_reviewList
            group by cola, colb, colc
            having count(*) > 1
          ) x on x.cola = t.col1
             and x.colb = t.col2
             and x.colc = t.col3
order by sign(coalesce(x.review_count,0)) desc ,
         t.col1 ,
         t.col2 ,
         t.col3

This query

*

*summarizes the entries table, developing a count of how many time seach col1/2/3 combination exists.

*summarizes the review table, developing a count of reviews for each cola/b/c combination

*joins them together matching cols a:1, b:2 c:3

*orders them

*

*preferring reviewed items to non-reviewed items by placing them first,

*then by the col1/2/3 values.

A: I think there's a way with less repetition, but this should be a start:
select
  tbl_entries.ID,
  col1,
  col2,
  col3,
  cola, -- ... you get the idea ...
from (
select coalesce(min(entid), min(tbl_entries.ID)) as favID
from tbl_entries left join tbl_reviewlist on entid = tbl_entries.ID
group by col1, col2, col3
) as A join tbl_entries on tbl_entries.ID = favID
left join tbl_reviewlist on entid = tbl_entries.ID

Basically you distill the desired output to a list of core ID's and then re-map back to the data...

A: SELECT e.col1, e.col2, e.col3,
       COALESCE(MIN(r.entid), MIN(e.id)) AS id
FROM tbl_entries AS e
  LEFT JOIN tbl_reviewlist AS r
    ON r.entid = e.id
GROUP BY e.col1, e.col2, e.col3 ;

Tested at SQL-Fiddle


text:
Q: Is exposing the API Key from Firebase at url/firebase-messaging-sw.js a security risk? I've noticed that the API Key of Firebase can be easily accessed on the website I'm managing through url + firebase-messaging-sw.js. I've got mixed answers online when searching for this issue. Is this a security issue I should be concerned about? If so, how can I block access to this URL?
I've searched about the problem and got mixed kind of answers. So far, I don't know if it is a security issue, if blocking access to this URL will affect other things like notifications, or how would I block it in the first place.

A: The API key is safe to share. Puf has answered this in this stack overflow post.
The reason is that direct database access is the desired outcome in Firebase and security is implemented server side through the use of security rules.


text:
Q: Can't install software - setup not loading I'm running Windows XP SP3, and I'm trying to install either Coffee Cup HTML Editor, or HTML-Kit.  Double-clicking either setup file produces no installer GUI.  They both in appear in Task Manager but do nothing else.  I have more than 30GB of free space on C:
To other annoying things are: MS Paint will not close, and after Computer Management loads it freezes.  I can't end mmc.exe either.
When I open Services.msc, I receive the error:

One or more ActiveX controls could not be displayed because either:
1) Your current security settings prohibit running ActiveX controls on this page, or
  2) You have blocked a publisher of one of the controls.
As a result, the page might not display correctly.

I can't close Services either.  I wanted to restart Windows Installer.
Avast Antivirus control centre freezes after opening also.

A: Surprise, rebooting fixed it.  I've only been using Windows for 17 years.


text:
Q: don't Return file to Editor in httpHandler on Asp.net web forms I use httpHander to Upload file and return it to Editor .
It's Save file but doesn't return image to editor . my code to do this is :
 public void ProcessRequest(HttpContext context)
    {
        HttpPostedFile file = context.Request.Files["file"];
        string path=HttpContext.Current.Server.MapPath("~")+"/Images/"+file.FileName;
        file.SaveAs(path);
        context.Response.ContentType = "image/jpeg";
        context.Response.Write("<img src='"+path+"'/>");
    }

and my config of redactor is:
                <script type="text/javascript">
                    $(document).ready(function () {
                        $(".editor").redactor({
                            imageUpload: "Upload.ashx/ProcessRequest()",
                            fileUpload: "Upload.ashx/ProcessRequest()",
                            linkFileUpload: "Upload.ashx/ProcessRequest()"
                            ,autoformat: false
                            , convertDivs: false
                        });

                    });
</script>

and :
    <asp:TextBox runat="server" ID="txtContnt" TextMode="MultiLine" CssClass="editor"></asp:TextBox>

My editor is :redactor and I use asp.net web forms .
httphandler work very well but don't return file to editor

A: Your path is incorrect. Server.MapPath returns an absolute (file system) path, not a path that the web browser can use. Also, according to this document, the expected response is a JSON string, not an img tag.
public void ProcessRequest(HttpContext context)
{
    HttpPostedFile file = context.Request.Files["file"];
    string virtualPath = "/Images/" + file.FileName;
    string path=HttpContext.Current.Server.MapPath("~") + virtualPath;
    file.SaveAs(path);
    context.Response.ContentType = "image/jpeg";
    context.Response.Write(@"{ 'filelink': '" + virtualPath + "' }");
}


text:
Q: Creating a Py_buffer from an array in c++ I am trying to extend my python code by creating a c++ module. I am able to import my c++ code by calling 'import my_code' in python with no problem. My issue occurs when I try to return the PyObject. I want to take a vector *settled_nodes_vector that I have created from my c++ code and write the data from that vector as binary data to a buffer and return that buffer. Right now I am doing this:
PyBuffer_FromReadWriteMemory((void *) settled_nodes_vector->data(), settled_nodes_vector->size() * sizeof(result_node)));

and when I call the following in python
>>> import my_module
>>> result = my_module.make_buffer()
>>> result
<read-write buffer ptr 0x7fae708c5010, size 20335840 at 0x7fae899577b0>
>>> len(result)
20335840
>>> result[0]
92121 Segmentation fault    (core dumped) python -i

So my question is how is it that I can't index my information in my result when it is a non-zero length.


text:
Q: Spring MVC with Java based config - 404 not found for static resources I'm trying out Spring MVC with java config and I'm getting 404 not found for static resources, the folder of which I can confirm is definitively getting published to the server. It seems like the resources are not being resolved at all. So even when calling localhost:8080/SpringMVC/resources/js/jquery-1.4.2.min.js I get 404 not found. I'm using Spring 4.0.1
Deployed structure
SpringMVC/
   resources/
      css/
      js/
         jquery-1.4.2.min.js
   WEB-INF/
      classes/
      lib/
      views/
         services.jsp
      web.xml

My Code:
com/me/config/WebApplicationConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.me.services"})
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    private static final String VIEW_RESOLVER_SUFFIX = ".jsp";
    private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/views/";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public ViewResolver setupViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();

        resolver.setPrefix(VIEW_RESOLVER_PREFIX);
        resolver.setSuffix(VIEW_RESOLVER_SUFFIX );
        resolver.setViewClass(JstlView.class);

        return resolver;
    }
}

com/me/config/Initializer.java
public class Initializer implements WebApplicationInitializer {

    private static final String DISPATCHER_SERVLET_MAPPING = "/";
    private static final String DISPATCHER_SERVLET_NAME = "dispatcher";

    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(WebApplicationConfig.class);
        rootContext.setServletContext(servletContext);

        Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(rootContext));
        servlet.addMapping(DISPATCHER_SERVLET_MAPPING );
        servlet.setLoadOnStartup(1);
    }
}

com/me/controller/ServicesController.java
@Controller
public class ServicesController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String services(ModelMap model) {
        return "services";
    }
}

WEB-INF/views/services.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Services

GET Request Response when calling localhost:8080/SpringMVC/:

Services

And then after that 404 Not Found on:
localhost:8080/SpringMVC/resources/js/jquery-1.4.2.min.js

A: I think in your services.jsp, could you try with single quotes:

It seems like a problem with 2 sets of double quotes in


text:
Q: On the definition of distributions Lars Hormander, The Analysis of Linear Partial Differential Operators I, chapter II:

Let $X$ be an open set in $\mathbb {R}^n$.
A distribution $u$ in $X$ is a linear form of $C_0^\infty(X)$ such that for every compact $K \subset X$ there exist constants $C$ and $k$ such that
$$ |u(\phi)| \leq C \sum_{|\alpha| \leq k } {\rm sup} |\partial ^{\alpha} \phi|, \hspace{1cm} \forall \phi \in C_0^\infty (K) $$

My question is. How does this definition even come to mind? Is there a reason to define a distribution like that?

A: A locally convex space $X$ is a linear space with a topology generated by a family of seminorms. A seminorm is a function $p:X\rightarrow [0,\infty)$ with $p(x+y)\leq p(x)+p(y)$ but where $p(x) = 0$ does not necessarily imply that $x = 0$.
Now for such spaces, a linear functional $l:X\rightarrow \mathbb{C}$ is continuous if and only if
$|l(x)|\leq C\sum_{k\in 1}^{n}p_k(x)$
for some finite collection of seminorms which generate the topology. See for instance Theorem IV.3.1 in John B. Conways book on functional analysis.
The principle is the same as for normed spaces (which is a locally convex space generated by one seminorm), where the continuous linear functionals are those that satisfy
$$|l(x)|\leq C|x|$$
for all $x$.
Distributions are simply the continuous linear functionals acting on the space of test functions, with topology generated by the family of seminorms $\{p_\alpha\}$ where
$$p_{\alpha}(\phi) = \sup |\partial^\alpha \phi|.$$
For more on this one can have a look at Chapter IV in the book by John B. Conway


text:
Q: Multiple procedures in IDL program I've written a procedure in IDL which performs some calculations on data and outputs an array of values.  The calculations take about 2 minutes to run.
I need to then perform analysis on these results, and ideally I would like not to have to perform the initial calculations each time I want to perform some different analysis.
Is the best way to achieve this to save the output from the calculation to a data file and then read this in from a different program?  Or is there a less cumbersome way to go about this?
Thanks in advance for any help

A: Yes, saving to a file is the easiest way to save the results from your first program for later use in the second (assuming you quit IDL between the two). There are may ways to save the data, depending on it's type and your preferences.
Easiest Way:
An IDL .sav file created by the SAVE command can store any kind of data, IDL variables, and even the whole state of your IDL session. Unfortunately, it only works for IDL (no other languages), and it can need to be re-generated if you upgrade IDL version. You read these files with RESTORE, which even remembers the names of the variables.
my_variable = 'Some data here.'

SAVE, my_variable, FILENAME='myfile.sav'  ; save variable(s)

... IDL opened and closed here ...

RESTORE, 'myfile.sav'                     ; read variable(s) from file

print, my_variable
Some data here.

Most Portable Way:
For simple tabular data, CSV has the advantage of being highly portable and human readable. However, it's also slow, since numbers are stored in ASCII. Use WRITE_CSV to write, and READ_CSV to read.
Most Portable Binary Formats:
For complex data that needs to be read by multiple languages, consider the HDF5 or NetCDF libraries. Both of these are binary formats that can store most types of IDL-supported data. Note that NetCDF is actually an easier-to-use subset of HDF5.
Simplest Binary Format:
Another option for tabular data is a simple binary dump. Use WRITEU to write to a normal file opened for writing. Use READU to read from a normal file open for reading.

A: Assuming that your data calculations will only change very rarely, then, yes, your best solution is to just save the calculations to an output file, and then read them back into your analysis program. You don't say what kind of data this is, so it's hard to give a more specific answer. Assuming that you have a two-dimensional array of data, you could just write the results as a "flat" binary file:
pro perform_calculations
  ...
  ; assume mydata is a float array of dimensions [m,n]
  openw, 1, 'results.dat'
  writeu, 1, mydata
  close, 1
end

Then, in either the same file or preferably a different .pro file:
pro perform_analysis
  mydata = fltarr(m, n)
  openr, 1, 'results.dat'
  readu, 1, mydata
  close, 1
  ...
end

Hope this helps.

A: Saving is a good way to do it, but if you run in the same session and your second program won't mess up the data from the first one, you can just call one and then pass the result to the second one.
pro do_calculations,result1,result2,result3
    result1=1
    result2=1.
    result3=result1/result2
    return
end

pro use_calculations,result1,result2,result3,result4
    result4=result1-result2+result3
    return
end

Then
IDL> do_calculations,result1,result2,result3
IDL> use_calculations,result1,result2,result3,result4

If you edit use_calculations, you can go again by:
IDL> use_calculations,result1,result2,result3,result4

Because the earlier results will stay in memory unless use_calculations does something bad to them.
You could also set up the second procedure to check to see if it has valid results from the first one and call it as needed.


text:
Q: TextField Corner Radius : Not Sharp Corners I am trying to add corner radius on uitextfield effect applies but not sharp corner.
Please check attached pictures.
I am expecting result like this.
Here is my Code for gray textfield.
 self.layer.cornerRadius = 7.5
 self.layer.borderWidth = 1.5
 self.layer.borderColor =  UIColor(red: 209/255.0, green: 209/255.0, blue: 209/255.0, alpha: 1.0).CGColor
 self.backgroundColor = UIColor.whiteColor()

Here is my Code for Red textfield.
 self.layer.cornerRadius = 7.5
 self.layer.borderWidth = 1.5
 self.layer.borderColor = TextFieldRedBorderColor.CGColor
 self.backgroundColor = TextFieldRedBackgroundColor

There is only color difference between both code but still it's not working.

A: self.layer.masksToBounds = true

This will solves your issue

A:  @IBOutlet var passwordboarderview: UIView!
 @IBOutlet var textusername: UITextField!
 @IBOutlet var txtpassword: UITextField!

 passwordboarderview.layer.cornerRadius = 7.5
 passwordboarderview.layer.borderColor = UIColor.whiteColor().CGColor
 passwordboarderview.layer.borderWidth = 2.0

 passwordboarderview.clipsToBounds = true
 txtpassword.attributedPlaceholder = NSAttributedString(string:"Password",attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])

 let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
 textusername.leftView = paddingView
 textusername.leftViewMode = .Always
 textusername.layer.borderWidth = 2.0
 textusername.layer.cornerRadius = 7.5
 textusername.layer.borderColor = UIColor.grayColor().CGColor
 textusername.clipsToBounds = true

Output :

Storyboard:

A: //
//  FDTextField.swift
//  FilloutDocs
//
//  Created by Janak Thakkar on 15/03/16.
//  Copyright © 2016 zetrixweb. All rights reserved.
//

import UIKit

private var maxLengthDictionary = [UITextField : Int]()

@IBDesignable

class ZWTextField : UITextField {

    var topBorder: UIView?
    var bottomBorder: UIView?
    var leftBorder: UIView?
    var rightBorder: UIView?
    var leftimageview : UIImageView?
    var rightimageview : UIImageView?
    @IBInspectable var borderColor: UIColor = UIColor.clearColor() {
        didSet {
            layer.borderColor = borderColor.CGColor
        }
    }

    @IBInspectable var ULText: Bool = false {
        didSet {
            let textRange = NSMakeRange(0, (self.text?.characters.count)!)
            let attributedText = NSMutableAttributedString(string: (self.text)!)
            attributedText.addAttribute(NSUnderlineStyleAttributeName , value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
            // Add other attributes if needed

            self.attributedText = attributedText
        }
    }
    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }

    @IBInspectable var fitToWidth: Bool = false {
        didSet {
            adjustsFontSizeToFitWidth = fitToWidth
        }
    }
    @IBInspectable var cursorColor : UIColor = UIColor.blueColor(){
        didSet {
            tintColor = cursorColor
        }
    }

    @IBInspectable var placeHolderColor : UIColor = UIColor.lightGrayColor(){
        didSet {
            setValue(placeHolderColor, forKeyPath: "_placeholderLabel.textColor")
        }
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    @IBInspectable var rightImage : UIImage? {
        didSet {
            if rightImage != nil {
                let width = rightviewWidth > rightImage!.size.width + 10 ? rightviewWidth :  rightImage!.size.width + 10
                rightViewMode = UITextFieldViewMode.Always
                rightimageview = UIImageView()
                rightimageview!.frame=CGRectMake(self.frame.size.width - width, self.frame.origin.y+2, width,self.frame.size.height-4)
                rightimageview!.image = rightImage
                rightView = rightimageview
                self.rightViewMode = .Always
                rightimageview!.contentMode = .Center
            }
            else {
                if rightimageview != nil {
                    rightimageview?.removeFromSuperview()
                    rightimageview = nil
                }
            }
        }
    }
    @IBInspectable var rightviewWidth : CGFloat = 0 {
        didSet{
            if rightimageview != nil{
                let width = rightviewWidth > rightImage!.size.width + 10 ? rightviewWidth :  rightImage!.size.width + 10
                rightimageview!.frame=CGRectMake(self.frame.origin.x+5, self.frame.origin.y+2, width,self.frame.size.height-4)
            }
        }
    }
    @IBInspectable var leftImage : UIImage? {
        didSet {
            if leftImage != nil {
                let width = leftviewWidth > leftImage!.size.width + 10 ? leftviewWidth :  leftImage!.size.width + 10
                leftViewMode = UITextFieldViewMode.Always
                leftimageview = UIImageView();
                leftimageview!.frame=CGRectMake(self.frame.origin.x+50, self.frame.origin.y+5, width,self.frame.size.height-5)
                //leftimageview!.frame = CGRectMake(10, 5, 40, 40)
                leftimageview!.image = leftImage;
                leftView = leftimageview;
                self.leftViewMode = .Always
                leftimageview!.contentMode = .Center
            }
        }
    }
    @IBInspectable var leftviewWidth : CGFloat = 0 {
        didSet{
            if leftimageview != nil{
                let width = leftviewWidth > leftImage!.size.width + 10 ? leftviewWidth :  leftImage!.size.width + 10
                leftimageview!.frame=CGRectMake(self.frame.origin.x+5, self.frame.origin.y+2, width,self.frame.size.height-4)
            }
        }
    }
    @IBInspectable var bottomLineWidth : CGFloat = 1 {
        didSet{
            let border: CALayer = CALayer()
            border.borderColor = UIColor.darkGrayColor().CGColor
            self.frame = CGRectMake(0, self.frame.size.height - bottomLineWidth, self.frame.size.width, self.frame.size.height)
            border.borderWidth = borderWidth
            self.layer.addSublayer(border)
            self.layer.masksToBounds = true
        }
    }

    @IBInspectable var bottomLineColor : UIColor = UIColor.lightGrayColor(){
        didSet {
            let border: CALayer = CALayer()
            border.borderColor = bottomLineColor.CGColor
        }
    }
    @IBInspectable var paddingLeft: CGFloat = 0
    @IBInspectable var paddingRight: CGFloat = 0

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y,
            bounds.size.width - paddingLeft - paddingRight, bounds.size.height);
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return textRectForBounds(bounds)
    }
    @IBInspectable var topBorderColor : UIColor = UIColor.clearColor()
    @IBInspectable var topBorderHeight : CGFloat = 0 {
        didSet{
            if topBorder == nil{
                topBorder = UIView()
                topBorder?.backgroundColor=topBorderColor;
                topBorder?.frame = CGRectMake(0, 0, self.frame.size.width, topBorderHeight)
                addSubview(topBorder!)
            }
        }
    }
    @IBInspectable var bottomBorderColor : UIColor = UIColor.clearColor()
    @IBInspectable var bottomBorderHeight : CGFloat = 0 {
        didSet{
            if bottomBorder == nil{
                bottomBorder = UIView()
                bottomBorder?.backgroundColor=bottomBorderColor;
                bottomBorder?.frame = CGRectMake(0, self.frame.size.height - bottomBorderHeight, self.frame.size.width, bottomBorderHeight)
                addSubview(bottomBorder!)
            }
        }
    }
    @IBInspectable var leftBorderColor : UIColor = UIColor.clearColor()
    @IBInspectable var leftBorderHeight : CGFloat = 0 {
        didSet{
            if leftBorder == nil{
                leftBorder = UIView()
                leftBorder?.backgroundColor=leftBorderColor;
                leftBorder?.frame = CGRectMake(0, 0, leftBorderHeight, self.frame.size.height)
                addSubview(leftBorder!)
            }
        }
    }
    @IBInspectable var rightBorderColor : UIColor = UIColor.clearColor()
    @IBInspectable var rightBorderHeight : CGFloat = 0 {
        didSet{
            if rightBorder == nil{
                rightBorder = UIView()
                rightBorder?.backgroundColor=topBorderColor;
                rightBorder?.frame = CGRectMake(self.frame.size.width - rightBorderHeight, 0, rightBorderHeight, self.frame.size.height)
                addSubview(rightBorder!)
            }
        }
    }
    @IBInspectable var maxLength: Int {
        get {
            if let length = maxLengthDictionary[self] {
                return length
            } else {
                return Int.max
            }
        }
        set {
            maxLengthDictionary[self] = newValue
            addTarget(self, action: "checkMaxLength:", forControlEvents: UIControlEvents.EditingChanged)
        }
    }

    func checkMaxLength(sender: UITextField) {
        let newText = sender.text
        if newText?.characters.count > maxLength {
            let cursorPosition = selectedTextRange
            text = (newText! as NSString).substringWithRange(NSRange(location: 0, length: maxLength))
            selectedTextRange = cursorPosition
        }
    }

}

Just add this file in project and you can set all the properties and can see realtime out.All properties you can set through storyboard.

A: There was just one mistake in my code.
TextField Border Style Was Line
textField.borderStyle = .Line

then I make it None
textField.borderStyle = .None

and it work like I wanted (Rounded Corners)...
Anyway.. Thanks for support and answers...


text:
Q: Kqemu Installation on Fedora 13 Can anyone tell me how to install kqemu on Fedora 13 host machine. I saw somewhere that Kqemu is not supported by Fedora 13, is that true???

A: http://en.wikipedia.org/wiki/QEMU#Accelerator


text:
Q: Verification method configuration for paswordless community (experience) logins how to enable external users to verify their phones?
They are getting their users created automatically with email and phone fields populated. On first login they have to validate email address (default behaviour) and we want to enable them to log in using SMS only.
How can they verify their mobile numbers and is there any standard method to do this?
As far as I know we need to implement this on ourselves so I am trying to create a LWC and use System.UserManagement.initRegisterVerificationMethod and System.UserManagement.verifyRegisterVerificationMethod methods, but the init one returns generic error message Something went wrong, try again. I have no idea what i did wrong as documentation for these is very poor.
My code:
@AuraEnabled
public static String registerUser( String phone ) {
    System.debug( 'Registering phone ' + phone);
    String exceptionText='';

        String userId = UserInfo.getUserId();
        User u = [Select MobilePhone, Id from User Where Id =: UserInfo.getUserId() ];
        System.debug( 'Update ' );

        String mobilePhone = getFormattedSms(phone);
        System.debug('Formatted phone ' + mobilePhone);
        u.MobilePhone = mobilePhone;
        u.Phone = mobilePhone;
        update u;

        exceptionText = System.UserManagement.initRegisterVerificationMethod(Auth.VerificationMethod.SMS);

    return exceptionText;
}

Formatted phone debug returns correct phone number as it was provided in LWC and yet the exceptionText returns that generic error.
The LWC is put on the homepage of my community and I am accessing it in context of Customer Community user.


text:
Q: Connecting PC to the internet over ethernet I have the following setup:
Laptop(Ubuntu 18.04) is connected to the internet over Wi-Fi.
PC(Ubuntu 18.04) is connected to the laptop using ethernet cable.
When the laptop is running VPN, the PC doesn't connect to the internet.
How can i establish connection with VPN running?
I don't want the PC to share the VPN connection.
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.50.0.1       128.0.0.0       UG    0      0        0 proton0
0.0.0.0         192.168.225.1   0.0.0.0         UG    600    0        0 wlp3s0
10.42.0.0       0.0.0.0         255.255.255.0   U     100    0        0 enp2s0
10.50.0.0       0.0.0.0         255.255.0.0     U     0      0        0 proton0
128.0.0.0       10.50.0.1       128.0.0.0       UG    0      0        0 proton0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlp3s0
172.16.174.0    0.0.0.0         255.255.255.0   U     0      0        0 vmnet8
172.83.43.131   192.168.225.1   255.255.255.255 UGH   0      0        0 wlp3s0
192.168.0.0     0.0.0.0         255.255.0.0     U     600    0        0 wlp3s0
192.168.220.0   0.0.0.0         255.255.255.0   U     0      0        0 vmnet1

A: For my VPN, I try to keep non essential traffic off of the VPN as it's slow.  The basic premise is to remove the default route to the VPN, and add in specific routes that you use for the VPN.  Mine has 'default' instead of 0.0.0.0 but I'll assume it's the same.  My delete looks like this:
route delete -net default gw 0.0.0.0 dev vpn0

So yours might be something like:
route delete -net 0.0.0.0 gw 128.0.0.0 dev proton0

This should route all traffic back through the ethernet, but it may break the VPN.  You have other proton0 entries so it may work fine.  From there I add specific networks that I need.  For instance 172.16.0.0 is a common one, as is 10.0.0.0:
route add -net 172.16.0.0 netmask 255.240.0.0 dev vpn0
route add -net 10.0.0.0 netmask 255.0.0.0 dev vpn0

You would need to use the routes that you need for the VPN, and set the device to proton0.  If things break completely, you can turn off and on the network and vpn and it should reset the settings.
If you manage to get this working, you can make this permanent by adding the file /etc/network/if-up.d/proton0 and inside you do something like this:
#!/bin/sh

if [ "$IFACE" = "proton0" ]; then
   route delete -net 0.0.0.0 gw 128.0.0.0 dev proton0
   route add -net 10.0.0.0 netmask 255.0.0.0 dev proton0
   route add -net 172.16.0.0 netmask 255.240.0.0 dev proton0
fi

Only replace the route commands with what you used to get it working.  You may have to do more than this to get the 2nd computer routing properly as this is setup is for keeping the internet traffic off the VPN.  I'm not 100% sure it will fix the second computer.


text:
Q: Is correlation matrix of residuals , a method to check for autocorrelation of residuals in the model? I am modelling and forecasting using a factor augmented VAR. I got the following residual matrix after fitting the model. My question is how to interpret it and does it indicate any autocorrelations in the model?

A: This seems to be the contemporaneous correlation matrix. In a regular reduced-form VAR model, the contemporaneous correlations are allowed to be anything, so looking at the matrix you have would be irrelevant. (I am not sure what the assumptions regarding contemporaneous correlations are in a factor-augmented model, though. You may look them up in the model description.)
Meanwhile, you want your residuals to be free of autocorrelation and cross-correlation at lags other than zero. To inspect that you would run acf(cbind(e1,e2,e3)) in R. Here, e1, e2 and e3 are the residuals corresponding to the three equations.


text:
Q: TreeView or ListView without column title bar Is there a way to show data in TreeView or ListView without column title bar?

A: When you talk about column title bar without showing any code makes me think that you are asking about Header.
If so, then this is the function you need:
gtk_tree_view_set_headers_visible()

Here is with headers_visible set to TRUE (which is default):

And here is with headers_visible set to FALSE:

And here is an example Code:
#include <gtk/gtk.h>

GtkWidget    *create_window ( void );
GtkWidget    *create_scrolled_window ( void );
GtkWidget    *create_tree_view ( void );
GtkListStore *create_list_store ( void );

int main ( void )
{
    GtkWidget *window;
    GtkWidget *scrolled_window;
    GtkWidget *tree_view;

    /// ***
    gtk_init ( NULL, NULL );

    /// ***
    window = create_window();

    /// ***
    ///scrolled_window = gtk_scrolled_window_new ( NULL, NULL );
    scrolled_window = create_scrolled_window ( );
    gtk_scrolled_window_set_kinetic_scrolling ( GTK_SCROLLED_WINDOW ( scrolled_window ), TRUE );
    gtk_scrolled_window_set_capture_button_press ( GTK_SCROLLED_WINDOW ( scrolled_window ), TRUE );

    /// ***
    tree_view = create_tree_view ( );
    gtk_container_add ( GTK_CONTAINER ( scrolled_window ), tree_view );
    gtk_container_add ( GTK_CONTAINER ( window ), scrolled_window );

    /// ***
    gtk_widget_show_all ( window );

    // ***
    gtk_widget_show_all ( window );
    gtk_main ();
}

GtkWidget *create_window ( void )
{
    GtkWidget *window;

    /// ***
    window = gtk_window_new ( GTK_WINDOW_TOPLEVEL );
    gtk_window_set_default_size ( GTK_WINDOW ( window ), 150, 150 );
    gtk_container_set_border_width ( GTK_CONTAINER ( window ), 5 );

    /// ***
    g_signal_connect ( window, "delete_event", G_CALLBACK ( gtk_main_quit ), NULL );

    /// ***
    return window;
}

GtkWidget *create_scrolled_window ( void )
{
    GtkWidget *scrolled_window;

    /// ***
    scrolled_window = gtk_scrolled_window_new ( NULL, NULL );
    gtk_scrolled_window_set_kinetic_scrolling ( GTK_SCROLLED_WINDOW ( scrolled_window ), TRUE );
    gtk_scrolled_window_set_capture_button_press ( GTK_SCROLLED_WINDOW ( scrolled_window ), TRUE );

    /// ***
    return scrolled_window;
}

GtkListStore *create_list_store ( void )
{
    GtkListStore *list_store;
    list_store = gtk_list_store_new ( 1, G_TYPE_STRING );

    /// ***
    for ( gint i = 0; i < 10; i++ )
    {
        GtkTreeIter iter;
        gchar *label = g_strdup_printf ( "Row number %d", i );

        /// ***
        gtk_list_store_append ( list_store, &iter );
        gtk_list_store_set ( list_store, &iter, 0, label, -1 );

        /// ***
        g_free ( label );
    }

    return list_store;
}

GtkWidget *create_tree_view ( void )
{
    GtkWidget       *tree_view;
    GtkCellRenderer *renderer;
    GtkListStore    *store;

    /// ***
    tree_view = gtk_tree_view_new ();
    store     = create_list_store();

    /// ***
    renderer = gtk_cell_renderer_text_new ();
    g_object_set ( renderer, "editable", TRUE, NULL );

    /// **
    gtk_tree_view_insert_column_with_attributes ( GTK_TREE_VIEW ( tree_view ),
            0, "This is the Title",
            renderer,
            "text", 0,
            NULL );

    /// ***
    gtk_tree_view_set_model ( GTK_TREE_VIEW ( tree_view ), GTK_TREE_MODEL ( store ) );
    g_object_unref ( store );

    /// ***
    gtk_tree_view_set_headers_visible ( GTK_TREE_VIEW ( tree_view ), FALSE );

    /// ***
    return tree_view;
}


text:
Q: Installing an ASP.NET web API on IIS I have built my first ASP.NET web API in MVC, when I debug the application from Visual Studio everything works perfectly.
Now I need to get these API's on my server...
I have tried copying the project files to the website root which usually works for normal MVC apps with views, and I have also built the project and copies the file full of DLL's and an exe to the IIS root.
Obviously, neither of these worked, anyone know what I am missing? Perhaps something I have to do with IIS?
I have now tried "publishing" the project and when I try to access the site this happens...
Thanks in advance!

A: Build the application then publish it. Copy the published files to a favorite IIS folder. Ensure you select the right version of ASP.NET in the server for your application in the application pool.

A: When you publish and get an error such as this it is often related to a configuration issue, or other non-supported .NET Runtime issue.
For best results, if you can get to the Event Viewer for the server a detailed error should appear there outlining the root cause of the issue.
If you don't have access to the server directly, updating the <system.webServer> section with the below should get you a detailed error.

<httpErrors errorMode="Detailed" />

Just please note DO NOT LEAVE THAT LINE IN PRODUCTION!


text:
Q: JSON object looped multiple times Hi I seem to have gotten myself stuck with the data passed by JSON. When I console log to see the data passed, the object are repeatedly passed and this is affecting my append output.
$.ajax({
            url: "http://howtodeployit.com/api/get_recent_posts",
            dataType: "json",
            jsonpCallback: 'successCallback',
            async: true,
            beforeSend: function() { $.mobile.showPageLoadingMsg(true); },
            complete: function() { $.mobile.hidePageLoadingMsg(); },
            success:function (data){
                $.each(data.posts, function(key, val) {
                console.log(data.posts);

                var result = $('
').append([$("
", {html: val.title}),$("
", {html: val.excerpt})]).wrapInner('');

                $('#postlist').empty().append(result);
            });

As seen below, this is appearing multiple times but the expected output should just be one line of object.

A: $.each(data.posts, function(key, val) {

That is a loop. So, assuming that the data.posts is an array that has multiple objects, you will see this fired as many times as there are posts.
What are you hoping to see?
Also, loxxy is right, you're missing a closing brace so it's hard to know where you intend your loop function to actually end.

A: If you are trying to load jsonp, the dataType should be jsonp
Also I do think you are trying to loop over each post. But there would be only one result since you empty the container every time.
So instead of :
$('#postlist').empty().append(result);

Use
$('#postlist').append(result);

And did you miss a closing braces??
$.ajax({
    url: "http://howtodeployit.com/api/get_recent_posts",
    dataType: "jsonp",
    jsonpCallback: 'successCallback',
    async: true,
    beforeSend: function () {
        // $.mobile.showPageLoadingMsg(true);
    },
    complete: function () {
        //  $.mobile.hidePageLoadingMsg();
    },
    success: function (data) {
        $.each(data.posts, function (key, val) {
            console.log(data.posts);

            var result = $('
').append([$("
", {
                html: val.title
            }), $("
", {
                html: val.excerpt
            })]).wrapInner('');

            $('#postlist').append(result);

        });
    }
});

here is a DEMO.


text:
Q: IOS Creating list of Dictionaries in plist I am having trouble to write new dictionaries in my plist file where I want to save data each time the user fill a form.
The code I am using right now only overwrite the data and doesn´t save the previous dictionary as wanted.
here the code :
//////////// Save data into plist /////////////////
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

// set the variables to the values in the text fields
self.titlestring = titleexperiencia.text;
self.descriptionstring = descriptionexperiencia.text;
self.coordinadastring = [self deviceLocation];

// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: titlestring, descriptionstring,coordinadastring, nil] forKeys:[NSArray arrayWithObjects: @"Title", @"Description", @"Coordinate", nil]];

NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

// check is plistData exists
if(plistData)
{
    // write plistData to our Data.plist file
    [plistData writeToFile:plistPath atomically:YES];
    NSLog(@"Saved in Data Plist");

}
else
{
    NSLog(@"Error in saveData: %@", error);
    [error release];
}

I also tried to use AddObject: instead of writeToFile: but that make the App crash.

A: Well, the crash is probably being caused because you're overreleasing the error variable.

A: Read the contents of the plistPath:
    NSMutableData *myData = [NSMutableData dataWithContentsOfFile:plistPath];
And change this:
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

to:
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
[myData appdendData:plistData];

and finally write myData to file.
Hope that helps!


text:
Q: 3 Address Code Generation using lex and yacc I'm trying to generate 3 address code corresponding to basic arithmetic expressions. I haven't worked with lex and yacc tools before much (Newbie) and I'm having trouble understanding the flow of control/command among the two i.e how the two programs are interacting.
lex.l
%{
    #include<stdio.h>
    #include"y.tab.h"
    int k=1;
%}

%%
[0-9]+ {
yylval.dval=yytext[0];
return NUM;
}

\n {return 0;}
. {return yytext[0];}
%%

void yyerror(char* str)
{
        printf("\n%s",str);
}
char *gencode(char word[],char first,char op,char second)
{
    char temp[10];
    sprintf(temp,"%d",k);
    strcat(word,temp);
    k++;
    printf("%s = %c %c %c\n",word,first,op,second);

    return word; //Returns variable name like t1,t2,t3... properly
}
int yywrap()
{
    return 1;
}

main()
{
        yyparse();
        return 0;
}

yacc.y
%{
#include<stdio.h>
int aaa;
%}

%union{
    char dval;
}

%token <dval> NUM
%type <dval> E
%left '+' '-'
%left '*' '/' '%'

%%
statement : E {printf("\nt = %c \n",$1);}
          ;

E : E '+' E
    {
        char word[]="t";
        char *test=gencode(word,$1,'+',$3);
        $$=test;

    }
  | E '-' E
    {
        char word[]="t";
        char *test=gencode(word,$1,'-',$3);
        $$=test;
    }
  | E '%' E
    {
        char word[]="t";
        char *test=gencode(word,$1,'%',$3);
        $$=test;
    }
  | E '*' E
    {
        char word[]="t";
        char *test=gencode(word,$1,'*',$3);
        $$=test;
    }
  | E '/' E
    {
        char word[]="t";
        char *test=gencode(word,$1,'/',$3);
        $$=test;
    }
  | '(' E ')'
    {
        $$=$2;
    }
  | NUM
    {
        $$=$1;
    }
  ;
%%

Problem:
getting garbage value in output
Expected output for expression (2+3)*5 should be like:
t1= 2 + 3
t2= t1 * 5

Obtained output:
t1= 2 + 3
t2= garbage value * 5

I'm unable to figure out how to correct this. The variable names (eg t1,t2,t3 ) are being properly returned from gencode() method in lex.l
char *test=gencode(word,$1,'%',$3);

But I'm completely clueless about what is going wrong after that. I believe I'm not handling the $$,$1,$3 terms correctly.

Please help me understand what is going wrong, what needs to be done and how to do it.
A little help and some explanation would be very helpful. Thank you.

A: The problem here is not in the use of flex or bison; rather, it is an Undefined Behaviour in your C code.
Your gencode function returns its first argument. Then you call it like this, roughly:
{
  char word[] = ...
  ... = gencode(word, ...);
}

The lifetime of word ends when the block finishes, which is right after the call to gencode. In effect, that is no different from the classic dangling pointer generator:
char* dangle(void) {
  char temporary[] = "some string";
  return temporary;
}

which is obviously incorrect, since the local variable ceases to exist before its address is returned.
In addition, you actually create word as a two-character array:
char word[] = "t";

since leaving out the size tells C to leave exactly enough space for the initial string (one character plus null terminator). That's fine, but you cannot then append more characters to the string (with strcat) because there is no space left and you will end up overwriting some other variable (or worse).

A: mentall n't end even after the function returns. That's why I declared char word[] before calling the function. This ideone.com/RBz0y2 is a code I wrote seperately and used it in here too. Is it not right? – Swagnik Dutta Mar 9 '16 at 16:38
@novice: If the caller allocates on the stack and passes to the called function, that is fine. The caller still has the memory. But as soon as the caller returns to its caller, the memory is gone. You cannot set a persistent variable to the address. So, no, it is not right. If you need keep the value around for the future, you need to allocate with malloc; stack-allocated storage


text:
Q: Varnish SSL with Nginx I have a website on my server and install Varnish , all right . Now I'm going to install the SSL certificates and I read that Varnish does not support SSL, I have to install Nginx to operate the certificates. Anyway , just be installing Nginx and my question is whether the SSL pages will have the benefit of the cache? Or the SSL pages, will not have cache.
Forgive me if my question is very simple, it is that I'm new at this and do not know much about web servers.

A: You can set up NGINX to take care of SSL termination. If you do so, you still have caching for SSL. Take a look at SSL termination article for more detail.


text:
Q: ProseMirror - Set caret position to end of selected node After running command({ href: url }), I would like to deselect current selection and set caret position to end of selected node. NOTE: I am using TipTap
setLinkUrl(command, url) {
command({ href: url })
this.hideLinkMenu()

// Set cursor position after highlighted link
var tag = document.getElementById("editor")

var setpos = document.createRange()

var set = window.getSelection()

const state = this.editor.state

let sel = state.selection
// TODO: Check if sel range > 0
let resolvedPos = state.doc.resolve(sel.from)
let node = resolvedPos.node(resolvedPos.depth)

// This is where I want to set the caret position to the end of the currently selected node
// Currently, I'm using hardcoded indices as proof of concept while the editor contains three paragraph nodes
setpos.setStart(document.getElementById("editor").childNodes[0].childNodes[1], 1)
setpos.setEnd(document.getElementById("editor").childNodes[0].childNodes[1], 1)

setpos.collapse(true)

set.removeAllRanges()

set.addRange(setpos)

tag.focus()

A: This is how you'd do it with ProseMirror, I guess it should translate to TipTap too.
A selection can span multiple nodes so we're going to move the caret the the end of the end of the last selected node.
The resolved position of the end of the selection is at selection.$to. It's a convention in ProseMirror that resolved positions start with a $.
To find the next "cut" at the end of the current node of a resolved position you can use the after() method. This will return a position after the node ends so we need to subtract one from it.
Finally, we need to create a new selection and apply it by dispatching a document transformation using the setSelection() method. Remember that TextSelection needs a resolved position to be instantiated not a position number.
If we put it all together we can create a command to do this:
import {TextSelection} from "prosemirror-state";

function moveToEnd (state, dispatch, view) {
    // Don't dispatch this command if the selection is empty
    if (state.selection.empty) return false;

    // Subtract one so that it falls within the current node
    const endPos = state.selection.$to.after() - 1;
    const selection = new TextSelection(state.doc.resolve(endPos));
    let transaction = state.tr.setSelection(selection);

    if (dispatch) dispatch(transaction.scrollIntoView());

    return true;
}

You can use this command with the keymap module when instantiating the editor:
keymap({
    'Mod-Shift-j': moveToEnd
})


text:
Q: Which one of these should be before "for you" I just heard someone say "fortunately for you" in the film The Arrow, and I know that "lucky for you" is also a synonymous common phrase.
Why is one an adverb and the other an adjective (before for you)? and furthermore, I once read that they were some kind of contraction. What is the complete form?

A: "Luckily for you" means the same thing as "fortunately for you."  This is a fragment, a portion of a longer sentence, such as, "Fortunately for you, I happen to have an extra umbrella in my car."  (Context: a sudden downpour, no parking space close to the theater.)
However, "lucky for you" is a bit different.  A slightly longer, clearer version would be "That was lucky for you!"  Or "How lucky for you!"  Example:

I have taken my son for a blood test.  His favorite tech is on duty, the one who always gets it on the first try, and distracts him with a joke.  I say, on our way out, "Lucky for you that Miriam was on duty this morning!"

And this means it was lucky for you etc.  Here, "lucky" is an adjective modifying "it".
If we wanted to use "luckily" instead, in this same context, it would be

Luckily for you, Miriam was on duty this morning.


text:
Q: How to stop/Disable Nagios email notifications How Can I stop the email notifications. I am setting up a new server and getting tons of notifications. Wants to disable them for time being.

A: You can also do it at a contact level, by disabling notifications for your Nagios contact.
E.g.:
define contact {
    contact_name JohnDoe
    email johndoe@example.com
    host_notifications_enabled 0
    service_notifications_enabled 0
}

The other way to skin this cat is to use the host_notification_options and service_notification_options in the contact definition. Set them to n (none).

A: Click on "Process Info" in the left nav pane, and then "Disable Notifications", then "Commit".

A: You can also do this via NAGIOS's command_file named pipe, if you have that defined.  The advantages of doing it this way are it's internal to NAGIOS, it can be programmed from at or cron rather than requiring interaction with a web browser, and it doesn't require changing any of the config files.
To disable notifications (on CentOS6 EPEL NAGIOS - other distributions may have the command_file configured elsewhere):
echo "[`date +%s`] DISABLE_NOTIFICATIONS" > /var/nagios/rw/nagios.cmd

and to re-enable it later:
echo "[`date +%s`] ENABLE_NOTIFICATIONS" > /var/nagios/rw/nagios.cmd

A: in nagios.cfg, set enable_notifications=0 and restart nagios

A: Set both:

*

*service_notification_period &

*host_notification_period

to never instead of 24x7

A: You can also stop your mail server (service postfix stop) on the Nagios server, if you are relaying through the mail server on localhost where Nagios is installed.  Then you can do postsuper -d ALL to delete all mails sitting in mailq.