问:
How to Upload Image an Text with a new UserId in firebase database to avoid overwriting of data on the same UserId? - Android
I am uploading image and text to firebase after logging in. It successfully uploads theimage url and text the first time. But now that i am logged in already, i simply stay on the upload activity and upload the image url and text.

The new image url and text overwrites the old image url and text under the same uid. How can i avoid this? How can create new uid everytime i upload the image url and text such that the new doesnt overwrite the old.

Firebase Database Structure

I had uploaded 2 more images with text before this one but this new child overwrote the old one.

MyUploadService.java

```<code> public class MyUploadService extends AppCompatActivity {

Button select_image,upload_button;
ImageView user_image;
TextView title;
public static final int READ_EXTERNAL_STORAGE = 0;
private static final int GALLERY_INTENT = 2;
private ProgressDialog mProgressDialog;
private Firebase mRoofRef;
private FirebaseAuth mAuth;
private Uri mImageUri = null;
private DatabaseReference mdatabaseRef;
private StorageReference mStorage;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FirebaseApp.initializeApp(this);
    setContentView(R.layout.upload_layout);

    Firebase.setAndroidContext(this);

    mAuth = FirebaseAuth.getInstance();
    select_image = (Button)findViewById(R.id.select_image);
    upload_button = (Button)findViewById(R.id.upload_bttn);
    user_image = (ImageView) findViewById(R.id.user_image);
    title = (TextView) findViewById(R.id.etTitle);

    //Initialize the Progress Bar
    mProgressDialog = new ProgressDialog(MyUploadService.this);

    //Select image from External Storage...
    select_image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            //Check for Runtime Permission
            if (ContextCompat.checkSelfPermission(getApplicationContext(),
             Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(getApplicationContext(), "Call for
          Permission", Toast.LENGTH_SHORT).show();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                {
                    requestPermissions(new String[]
       {Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
                }
            }
            else
            {
                callgalary();
            }
        }
    });

    //Initialize Firebase Database paths for database and Storage

    mdatabaseRef = FirebaseDatabase.getInstance().getReference();
    mRoofRef = new Firebase("https://first-project-
           7f5d4.firebaseio.com/").child("Item_Details(categories)").push();
                // Push will create new child every time we upload data
    mStorage =
           FirebaseStorage.getInstance().getReferenceFromUrl("gs://first-
       project-7f5d4.appspot.com");

    //Click on Upload Button Title will upload to Database
    upload_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String mName = title.getText().toString().trim();

            if(mName.isEmpty())
            {
                Toast.makeText(getApplicationContext(), "Fill all Field",
          Toast.LENGTH_SHORT).show();
                return;
            }
            Firebase childRef_name = mRoofRef.child("Image_Title");
            childRef_name.setValue(mName);

            Toast.makeText(getApplicationContext(), "Updated Info",
                    Toast.LENGTH_SHORT).show();
            signInAnonymously();
                        }
              });

            }

//Check for Runtime Permissions for Storage Access
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
                  permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions,
             grantResults);
    switch (requestCode) {
        case READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] ==
             PackageManager.PERMISSION_GRANTED)
                callgalary();
            return;
    }
    Toast.makeText(getApplicationContext(), "...",
                         Toast.LENGTH_SHORT).show();
              }

//If Access Granted gallery Will open
private void callgalary() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, GALLERY_INTENT);
                    }

     //After Selecting image from gallery image will directly uploaded to
      Firebase Database
     //and Image will Show in Image View
       @Override
           public void onActivityResult(int requestCode,
         int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {

        mImageUri = data.getData();
        user_image.setImageURI(mImageUri);
        StorageReference filePath =

      mStorage.child("Item_Images_By_Category").child
                    (mImageUri.getLastPathSegment());

        mProgressDialog.setMessage("Uploading Image....");
        mProgressDialog.show();

        filePath.putFile(mImageUri).addOnSuccessListener(new
       OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Uri downloadUri = taskSnapshot.getDownloadUrl();
       //Ignore This error

             mRoofRef.child("Image_URL").setValue(downloadUri.toString());

                Glide.with(getApplicationContext())
                        .load(downloadUri)
                        .crossFade()
                        .placeholder(R.drawable.loading)
                        .diskCacheStrategy(DiskCacheStrategy.RESULT)
                        .into(user_image);
                Toast.makeText(getApplicationContext(), "Updated.",
          Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
            }
        });
        }
       }

private void signInAnonymously() {

     final String TAG = "Storage#MainActivity";

    // Sign in anonymously. Authentication is required to read or write from
     Firebase Storage.

    mAuth.signInAnonymously()
            .addOnSuccessListener(this, new OnSuccessListener<AuthResult>()
      {
                @Override
                public void onSuccess(AuthResult authResult) {
                    Log.d(TAG, "signInAnonymously:SUCCESS");
               Toast.makeText(getApplicationContext(), "Successful Signin",
    Toast.LENGTH_SHORT).show();
                    updateUI(authResult.getUser());
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Log.e(TAG, "signInAnonymously:FAILURE", exception);
                    hideProgressDialog();
                    updateUI(null);
                }
            });
}

private void updateUI(FirebaseUser user) {
    // Signed in or Signed out
    if (user != null) {

    } else {

    }

}

private void showProgressDialog(String caption) {
    if (mProgressDialog == null) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setIndeterminate(true);
    }

    mProgressDialog.setMessage(caption);
    mProgressDialog.show();
}

     private void hideProgressDialog() {
    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
        }
      }
</code>```

答:
To solve this problem you need to use updateChildren() method in stead of setValue() method. Because Firebase is structured as a pair of key and value, in the case of a Map, it replaces the old value with the new one.

Hope it helps.

Body:
I am uploading image and text to firebase after logging in. It successfully uploads theimage url and text the first time. But now that i am logged in already, i simply stay on the upload activity and upload the image url and text.

The new image url and text overwrites the old image url and text under the same uid. How can i avoid this? How can create new uid everytime i upload the image url and text such that the new doesnt overwrite the old.

Firebase Database Structure

I had uploaded 2 more images with text before this one but this new child overwrote the old one.

MyUploadService.java

 public class MyUploadService extends AppCompatActivity {

Button select_image,upload_button;
ImageView user_image;
TextView title;
public static final int READ_EXTERNAL_STORAGE = 0;
private static final int GALLERY_INTENT = 2;
private ProgressDialog mProgressDialog;
private Firebase mRoofRef;
private FirebaseAuth mAuth;
private Uri mImageUri = null;
private DatabaseReference mdatabaseRef;
private StorageReference mStorage;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FirebaseApp.initializeApp(this);
    setContentView(R.layout.upload_layout);

    Firebase.setAndroidContext(this);

    mAuth = FirebaseAuth.getInstance();
    select_image = (Button)findViewById(R.id.select_image);
    upload_button = (Button)findViewById(R.id.upload_bttn);
    user_image = (ImageView) findViewById(R.id.user_image);
    title = (TextView) findViewById(R.id.etTitle);

    //Initialize the Progress Bar
    mProgressDialog = new ProgressDialog(MyUploadService.this);

    //Select image from External Storage...
    select_image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            //Check for Runtime Permission
            if (ContextCompat.checkSelfPermission(getApplicationContext(),
             Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(getApplicationContext(), "Call for
          Permission", Toast.LENGTH_SHORT).show();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                {
                    requestPermissions(new String[]
       {Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
                }
            }
            else
            {
                callgalary();
            }
        }
    });

    //Initialize Firebase Database paths for database and Storage

    mdatabaseRef = FirebaseDatabase.getInstance().getReference();
    mRoofRef = new Firebase("https://first-project-
           7f5d4.firebaseio.com/").child("Item_Details(categories)").push();
                // Push will create new child every time we upload data
    mStorage =
           FirebaseStorage.getInstance().getReferenceFromUrl("gs://first-
       project-7f5d4.appspot.com");

    //Click on Upload Button Title will upload to Database
    upload_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String mName = title.getText().toString().trim();

            if(mName.isEmpty())
            {
                Toast.makeText(getApplicationContext(), "Fill all Field",
          Toast.LENGTH_SHORT).show();
                return;
            }
            Firebase childRef_name = mRoofRef.child("Image_Title");
            childRef_name.setValue(mName);

            Toast.makeText(getApplicationContext(), "Updated Info",
                    Toast.LENGTH_SHORT).show();
            signInAnonymously();
                        }
              });

            }

//Check for Runtime Permissions for Storage Access
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
                  permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions,
             grantResults);
    switch (requestCode) {
        case READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] ==
             PackageManager.PERMISSION_GRANTED)
                callgalary();
            return;
    }
    Toast.makeText(getApplicationContext(), "...",
                         Toast.LENGTH_SHORT).show();
              }

//If Access Granted gallery Will open
private void callgalary() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, GALLERY_INTENT);
                    }

     //After Selecting image from gallery image will directly uploaded to
      Firebase Database
     //and Image will Show in Image View
       @Override
           public void onActivityResult(int requestCode,
         int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {

        mImageUri = data.getData();
        user_image.setImageURI(mImageUri);
        StorageReference filePath =

      mStorage.child("Item_Images_By_Category").child
                    (mImageUri.getLastPathSegment());

        mProgressDialog.setMessage("Uploading Image....");
        mProgressDialog.show();

        filePath.putFile(mImageUri).addOnSuccessListener(new
       OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Uri downloadUri = taskSnapshot.getDownloadUrl();
       //Ignore This error

             mRoofRef.child("Image_URL").setValue(downloadUri.toString());

                Glide.with(getApplicationContext())
                        .load(downloadUri)
                        .crossFade()
                        .placeholder(R.drawable.loading)
                        .diskCacheStrategy(DiskCacheStrategy.RESULT)
                        .into(user_image);
                Toast.makeText(getApplicationContext(), "Updated.",
          Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
            }
        });
        }
       }

private void signInAnonymously() {

     final String TAG = "Storage#MainActivity";

    // Sign in anonymously. Authentication is required to read or write from
     Firebase Storage.

    mAuth.signInAnonymously()
            .addOnSuccessListener(this, new OnSuccessListener<AuthResult>()
      {
                @Override
                public void onSuccess(AuthResult authResult) {
                    Log.d(TAG, "signInAnonymously:SUCCESS");
               Toast.makeText(getApplicationContext(), "Successful Signin",
    Toast.LENGTH_SHORT).show();
                    updateUI(authResult.getUser());
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Log.e(TAG, "signInAnonymously:FAILURE", exception);
                    hideProgressDialog();
                    updateUI(null);
                }
            });
}

private void updateUI(FirebaseUser user) {
    // Signed in or Signed out
    if (user != null) {

    } else {

    }

}

private void showProgressDialog(String caption) {
    if (mProgressDialog == null) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setIndeterminate(true);
    }

    mProgressDialog.setMessage(caption);
    mProgressDialog.show();
}

     private void hideProgressDialog() {
    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
        }
      }


来源: stackexchange

问:
How to line up each word in a list so that entries start at the same point horizontally?
Here's an example I've changed slightly from a previous SO question:
http://jsfiddle.net/tPjQR/72/

ol {
    font-family: Georgia, serif;
}
ol span {
    font-family: Arial, sans-serif;
    font-size: 17px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
    <li><span>Entry one</span></li>
    <li><span>Entry two</span></li>
    <li><span>Entrye three</span></li>
    <li><span>Entry five</span></li>
    <li><span>Entry six</span></li>
    <li><span>Entry Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long</span></li>
</ol></code>```

I would like to line up the columns so that, no matter how much text is in one column, the first characters of each column will be lined up.

E.g.

not

```<code>Entry one
Entry two
Entrye three
Entry five
Entry six
</code>```

rather

```<code>Entry  one
Entry  two
Entrye three
Entry  five
Entry  six
</code>```

Is there a way to do this with list items, or do I need to use a table?

答:
You can change your css

```<code>li span {
    display:inline-block;
    width:15%;

}

li  p {text-align: left; display:inline-block; margin : 0px 45px;}
</code>```

inline-block value of the display property makes this even easier

CSS margin properties are used to generate space around elements.
learn more about that CSS Margins

li span {
    display:inline-block;  width:15%;

}
li  p {text-align: left; display:inline-block; margin : 0px 75px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
    <li><span>Entry </span> <p>

  one</p></li>
   <li><span>Entry</span> <p>

  two</p></li>
  <li><span>Entryre</span> <p>

    three</p></li>
  <li><span>Entry</span> <p>

    fiv</p></li>
   <li><span>Entry</span> <p>

    six</p></li>
</ol></code>```

ContentLicense: CC BY-SA 3.0

Body:
Here's an example I've changed slightly from a previous SO question:
http://jsfiddle.net/tPjQR/72/

ol {
    font-family: Georgia, serif;
}
ol span {
    font-family: Arial, sans-serif;
    font-size: 17px
}

Entry one

Entry two

Entrye three

Entry five

Entry six

Entry Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long

I would like to line up the columns so that, no matter how much text is in one column, the first characters of each column will be lined up.

E.g.

not

Entry one
Entry two
Entrye three
Entry five
Entry six

rather

Entry  one
Entry  two
Entrye three
Entry  five
Entry  six

Is there a way to do this with list items, or do I need to use a table?

Body:
You can change your css

li span {
    display:inline-block;
    width:15%;

}

li  p {text-align: left; display:inline-block; margin : 0px 45px;}

inline-block value of the display property makes this even easier

CSS margin properties are used to generate space around elements.
learn more about that CSS Margins

li span {
    display:inline-block;  width:15%;

}
li  p {text-align: left; display:inline-block; margin : 0px 75px;}

<ol>
    <li><span>Entry </span> <p>

  one</p></li>
   <li><span>Entry</span> <p>

  two</p></li>
  <li><span>Entryre</span> <p>

    three</p></li>
  <li><span>Entry</span> <p>

    fiv</p></li>
   <li><span>Entry</span> <p>

    six</p></li>
</ol>


问:
cv::Mat initialization using array
I experienced a strange behavior after for example initializing through

```<code>#include <iostream>
#include <opencv2/opencv.hpp>

int main() {
    cv::Mat h = cv::Mat(2, 2, CV_32F, {1.0, 2.0, 1.0, 0.0});
    std::cout << h << std::endl;
    return 0;
}
</code>```

cout prints out [1, 1; 1, 1]. WTF just happened? I'm using eclipse on ubuntu, gcc version 5.4, OpenCV 3.2

答:
You're not using a valid Mat constructor. You have a few options:

From an array:

```<code>float pf[] = { 1.f, 2.f, 3.f, 4.f };
Mat1f m1(2, 2, pf);
</code>```

or

```<code>std::vector<float> vf = { 1.f, 2.f, 3.f, 4.f };
Mat1f m2(2, 2, vf.data());
</code>```

With comma initializers:

```<code>Mat1f m3 = (Mat1f(2, 2) << 1.f, 2.f, 3.f, 4.f);
</code>```

If the matrix is small, you can use Matx:

```<code>Matx22f m4(1.f, 2.f, 3.f, 4.f);
</code>```

Note that a Mat1f is a typedef for Mat_<float>, which is a Mat of type CV_32FC1.

Using your method doesn't work because {1.0, 2.0, 1.0, 0.0} constructs  cv::Scalar, so you call the constructor Mat(int rows, int cols, int type, cv::Scalar). Since you have only 1 channel, the matrix is initialized with the first value of this scalar, which is the first value in your initializer list.

Note that this is just a coincidence since your matrix has 4 elements (the maximum number supported by Scalars). If you use a higher number of elements:

```<code>cv::Mat h(2, 3, CV_32F, {3.f, 2.f, 1.f, 0.f, 2.f, 5.f});
</code>```

the code should not compile.

Title: cv::Mat initialization using array

Body:
I experienced a strange behavior after for example initializing through

#include <iostream>
#include <opencv2/opencv.hpp>

int main() {
    cv::Mat h = cv::Mat(2, 2, CV_32F, {1.0, 2.0, 1.0, 0.0});
    std::cout << h << std::endl;
    return 0;
}

cout prints out [1, 1; 1, 1]. WTF just happened? I'm using eclipse on ubuntu, gcc version 5.4, OpenCV 3.2

Body:
You're not using a valid Mat constructor. You have a few options:

From an array:

float pf[] = { 1.f, 2.f, 3.f, 4.f };
Mat1f m1(2, 2, pf);

or

std::vector<float> vf = { 1.f, 2.f, 3.f, 4.f };
Mat1f m2(2, 2, vf.data());

With comma initializers:

Mat1f m3 = (Mat1f(2, 2) << 1.f, 2.f, 3.f, 4.f);

If the matrix is small, you can use Matx:

Matx22f m4(1.f, 2.f, 3.f, 4.f);

Note that a Mat1f is a typedef for Mat_<float>, which is a Mat of type CV_32FC1.

Using your method doesn't work because {1.0, 2.0, 1.0, 0.0} constructs  cv::Scalar, so you call the constructor Mat(int rows, int cols, int type, cv::Scalar). Since you have only 1 channel, the matrix is initialized with the first value of this scalar, which is the first value in your initializer list.

Note that this is just a coincidence since your matrix has 4 elements (the maximum number supported by Scalars). If you use a higher number of elements:

cv::Mat h(2, 3, CV_32F, {3.f, 2.f, 1.f, 0.f, 2.f, 5.f});

the code should not compile.


问:
How to correctly use of imagettftext?
I am making a form which the user is filling to create a mail signature:

generatarjeta.php

```<code>if(isset($_GET["suc"]) && $_GET["suc"] !="")
{ $code="";
  foreach($_GET as $key => $value){
    $code.= $key . "=" . $value . "&";
  }
  $code = rtrim($code,"&");
  ?>
  <img src="imagem.php?<?php echo $code;?>">
  <script>window.history.pushState("", "", '/generatarjeta.php');</script>
  <?php exit();
}

<form method="get">
      <table>
        <tr><td><label>Sucursal</label></td><td><select name="suc">
          <option value="">Seleccione...</option>
          <?php
          $con_sucursal = mssql_query("select * from localitos where local NOT IN (3,5, 7,12, 13, 14,15,16,17,19, 20, 21, 22,23,24,25,26,27)");
          while ($res_sucursal = mssql_fetch_array($con_sucursal))
          {
            echo "<option value='$res_sucursal[0]'>$res_sucursal[1]</option>";
          }?>
        </select></td></tr>
        <tr><td><label>Nombre del Trabajador: </label></td><td><input type="text" name="nombre" required="" onkeypress="return textonly(event);"/></td></tr>
        <tr><td><label>Puesto: </label></td><td><input type="text" name="puesto" required="" onkeypress="return textonly(event);"/></td></tr>
        <tr><td><label>Telefono: </label></td><td><input type="text" name="tel" required="" onkeypress='return solonums(event)'/> <label>Extension: </label><input type="text" name="ext" onkeypress='return solonums(event)'/></td></tr>
        <tr><td><label>correo: </label></td><td><input type="text" name="mail" placeholder="nombre.apellido"/></td></tr>
        <tr><td><input type="submit" name="submit" value="Generar"/></td><td><input type="reset"/></td></tr>
      </table>
    </form>
</code>```

imagem.php

```<code>//Carregar imagem
$rImg = ImageCreateFromJPEG("the_firma.jpg");
//Definir cor
$cor = imagecolorallocate($rImg, 226, 41, 34);
$cor2 = imagecolorallocate($rImg, 60, 60, 59);

$tel = "$_GET[tel] Ext. $_GET[ext]";
$correo = "$_GET[mail]@mail.x";
//Escrever nome
imagettftext($rImg,14,0,850,60,$cor,'Open Sans',$_GET["nombre"]);
//imagestring($rImg,5,850,60,urldecode($_GET["nombre"]),$cor);
//imagestring($rImg,5,850,80,urldecode($_GET["puesto"]),$cor2);
//imagestring($rImg,5,800,120,urldecode($tel),$cor2);
//imagestring($rImg,5,800,140,urldecode($correo),$cor2);
//Header e output
header('Content-type: image/jpeg');
imagejpeg($rImg,NULL,100);
</code>```

My issue is, when I use imagestring, everything works fine, but I need to use Open Sans ttf so I tried to use imagettftext, but it "echoes" an empty result or error when loading img src and also when testing file separately it doesnt show any error.

Any suggestions?

UPDATE:

```<code>$tel = "$_GET[tel] Ext. $_GET[ext]";
$correo = "$_GET[mail]@mail.mx";
$puesto = strtoupper($_GET["puesto"]);

imagettftext($rImg, 14, 0, 780,60, $cor, 'OpenSans-Bold.ttf', $_GET['nombre']); (WORKS)
imagettftext($rImg, 8, 0, 780,80, $cor2, 'OpenSans-Regular.ttf', $puesto); (WORKS)
imagettftext($rImg,9,780,135,$cor2, 'OpenSans-Regular.ttf',urldecode($_GET["tel"])); (CRASHES)
imagettftext($rImg,9,780,172,$cor2,'OpenSans-Regular.ttf',$correo);(CRASHES)
imagettftext($rImg,8,780,209,$cor2,'OpenSans-Regular.ttf',$_GET["direccion"]);(CRASHES)
imagettftext($rImg,8,780,223,$cor2,'OpenSans-Regular.ttf',$_GET["dir2"]);(CRASHES)
</code>```

答:
As documented, the $fontfile parameter needs a path to the font file, not its display name:

The path to the TrueType font you wish to use.

The simplest solution is to put the .ttf file (opensans.ttf?) in the same folder as your script and then change your function call like so:

```<code>imagettftext($rImg, 14, 0, 850, 60, $cor, 'opensans.ttf', $_GET['nombre']);
</code>```

Title: How to correctly use of imagettftext?

Body:
I am making a form which the user is filling to create a mail signature:

generatarjeta.php

if(isset($_GET["suc"]) && $_GET["suc"] !="")
{ $code="";
  foreach($_GET as $key => $value){
    $code.= $key . "=" . $value . "&";
  }
  $code = rtrim($code,"&");
  ?>
  <img src="imagem.php?<?php echo $code;?>">

  <?php exit();
}

<form method="get">

Sucursal	<select name="suc">
          <option value="">Seleccione...</option>
          <?php
          $con_sucursal = mssql_query("select * from localitos where local NOT IN (3,5, 7,12, 13, 14,15,16,17,19, 20, 21, 22,23,24,25,26,27)");
          while ($res_sucursal = mssql_fetch_array($con_sucursal))
          {
            echo "<option value='$res_sucursal[0]'>$res_sucursal[1]</option>";
          }?>
        </select>

Nombre del Trabajador: 	<input type="text" name="nombre" required="" onkeypress="return textonly(event);"/>

Puesto: 	<input type="text" name="puesto" required="" onkeypress="return textonly(event);"/>

Telefono: 	<input type="text" name="tel" required="" onkeypress='return solonums(event)'/> Extension: <input type="text" name="ext" onkeypress='return solonums(event)'/>

correo: 	<input type="text" name="mail" placeholder="nombre.apellido"/>

<input type="submit" name="submit" value="Generar"/>	<input type="reset"/>

    </form>

imagem.php

//Carregar imagem
$rImg = ImageCreateFromJPEG("the_firma.jpg");
//Definir cor
$cor = imagecolorallocate($rImg, 226, 41, 34);
$cor2 = imagecolorallocate($rImg, 60, 60, 59);

$tel = "$_GET[tel] Ext. $_GET[ext]";
$correo = "$_GET[mail]@mail.x";
//Escrever nome
imagettftext($rImg,14,0,850,60,$cor,'Open Sans',$_GET["nombre"]);
//imagestring($rImg,5,850,60,urldecode($_GET["nombre"]),$cor);
//imagestring($rImg,5,850,80,urldecode($_GET["puesto"]),$cor2);
//imagestring($rImg,5,800,120,urldecode($tel),$cor2);
//imagestring($rImg,5,800,140,urldecode($correo),$cor2);
//Header e output
header('Content-type: image/jpeg');
imagejpeg($rImg,NULL,100);

My issue is, when I use imagestring, everything works fine, but I need to use Open Sans ttf so I tried to use imagettftext, but it "echoes" an empty result or error when loading img src and also when testing file separately it doesnt show any error.

Any suggestions?

UPDATE:

$tel = "$_GET[tel] Ext. $_GET[ext]";
$correo = "$_GET[mail]@mail.mx";
$puesto = strtoupper($_GET["puesto"]);

imagettftext($rImg, 14, 0, 780,60, $cor, 'OpenSans-Bold.ttf', $_GET['nombre']); (WORKS)
imagettftext($rImg, 8, 0, 780,80, $cor2, 'OpenSans-Regular.ttf', $puesto); (WORKS)
imagettftext($rImg,9,780,135,$cor2, 'OpenSans-Regular.ttf',urldecode($_GET["tel"])); (CRASHES)
imagettftext($rImg,9,780,172,$cor2,'OpenSans-Regular.ttf',$correo);(CRASHES)
imagettftext($rImg,8,780,209,$cor2,'OpenSans-Regular.ttf',$_GET["direccion"]);(CRASHES)
imagettftext($rImg,8,780,223,$cor2,'OpenSans-Regular.ttf',$_GET["dir2"]);(CRASHES)

Body:
As documented, the $fontfile parameter needs a path to the font file, not its display name:

The path to the TrueType font you wish to use.

The simplest solution is to put the .ttf file (opensans.ttf?) in the same folder as your script and then change your function call like so:

imagettftext($rImg, 14, 0, 850, 60, $cor, 'opensans.ttf', $_GET['nombre']);


问:
TypeError: itertuples() missing 1 required positional argument: 'self'
I am trying to read PDF file and save some data

```<code>import PyPDF2
import os
from pandas import DataFrame as df

FilePath = "/home/milenko/Documents/komp/"
FileName = "stats.pdf"
output_filename = "export.txt"
PageStart = 184
PageEnd = 185

for row in df.itertuples():
    page_start, page_end = row.PageStart, row.PageEnd
    filename = os.path.join(row.FilePath, row.FileName)
    with PdfFileMerger() as merger:
        merger.append(filename, pages=(page_start, page_end))
        merger.write(output_filename)
</code>```

I got this

```<code>  File "b21.py", line 11, in <module>
    for row in df.itertuples():
TypeError: itertuples() missing 1 required positional argument: 'self'
</code>```

My original effort was to read one page from terminal but I got data that were not formatted at all

```<code> pageObj = pdfReader.getPage(184)
"Appendix tables171Table A5 (continued) World merchandise exports by region and selected economy, 1990-00(Million dollars)19901991199219931994199519961997199819992000  Slovenia --668160836828831683128372904886048733  Spain556426017764334I609357312991613102091104277109037110246113747  Sweden5754055217561184985761292795848487982883849448484286933  Switzerland6378461517656786318570360816418084376150788568030081534
</code>```

How to solve this problem?I am looking for any solution that will print data into tables or whatever that can latter be exported and manipulated.

答:
About the TypeError:

itertuples is a Dataframe method, i.e. it has to be called from an instance of the class Dataframe. You're renaming the class Dataframe to df when you do from pandas import DataFrame as df, instead of instancing it.

Make an instance with df = Dataframe() and then you'll be able to call itertuples() (obviously you also need to fill the dataframe with data before being able to iterate over it).

About your use of itertuples:

I'm not completely sure of what you're trying to do here, but I think you should take a look at the itertuples documentation (and the example within). The function iterates over the data inside the dataframe. You're not even opening your pdf file, let alone reading data from it.

Body:
I am trying to read PDF file and save some data

import PyPDF2
import os
from pandas import DataFrame as df

FilePath = "/home/milenko/Documents/komp/"
FileName = "stats.pdf"
output_filename = "export.txt"
PageStart = 184
PageEnd = 185

for row in df.itertuples():
    page_start, page_end = row.PageStart, row.PageEnd
    filename = os.path.join(row.FilePath, row.FileName)
    with PdfFileMerger() as merger:
        merger.append(filename, pages=(page_start, page_end))
        merger.write(output_filename)

I got this

  File "b21.py", line 11, in <module>
    for row in df.itertuples():
TypeError: itertuples() missing 1 required positional argument: 'self'

My original effort was to read one page from terminal but I got data that were not formatted at all

 pageObj = pdfReader.getPage(184)
"Appendix tables171Table A5 (continued) World merchandise exports by region and selected economy, 1990-00(Million dollars)19901991199219931994199519961997199819992000  Slovenia --668160836828831683128372904886048733  Spain556426017764334I609357312991613102091104277109037110246113747  Sweden5754055217561184985761292795848487982883849448484286933  Switzerland6378461517656786318570360816418084376150788568030081534

How to solve this problem?I am looking for any solution that will print data into tables or whatever that can latter be exported and manipulated.


问:
Order mysql table by non column elements
I am developing an android app where users can view data according to the area they want. I am getting the area in my php back-end code. I have a table 'help' which has a column name. What I want to do is sort the entire table according to the percentage match using similar_text or something similar between users input and table name data in descending order.I don't know how to do it.This is how far I got.

```<code><?php
require_once "Database/DB_Connect.php";
$db = new DB_Connect();
$db_conn = $db->connect();
$area=$_REQUEST['area']
$name1=array();
$query="SELECT `name` from `help`";
$result=mysqli_query($db_conn,$query);
while ($row=$result->fetch_assoc()) {
    $name=$row['name'];
    similar_text($area,$name,$percentage);
    $query1="SELECT * FROM `help` ORDER BY '$percentage' DESC ";
    $result1=mysqli_query($db_conn,$query1);
    while($row1=$result1->fetch_assoc()){
        $name1[]=$row1;
    }
}
echo json_encode($name1);
$db_conn->close();
?>
</code>```

The output I am getting is the entire table data multiple times order by names in descending order

答:
I don't know if it is the optimum answer or not, however, I came up with a solution.</p>

```<code><?php
require_once "Database/DB_Connect.php";
$db = new DB_Connect();
$db_conn = $db->connect();
$name1=array();
$id=array();
$area = $_REQUEST['area'];
$query="SELECT * FROM `help`";
$result=mysqli_query($db_conn,$query);
while ($row=mysqli_fetch_array($result)) {
    $name1[]=$row['name'];
    $id[]=$row['id'];
}
$sorted_arr=array();
$sorted_id=array();
for($i=0; $i<count($name1); $i++) {
   $temp_arr[$i] = similar_text($search, $name1[$i]);
}
arsort($temp_arr);
foreach($temp_arr as $k => $v) {
    $sorted_arr[] = $name1[$k];
    $sorted_id[]=$id[$k];
}
$data = [];
for($i=0; $i<count($name1); $i++) {
    $sql="SELECT * FROM `help` WHERE `id`='$sorted_id[$i]' ";
    $result = $db_conn->query($sql);
    $data[]=$result->fetch_assoc();
}
echo json_encode($data);
$db_conn->close();
?>
</code>```

Body:
I am developing an android app where users can view data according to the area they want. I am getting the area in my php back-end code. I have a table 'help' which has a column name. What I want to do is sort the entire table according to the percentage match using similar_text or something similar between users input and table name data in descending order.I don't know how to do it.This is how far I got.

<?php
require_once "Database/DB_Connect.php";
$db = new DB_Connect();
$db_conn = $db->connect();
$area=$_REQUEST['area']
$name1=array();
$query="SELECT `name` from `help`";
$result=mysqli_query($db_conn,$query);
while ($row=$result->fetch_assoc()) {
    $name=$row['name'];
    similar_text($area,$name,$percentage);
    $query1="SELECT * FROM `help` ORDER BY '$percentage' DESC ";
    $result1=mysqli_query($db_conn,$query1);
    while($row1=$result1->fetch_assoc()){
        $name1[]=$row1;
    }
}
echo json_encode($name1);
$db_conn->close();
?>

The output I am getting is the entire table data multiple times order by names in descending order

Body:
I don't know if it is the optimum answer or not, however, I came up with a solution.

<?php
require_once "Database/DB_Connect.php";
$db = new DB_Connect();
$db_conn = $db->connect();
$name1=array();
$id=array();
$area = $_REQUEST['area'];
$query="SELECT * FROM `help`";
$result=mysqli_query($db_conn,$query);
while ($row=mysqli_fetch_array($result)) {
    $name1[]=$row['name'];
    $id[]=$row['id'];
}
$sorted_arr=array();
$sorted_id=array();
for($i=0; $i<count($name1); $i++) {
   $temp_arr[$i] = similar_text($search, $name1[$i]);
}
arsort($temp_arr);
foreach($temp_arr as $k => $v) {
    $sorted_arr[] = $name1[$k];
    $sorted_id[]=$id[$k];
}
$data = [];
for($i=0; $i<count($name1); $i++) {
    $sql="SELECT * FROM `help` WHERE `id`='$sorted_id[$i]' ";
    $result = $db_conn->query($sql);
    $data[]=$result->fetch_assoc();
}
echo json_encode($data);
$db_conn->close();
?>


问:
Progress bar in Status bar, a blank and a filled in char are not equal width
I am playing around creating code for a progress bar that runs in the Excel Status Bar. I want to replace my old dated userform with the 2 rectangles (which worked but I would sooner a less obtrusive method now).

Problem: The width of the chars I am using to signify "Filled In" and "Not Filled in" are slightly different, when using 100 of them you can see the percentage at the end appears to shift right as the progress increases.

Here is some working sample code to show you exactly what I mean:

```<code>Sub TestNewProgBar()
Dim X As Long
For X = 1 To 100000
    Call NewProgressBar("Testing", X, 100000)
Next
End Sub

Sub NewProgressBar(MyMessage As String, CurrentVal As Long, MaxVal As Long)
Dim FilledIn As Long, NotFilledIn As Long
If CurrentVal >= MaxVal Then
    Application.StatusBar = MyMessage & ": Complete"
Else
    FilledIn = Round((CurrentVal / MaxVal) * 100, 0)
    NotFilledIn = (100 - FilledIn)
    Application.StatusBar = MyMessage & ": " & Application.WorksheetFunction.Rept(ChrW(9608), FilledIn) & Application.WorksheetFunction.Rept(ChrW(9620), NotFilledIn) & "| " & FilledIn & "%"
End If
End Sub
</code>```

Run TestNewProgBar and look at the status bar.

Is this going to be a simple case of choosing a different Unicode symbol or are there forces beyond my control at work here?

答:
Edit:

To follow up on my 'aside' below, I did some experimenting, and Comintern was onto something when s/he provided a link to this issue. The problem described above is to do with ScreenUpdating. If Screenupdating is set to false when the status bar is changed, the character widths of ChrW(9608) and ChrW(9620) are the same.

I've no idea why, but it does the trick. So you'll want to do the following:

```<code>Application.Screenupdating = False

'code which changes the status bar

Application.Screenupdating = True
</code>```

(my previous comment continues below)

I prefer this pairing:

```<code>strFilledChar = ChrW(&H2588) 'a black rectangle, "Full Block"
strUnfilledChar = ChrW(&H2584) 'an array of sparse dots, "Light Shade"
</code>```

Or this one:

```<code>strFilledChar = ChrW(&H2588) 'a black rectangle, "Full Block"
strUnfilledChar = ChrW(&H2500) 'a horizontal line, "Block Drawings Light Horizontal"
</code>```

(as an aside, I encountered the same problem as described in the question whereby ChrW(9608) and ChrW(9620) have different widths - but only in one of my workbooks. In another workbook, they have the same widths and so the progress bar displays properly. I have no idea why.)

Body:
I am playing around creating code for a progress bar that runs in the Excel Status Bar. I want to replace my old dated userform with the 2 rectangles (which worked but I would sooner a less obtrusive method now).

Problem: The width of the chars I am using to signify "Filled In" and "Not Filled in" are slightly different, when using 100 of them you can see the percentage at the end appears to shift right as the progress increases.

Here is some working sample code to show you exactly what I mean:

Sub TestNewProgBar()
Dim X As Long
For X = 1 To 100000
    Call NewProgressBar("Testing", X, 100000)
Next
End Sub

Sub NewProgressBar(MyMessage As String, CurrentVal As Long, MaxVal As Long)
Dim FilledIn As Long, NotFilledIn As Long
If CurrentVal >= MaxVal Then
    Application.StatusBar = MyMessage & ": Complete"
Else
    FilledIn = Round((CurrentVal / MaxVal) * 100, 0)
    NotFilledIn = (100 - FilledIn)
    Application.StatusBar = MyMessage & ": " & Application.WorksheetFunction.Rept(ChrW(9608), FilledIn) & Application.WorksheetFunction.Rept(ChrW(9620), NotFilledIn) & "| " & FilledIn & "%"
End If
End Sub

Run TestNewProgBar and look at the status bar.

Is this going to be a simple case of choosing a different Unicode symbol or are there forces beyond my control at work here?

Body:
Edit:

To follow up on my 'aside' below, I did some experimenting, and Comintern was onto something when s/he provided a link to this issue. The problem described above is to do with ScreenUpdating. If Screenupdating is set to false when the status bar is changed, the character widths of ChrW(9608) and ChrW(9620) are the same.

I've no idea why, but it does the trick. So you'll want to do the following:

Application.Screenupdating = False

'code which changes the status bar

Application.Screenupdating = True

(my previous comment continues below)

I prefer this pairing:

strFilledChar = ChrW(&H2588) 'a black rectangle, "Full Block"
strUnfilledChar = ChrW(&H2584) 'an array of sparse dots, "Light Shade"

Or this one:

strFilledChar = ChrW(&H2588) 'a black rectangle, "Full Block"
strUnfilledChar = ChrW(&H2500) 'a horizontal line, "Block Drawings Light Horizontal"

(as an aside, I encountered the same problem as described in the question whereby ChrW(9608) and ChrW(9620) have different widths - but only in one of my workbooks. In another workbook, they have the same widths and so the progress bar displays properly. I have no idea why.)


问:
what the name for the item in the green circle
what's the element name in the green circle? Whta's the event corresponding to click this element?

答: Interestingly, this part of the DataGrid is no-man's-land - it doesn't even have an official name, let alone a behaviour or a template. In order to handle events related to this area, see here or here.</p>

ContentLicense: CC BY-SA 2.5


问:
Linq query returns half the results
I am making an intranet Website using asp.NET MVC5 and Entity Framework for Data Access. I have two tables Web_Documents and Web_Profiles and a relation's table Web_Profile_joint_Document. Now to retrieve the Documents I want, I have to use IDProfile of Web_Profiles table. Then using this, I can find documents in the relation's table. One problem though, the query I make returns half the results I want. In the test I am making I have 2 IDProfile, values being 120 & 124. Here is my query:

```<code>IEnumerable<Web_Documents> retrieveDocuments;
List<int> idProfiles = new List<int>();
idProfiles.Add(120);
idProfiles.Add(124);
foreach (var item in idProfiles)
{
    var idDocument = context.WebProfils
                    .Where(c => c.IDProfil == item)
                    .SelectMany(c => c.Documents).ToList();

    if (idDocument != null)
    {
         if (retrieveDocuments == null)
         {
              retrieveDocuments = idDocument;
         }
         else
         {
              retrieveDocuments.Concat(idDocument);
         }
}
</code>```

Since Web_Profiles and Web_Documents have a relation, I can access ICollection <Web_Documents> Documents which is in Web_Profiles POCO (entity). I then store results in retrieveDocuments. But this returns only the values for IDProfile=120. Any ideas why?

Thanks!

Remark All answers are good!

答:
You can delete the foreach and change your query in this way</p>

```<code>var idDocument = context.WebProfils
                .Where(c => idProfiles.Contains(c.IDProfil))
                .SelectMany(c => c.Documents).ToList();

if (idDocument != null) // Not required. idDocument can't be null (but can be empty)
{
     // Now the following lines are not required
     if (retrieveDocuments == null)
     {
          retrieveDocuments = idDocument;
     }
     else
     {
          retrieveDocuments.Concat(idDocument);
     }
}
</code>```

Title: Linq query returns half the results

Body:
I am making an intranet Website using asp.NET MVC5 and Entity Framework for Data Access. I have two tables Web_Documents and Web_Profiles and a relation's table Web_Profile_joint_Document. Now to retrieve the Documents I want, I have to use IDProfile of Web_Profiles table. Then using this, I can find documents in the relation's table. One problem though, the query I make returns half the results I want. In the test I am making I have 2 IDProfile, values being 120 & 124. Here is my query:

IEnumerable<Web_Documents> retrieveDocuments;
List<int> idProfiles = new List<int>();
idProfiles.Add(120);
idProfiles.Add(124);
foreach (var item in idProfiles)
{
    var idDocument = context.WebProfils
                    .Where(c => c.IDProfil == item)
                    .SelectMany(c => c.Documents).ToList();

    if (idDocument != null)
    {
         if (retrieveDocuments == null)
         {
              retrieveDocuments = idDocument;
         }
         else
         {
              retrieveDocuments.Concat(idDocument);
         }
}

Since Web_Profiles and Web_Documents have a relation, I can access ICollection <Web_Documents> Documents which is in Web_Profiles POCO (entity). I then store results in retrieveDocuments. But this returns only the values for IDProfile=120. Any ideas why?

Thanks!

Remark All answers are good!

Body:
You can delete the foreach and change your query in this way

var idDocument = context.WebProfils
                .Where(c => idProfiles.Contains(c.IDProfil))
                .SelectMany(c => c.Documents).ToList();

if (idDocument != null) // Not required. idDocument can't be null (but can be empty)
{
     // Now the following lines are not required
     if (retrieveDocuments == null)
     {
          retrieveDocuments = idDocument;
     }
     else
     {
          retrieveDocuments.Concat(idDocument);
     }
}


问:
Angular template versioning
I observed that often unexpected issues occurs with my apps as the user has templates cached in browser.
I tried $window.location.reload(true) but even then chrome serves templates from the cache.

Is there an easy solution for this like adding a version query parameter to template URL dynamically using something like Interceptor?

答:
Although on other similar question people sugested to use $templateCache and load everything in one go. This isn't the solution I was looking for as it would increase app first load time by increasing app size and sacrifing on lazy loading provided by angular-ui-router.

So, below is what I did.
Created a value provider for which contains version.
This file is minified and include in index page and thus gets loaded along with the page.

```<code>angular.module('my-app').value('version', 'X.X.X');
</code>```

I noticed that all my templateUrl in states, directives and even in ng-include is loaded via $http service and thus at time of fetching template I can inject a query parameter. So I added following lines in app's config block:

```<code>angular.module('my-app').config(['$httpProvider', function($httpProvider){
    $httpProvider.interceptors.push(['$q', 'version', function($q, version) {
        return {
            'request': function (request) {
                if (request.url.substr(-5) == '.html') {
                    request.params = {
                        v: version
                    }
                }
                return $q.resolve(request);
            }
        }
    }]);
}]);
</code>```

So, all my templates are called with version number and now browser waits for new template to load if version is increased.
I periodically check for version update via an api. And if a new version is detected, I prompt user to reload the page. On user approval, I reload it via $window.location.reload(true)

Update

Following is snippet to check for new version. It can vary according to use case. As we have ad-hoc release cycle here, we check for new version on each window focus and also during first load.

```<code>angular.module('my-app').run(['$rootScope', '$window', 'version', 'configService', function($rootScope, $window, version, configService){
    $rootScope.checkVersion = function () {
        configService.getVersion().then(function (data) {
            if (data.version != version) {
                // show user a message that new version is available
                promptUserForReload().then(function () {
                    $window.location.reload(true);
                })
            }
        });
    }

    $window.addEventListener("focus", $rootScope.checkVersion);

    $rootScope.checkVersion();
}])
</code>```

Title: Angular template versioning

Body:
Although on other similar question people sugested to use $templateCache and load everything in one go. This isn't the solution I was looking for as it would increase app first load time by increasing app size and sacrifing on lazy loading provided by angular-ui-router.

So, below is what I did.
Created a value provider for which contains version.
This file is minified and include in index page and thus gets loaded along with the page.

angular.module('my-app').value('version', 'X.X.X');

I noticed that all my templateUrl in states, directives and even in ng-include is loaded via $http service and thus at time of fetching template I can inject a query parameter. So I added following lines in app's config block:

angular.module('my-app').config(['$httpProvider', function($httpProvider){
    $httpProvider.interceptors.push(['$q', 'version', function($q, version) {
        return {
            'request': function (request) {
                if (request.url.substr(-5) == '.html') {
                    request.params = {
                        v: version
                    }
                }
                return $q.resolve(request);
            }
        }
    }]);
}]);

So, all my templates are called with version number and now browser waits for new template to load if version is increased.
I periodically check for version update via an api. And if a new version is detected, I prompt user to reload the page. On user approval, I reload it via $window.location.reload(true)

Update

Following is snippet to check for new version. It can vary according to use case. As we have ad-hoc release cycle here, we check for new version on each window focus and also during first load.

angular.module('my-app').run(['$rootScope', '$window', 'version', 'configService', function($rootScope, $window, version, configService){
    $rootScope.checkVersion = function () {
        configService.getVersion().then(function (data) {
            if (data.version != version) {
                // show user a message that new version is available
                promptUserForReload().then(function () {
                    $window.location.reload(true);
                })
            }
        });
    }

    $window.addEventListener("focus", $rootScope.checkVersion);

    $rootScope.checkVersion();
}])


答:
Concat returns a new list. You need to either do

```<code>retrieveDocuments = retrieveDocuments.Concat(idDocument);
</code>```

or

```<code>retrieveDocuments.AddRange(idDocument);
</code>```

Title: Linq query returns half the results

Body:
Concat returns a new list. You need to either do

retrieveDocuments = retrieveDocuments.Concat(idDocument);

or

retrieveDocuments.AddRange(idDocument);


问:
How do I troubleshoot this CLR error in SQL Server spatial
I have the following query:

```<code>Insert into PropertyTractsTemp
    Select
        P.field1 as field1 ,
        P.field2 as field2,
        P.field3 as field3,
        P.field4 as field4,
        G.GEOID,
        P.field5 as field5
    from PROPERTY_PARAMETERS P
    join BH_EDW.dbo.REF_GEOID_GEOG G WITH(INDEX([geog_sidx]))on G.geom.STIntersects(P.GeoLocation) =1
    where P.GEOID is null
</code>```

This may have 1,000 to 100Mil records to match up.
Either way, the query stops and I receive this error:

```<code>Msg 10316, Level 16, State 1, Line 3
The app domain with specified version id (4) was unloaded due to memory pressure and could not be found.
The statement has been terminated.
</code>```

I'm told it's a CLR error, and it has something to do with the spatial index but no explanation on how to troubleshoot it.

Any wisdom would be greatly appreciated.

答:
i had same problem using a custom Clr type in a column.
i solved adding "-g1024" (or you can choose an other value) on SqlServer service.

Body:
I have the following query:

Insert into PropertyTractsTemp
    Select
        P.field1 as field1 ,
        P.field2 as field2,
        P.field3 as field3,
        P.field4 as field4,
        G.GEOID,
        P.field5 as field5
    from PROPERTY_PARAMETERS P
    join BH_EDW.dbo.REF_GEOID_GEOG G WITH(INDEX([geog_sidx]))on G.geom.STIntersects(P.GeoLocation) =1
    where P.GEOID is null

This may have 1,000 to 100Mil records to match up.
Either way, the query stops and I receive this error:

Msg 10316, Level 16, State 1, Line 3
The app domain with specified version id (4) was unloaded due to memory pressure and could not be found.
The statement has been terminated.

I'm told it's a CLR error, and it has something to do with the spatial index but no explanation on how to troubleshoot it.

Any wisdom would be greatly appreciated.


问:
How to add dummy rows in MakeTable Query - Access 2000?
I have this picture:

As you can see the field "promet" can go from 1 to 9. However for tipprod = "02" promet has values of 1, 2, 3, 5 and 7.

I want to add dummy rows for missing values of promet, 4, 6, 8 and 9, and I want to do it for other values of tipprod, like "03" for example or "04" etc...

Here is an example of my query with some columns removed:

How can i do that?

答:
Years ago I wrote an article about this. It is still on-line:

Find and Generate Missing Values in an Access Table

It lists the numbers missing, but you should be able to modify the code to also append these to the table.


问:
Android studio trying to connect to mongodb using AsyncTask throwing an error exception
```<code>MongoCredential credential = MongoCredential.createCredential(user, database, password);
MongoClientOptions options = MongoClientOptions.builder().sslEnabled(true).build();
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(credential), options);
</code>```

<p>throwing the following error </p>

```<code>Failed to get process identifier from JMX, using random number instead
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
    at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:506)
    at org.bson.types.ObjectId.<clinit>(ObjectId.java:464)
    at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
    at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:69)
    at com.mongodb.Mongo.createCluster(Mongo.java:683)
    at com.mongodb.Mongo.createCluster(Mongo.java:669)
    at com.mongodb.Mongo.<init>(Mongo.java:282)
    at com.mongodb.MongoClient.<init>(MongoClient.java:187)
    at com.example.michael.version_10.Connection.doInBackground(Connection.java:40)
    at com.example.michael.version_10.Connection.doInBackground(Connection.java:30)
    at android.os.AsyncTask$2.call(AsyncTask.java:305)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.management.ManagementFactory" on path: DexPathList[[zip file "/data/app/com.example.michael.version_10-1/base.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.michael.version_10-1/lib/x86, /system/lib, /vendor/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:506)
    at org.bson.types.ObjectId.<clinit>(ObjectId.java:464)
    at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
    at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:69)
    at com.mongodb.Mongo.createCluster(Mongo.java:683)
    at com.mongodb.Mongo.createCluster(Mongo.java:669)
    at com.mongodb.Mongo.<init>(Mongo.java:282)
    at com.mongodb.MongoClient.<init>(MongoClient.java:187)
    at com.example.michael.version_10.Connection.doInBackground(Connection.java:40)
    at com.example.michael.version_10.Connection.doInBackground(Connection.java:30)
    at android.os.AsyncTask$2.call(AsyncTask.java:305)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)
</code>```

答: I was actually doing it the wrong way. It is not advisable to connect to MongoDB directly it is recommended to use an Rest API. And that solved my problem.</p>

ContentLicense: CC BY-SA 4.0

Body:
MongoCredential credential = MongoCredential.createCredential(user, database, password);
MongoClientOptions options = MongoClientOptions.builder().sslEnabled(true).build();
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(credential), options);

throwing the following error

Failed to get process identifier from JMX, using random number instead
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
    at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:506)
    at org.bson.types.ObjectId.<clinit>(ObjectId.java:464)
    at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
    at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:69)
    at com.mongodb.Mongo.createCluster(Mongo.java:683)
    at com.mongodb.Mongo.createCluster(Mongo.java:669)
    at com.mongodb.Mongo.<init>(Mongo.java:282)
    at com.mongodb.MongoClient.<init>(MongoClient.java:187)
    at com.example.michael.version_10.Connection.doInBackground(Connection.java:40)
    at com.example.michael.version_10.Connection.doInBackground(Connection.java:30)
    at android.os.AsyncTask$2.call(AsyncTask.java:305)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.management.ManagementFactory" on path: DexPathList[[zip file "/data/app/com.example.michael.version_10-1/base.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.michael.version_10-1/lib/x86, /system/lib, /vendor/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:506)
    at org.bson.types.ObjectId.<clinit>(ObjectId.java:464)
    at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
    at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:69)
    at com.mongodb.Mongo.createCluster(Mongo.java:683)
    at com.mongodb.Mongo.createCluster(Mongo.java:669)
    at com.mongodb.Mongo.<init>(Mongo.java:282)
    at com.mongodb.MongoClient.<init>(MongoClient.java:187)
    at com.example.michael.version_10.Connection.doInBackground(Connection.java:40)
    at com.example.michael.version_10.Connection.doInBackground(Connection.java:30)
    at android.os.AsyncTask$2.call(AsyncTask.java:305)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)


问:
Remove storyboard left and right padding on IB
I'm trying to remove the seemingly forced left and right padding on a storyboard, need to anchor my view on the border on the Storyboard. Doesn't seem to give me the option to anchor on the border in the interface builder.

Most probably not best practice, but the design looks weird with this padding.

How can I remove the white space on the left and right:

Update:

I have checked the constraint value, its bound at zero on superview.

It only works if I use -20 and 20 for trailing and leading. Need to change superview itself?

答:
When your on the storyboard select the control you want to have edge to edge, and in the properties window if you select layout you will see the constraints that you've added.

You would want to double click on the 'leading margin space'and set it's 'constant' value to 0 (this can be a bit buggy sometimes, so it may show 0 already, simply remove the 0, re-enter the value 0 and save)

Finally repeat the first step and select the 'Trailing Space' constraint and do the same thing.

once done press on the square icon which visually adjusts the control into it's new constraints and it should be edge to edge.


问:
Different behavior in a job when execute it from the kitchen
I'm using Pentaho Data Integration 7.1 to copy some local files to a Hadoop 2.8.0 Cluster. I have created a Hadoop Cluster connection on Pentaho and I'm using a Hadoop Copy Files step. I can successfully upload the files when I execute my job from the GUI (spoon.sh), I can see the following line on the log:

Hadoop Copy Files - Processing row source File/folder source : [file:///home/etl/Desktop/users_full_20170620.csv] ... destination file/folder : [hdfs://hadoop:***@spark-master.cu:9000/value_iq]... wildcard : [null]

But when I attempt to run the same transformation using the kitchen.sh fails I got the following error:

Hadoop Copy Files - ERROR (version 7.1.0.0-12, build 1 from 2017-05-16 17.18.02 by buildguy) : Folder  file:///value_iq/bin/kettle/data-integration_7.1/hdfs:/hadoop:hadoop@spark-master.cu:9000/value_iq does not exist!

Somehow it's adding the path where the kitchen.sh is located in front of the hdfs url, assuming that the destinations enviroment is local.

This is a screenshot of my Hadoop Copy Files step

a JIRA report of this bug has been created: http://jira.pentaho.com/browse/PDI-16443

答:
As far as I can see PDI expects a file which does not exists. Create it!

To move a PDI solution from dev to prod, makes files references relative. Instead of hard-coding the folder name, press Ctrl-space, and select ${Internal.Job.Filename.Directory} which will be replaced at runtime by the name of the directory containing your job/transfo and are different on your dev machine and your prod environment.

You can setup manually these name before each un: you are presented a list of Parameters and Variables, among which the {Internal.Job.Filename.Directory which you can change for this run.

You can also (I advise you to do so early in the dev process) define your own variables. In the top menu, Edit the kettle.properties, and add my-dir. It will appear on the Ctrl-space and the run options. The kettle.properties is stored in a hidden directory named .kettle, and is different on your dev machine and your prod serer.

You will very soon how to set and change these variables in job and transfos with Get variables and Set variable in order to automate load with loops. SOme example can be found in the sample directory which was shipped with your PDI distribution.


问:
Drupal 8 in visual studio code
I'm using Visual Studio Code for different web development. Recently I'm using Drupal 8 to develop new websites. Drupal 8 has some theme file to place some PHP code in it to changes some parts of theming. How can I debug this theme files in Visual Studio Code? I can't place any breakpoints in my code.</p>

答:
If you want to use Drupal with vscode I suggest you to install VS-code-drupal extension. It makes .module files recognizable as php files.

If you want to debug php code I suggest you to install vscode-php-debug extension. It's a bit tricky to configure, but if you follow the guide you will succeed.

Another useful extension is vscode-code-runner. It runs portions of code for testing it on the fly.

Unfortunately I have not found yet a good extension for php intellisense.

Title: Drupal 8 in visual studio code


问:
How to fetch 4 characters from a string in oracle?
By using following query i am able to fetch a particular string.Now this output string contains alphanumeric characters.e.g.abcd123,pqrs542356.
Now i want to fetch only first 4 characters of this string which will be always alpha bates.

Query::

```<code>(SELECT SUBSTR(in_msg, INSTR( in_msg,'?', 1, 10 )+ 1, INSTR(in_msg,'?', 1, 11 ) - INSTR( in_msg,'?', 1, 10 )- 1)
 FROM emp_message
WHERE emp_no IN (SELECT emp_no
                   FROM main_table
                  WHERE name like '%abcd%')
</code>```

This query returns output as e.g.abcd1234,pqrs145423.
Again i want to fetch only first 4 characters from this query output.
Can somebody help me in this.

答:
Here it is:</p>

```<code>SUBSTR(field, 0, 4)
</code>```

Body:
By using following query i am able to fetch a particular string.Now this output string contains alphanumeric characters.e.g.abcd123,pqrs542356.
Now i want to fetch only first 4 characters of this string which will be always alpha bates.

Query::

(SELECT SUBSTR(in_msg, INSTR( in_msg,'?', 1, 10 )+ 1, INSTR(in_msg,'?', 1, 11 ) - INSTR( in_msg,'?', 1, 10 )- 1)
 FROM emp_message
WHERE emp_no IN (SELECT emp_no
                   FROM main_table
                  WHERE name like '%abcd%')

This query returns output as e.g.abcd1234,pqrs145423.
Again i want to fetch only first 4 characters from this query output.
Can somebody help me in this.

Body:
Here it is:

SUBSTR(field, 0, 4)


问:
Counting the selected/checked boxes [EXCEL]
One of the columns (MONTHS), let's say column A in my raw data contains numbers ranging from 0-12. Now, in another sheet, I'd like to be able to count the number of observations with the selected / checked months as shown below:

How can I do that? I tried doing it with countifs but hit a snag because column A is numeric and when a user checks a box in the other sheet, it only evaluates to "TRUE". Any ideas? Thank you!

EDIT:

The column of MONTHS LOOKS LIKE THE FOLLOWING:

答:
This formula should work for you:

```<code>=SUMPRODUCT(($A$1:$A$13)*COUNTIF(F:F,$B$1:$B$13))
</code>```

Adjust it to your actual data layout by adding sheet names to the ranges.

Body:
This formula should work for you:

=SUMPRODUCT(($A$1:$A$13)*COUNTIF(F:F,$B$1:$B$13))

Adjust it to your actual data layout by adding sheet names to the ranges.


问:
How to disable interface suggestions in VSCode?
I.E Global browser interfaces keep showing up while editing .js files and therefore distracting my work? </p>

答:
This was a bug in VSCode <=1.13: https://github.com/Microsoft/TypeScript/issues/15750

It should be fixed in VSCode 1.14+. Please let us know if you still see this issue: https://github.com/Microsoft/vscode/issues/new


问:
Curl error: Operation timed out
I have the following fatal error when trying to use Curl:

```<code>PHP Fatal error:  Uncaught HTTP_Request2_MessageException:
Curl error: Operation timed out after 30000 milliseconds with 0 bytes received in
/usr/share/php/HTTP/Request2/Adapter/Curl.php on line 200
Exception trace    Function       Location
0                  HTTP_Request2_Adapter_Curl::wrapCurlError('Resource id #12')
                   /usr/share/php/HTTP/Request2/Adapter/Curl.php:200
1                  HTTP_Request2_Adapter_Curl->sendRequest(Object(HTTP_Request2))
/usr/share/php/HTTP/Request2.php:959< in /usr/share/php/HTTP/Request2/Adapter/Curl.php on line 172
</code>```

However, I can't see how to best debug it. There's no reference to any line of code I've written, only the HTTP_Request2 and Curl modules. What's the best approach to try and resolve this?

答:
Some time this error in Joomla appear because some thing incorrect with SESSION or coockie.
That may because incorrect HTTPd server setting or because some before CURL or Server http requests

so PHP code like:

```<code>  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
</code>```

will need replace to PHP code

```<code>  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
  //if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);
</code>```

May be some body reply how this options connected with "Curl error: Operation timed out after .."

Title: Curl error: Operation timed out

Body:
I have the following fatal error when trying to use Curl:

PHP Fatal error:  Uncaught HTTP_Request2_MessageException:
Curl error: Operation timed out after 30000 milliseconds with 0 bytes received in
/usr/share/php/HTTP/Request2/Adapter/Curl.php on line 200
Exception trace    Function       Location
0                  HTTP_Request2_Adapter_Curl::wrapCurlError('Resource id #12')
                   /usr/share/php/HTTP/Request2/Adapter/Curl.php:200
1                  HTTP_Request2_Adapter_Curl->sendRequest(Object(HTTP_Request2))
/usr/share/php/HTTP/Request2.php:959< in /usr/share/php/HTTP/Request2/Adapter/Curl.php on line 172

However, I can't see how to best debug it. There's no reference to any line of code I've written, only the HTTP_Request2 and Curl modules. What's the best approach to try and resolve this?

Body:
Some time this error in Joomla appear because some thing incorrect with SESSION or coockie.
That may because incorrect HTTPd server setting or because some before CURL or Server http requests

so PHP code like:

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

will need replace to PHP code

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
  //if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

May be some body reply how this options connected with "Curl error: Operation timed out after .."


问:
Scrolling 2 textview in same time with Android Studio
I wouldlike to scroll 2 textview in same time:

Code :

```<code>TextView text_A;
TextView text_B;

A=(TextView)findViewById(R.id.t1);
B=(TextView)findViewById(R.id.t2);

A.setMouvementMethod(new ScrollingMovementMethod());
B.setMouvementMethod(new ScrollingMovementMethod());
</code>```

How can I change this code for works ?

Thanks for your help !

答:
You can just put all your text views into a LinearLayout and then put that layout into the ScrollView.For example,

```<code>    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="horizontal" android:id="@+id/ScrollView">

<LinearLayout
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:id="@+id/linearLayout1"
        android:layout_height="fill_parent"
        android:layout_gravity="center_vertical|center_horizontal">

    <TextView android:text="@string/textView1"
        android:id="@+id/t1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>

    <TextView android:text="@string/textView2"
        android:id="@+id/t2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>
</LinearLayout>
</ScrollView>
</code>```

Also try with this link also,
Try

Body:
I wouldlike to scroll 2 textview in same time:

Code :

TextView text_A;
TextView text_B;

A=(TextView)findViewById(R.id.t1);
B=(TextView)findViewById(R.id.t2);

A.setMouvementMethod(new ScrollingMovementMethod());
B.setMouvementMethod(new ScrollingMovementMethod());

How can I change this code for works ?

Thanks for your help !

Body:
You can just put all your text views into a LinearLayout and then put that layout into the ScrollView.For example,

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="horizontal" android:id="@+id/ScrollView">

<LinearLayout
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:id="@+id/linearLayout1"
        android:layout_height="fill_parent"
        android:layout_gravity="center_vertical|center_horizontal">

    <TextView android:text="@string/textView1"
        android:id="@+id/t1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>

    <TextView android:text="@string/textView2"
        android:id="@+id/t2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>
</LinearLayout>
</ScrollView>

Also try with this link also,
Try


问:
VBA Excel Removing duplicate rows
So I'm trying to remove any rows that have a duplicate in column C. This is a column of about 700 records however this value varies with different data used hence I've implemented a "LastRow" function. Here's my code:

```<code>Public Function LastRowInCRC() As Long

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    With wsCRC
        LastRowInCRC = .Cells(.Rows.Count, "C").End(xlUp).Row
    End With

End Function

Sub DeleteDupRowsCRC()

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    Dim lrowcrc As Long
    lrowcrc = CRC.LastRowInCRC

    'Debug.Print "C8:C" & lrowcrc

    With wsCRC

        .Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3)

    End With

End Sub
</code>```

I get the "application-defined or object-defined" error at the following line when I step by step debug:

```<code>.Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3)
</code>```

Any ideas whats going wrong? I call the "C8:C" & lrowcrc to the immediate window which is commented out, and it gives me the correct range values so I don't think the issue is in that but I cannot find whats wrong... any help greatly appreciated.

答:
In general, change Array(3) to Array(1) and it may work.

Not general: The following works for me, removing the duplicates in column C Make sure that you work on the first Worksheet:

```<code>Option Explicit

Public Function LastRowInCRC() As Long

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets(1)

    With wsCRC
        LastRowInCRC = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

End Function

Sub DeleteDupRowsCRC()

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets(1)

    Dim lrowcrc As Long
    lrowcrc = LastRowInCRC

    'Debug.Print "C8:C" & lrowcrc

    With wsCRC

        .Range("C1:C" & lrowcrc).RemoveDuplicates Columns:=Array(1)

    End With

End Sub
</code>```

In your code, Array(3) means that you should have at least three column in the .Range. But you only have column C there. Thus, it gives mistake. To work with Array(3), Write A1:C and it would be working.

Title: VBA Excel Removing duplicate rows

Body:
So I'm trying to remove any rows that have a duplicate in column C. This is a column of about 700 records however this value varies with different data used hence I've implemented a "LastRow" function. Here's my code:

Public Function LastRowInCRC() As Long

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    With wsCRC
        LastRowInCRC = .Cells(.Rows.Count, "C").End(xlUp).Row
    End With

End Function

Sub DeleteDupRowsCRC()

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets("CRC")

    Dim lrowcrc As Long
    lrowcrc = CRC.LastRowInCRC

    'Debug.Print "C8:C" & lrowcrc

    With wsCRC

        .Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3)

    End With

End Sub

I get the "application-defined or object-defined" error at the following line when I step by step debug:

.Range("C8:C" & lrowcrc).RemoveDuplicates Columns:=Array(3)

Any ideas whats going wrong? I call the "C8:C" & lrowcrc to the immediate window which is commented out, and it gives me the correct range values so I don't think the issue is in that but I cannot find whats wrong... any help greatly appreciated.

Body:
In general, change Array(3) to Array(1) and it may work.

Not general: The following works for me, removing the duplicates in column C Make sure that you work on the first Worksheet:

Option Explicit

Public Function LastRowInCRC() As Long

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets(1)

    With wsCRC
        LastRowInCRC = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

End Function

Sub DeleteDupRowsCRC()

    Dim wsCRC As Worksheet
    Set wsCRC = Worksheets(1)

    Dim lrowcrc As Long
    lrowcrc = LastRowInCRC

    'Debug.Print "C8:C" & lrowcrc

    With wsCRC

        .Range("C1:C" & lrowcrc).RemoveDuplicates Columns:=Array(1)

    End With

End Sub

In your code, Array(3) means that you should have at least three column in the .Range. But you only have column C there. Thus, it gives mistake. To work with Array(3), Write A1:C and it would be working.


问:
How to generate a jar file for the java program which has property file
How to generate a jar file for the java program which has property file</p>
```<code>public class Download_logfiles {
/**
 * Download_logfiles class has to be public because another class uses the
 * Download_logfiles class
 */

private static URL URLObj;
/**
 * variable set for the server links from which the log files to be
 * downloaded
 */
private static URLConnection connect;
/** Variable for URL connection */
static String filename = "";
/** Variable used for extracting the servers */
static String user = "";
/** Variable used for user id */
static String pass = "";
/** Variable used for password */

static String download = "";
static Set<String> urls = new HashSet<String>();
static Set<String> comp = new HashSet<String>();
static Set<String> envir = new HashSet<String>();
static Properties prop = new Properties();

public static void main(String[] args)
        throws IOException { /** program entry point */

    System.out.println("argument count:" + args.length + " content:" + args);

    if(args.length==0)
    {
        System.out.println("Please enter the property file via arguments!!!");   /**Go to run configuration and under arguments enter the path **/
        System.exit(0);
    }

    readConfigProperties(args[0]);
    configUIParameter();
    Hashtable<String, String> loginfo = Validation();
    String componentavx = loginfo
            .get("component"); /** extract component information */
    String environmentProd = loginfo
            .get("environment"); /** extract environment information */
    config(componentavx, environmentProd);
    user = loginfo.get(
            "user"); /** extract login information from the property file */
    pass = loginfo.get("pass");

    try { /** Usage of Try catch handlers */
        String currentURL;
        Iterator<String> iter = urls.iterator();
        System.out.println(iter);

        while (iter.hasNext()) { /** Start iterating over URLs */

            currentURL = iter.next();
            StringTokenizer st = new StringTokenizer(currentURL,
                    "/."); /**
                             * The string tokenizer class allows an
                             * application to break a string into tokens
                             */
            st.nextToken();
            String filePrefix = st.nextToken();
            System.out.println("Url: " + currentURL);

            boolean moreFilesAvailable = true; /**
                                                 * check condition for all
                                                 * log files available in
                                                 * the server
                                                 */

            for (int i = 0; moreFilesAvailable; i++) {

                File file = null;

                if (i != 0) { /** Handle the condition */
                    URLObj = new URL(currentURL + filename + "." + i);

                } else {
                    URLObj = new URL(currentURL + filename);

                }
</code>```

答: You should be able to do it just like any other. See this on how to generate a jar file: Java creating .jar file </p>

Body:
How to generate a jar file for the java program which has property file

public class Download_logfiles {
/**
 * Download_logfiles class has to be public because another class uses the
 * Download_logfiles class
 */

private static URL URLObj;
/**
 * variable set for the server links from which the log files to be
 * downloaded
 */
private static URLConnection connect;
/** Variable for URL connection */
static String filename = "";
/** Variable used for extracting the servers */
static String user = "";
/** Variable used for user id */
static String pass = "";
/** Variable used for password */

static String download = "";
static Set<String> urls = new HashSet<String>();
static Set<String> comp = new HashSet<String>();
static Set<String> envir = new HashSet<String>();
static Properties prop = new Properties();

public static void main(String[] args)
        throws IOException { /** program entry point */

    System.out.println("argument count:" + args.length + " content:" + args);

    if(args.length==0)
    {
        System.out.println("Please enter the property file via arguments!!!");   /**Go to run configuration and under arguments enter the path **/
        System.exit(0);
    }

    readConfigProperties(args[0]);
    configUIParameter();
    Hashtable<String, String> loginfo = Validation();
    String componentavx = loginfo
            .get("component"); /** extract component information */
    String environmentProd = loginfo
            .get("environment"); /** extract environment information */
    config(componentavx, environmentProd);
    user = loginfo.get(
            "user"); /** extract login information from the property file */
    pass = loginfo.get("pass");

    try { /** Usage of Try catch handlers */
        String currentURL;
        Iterator<String> iter = urls.iterator();
        System.out.println(iter);

        while (iter.hasNext()) { /** Start iterating over URLs */

            currentURL = iter.next();
            StringTokenizer st = new StringTokenizer(currentURL,
                    "/."); /**
                             * The string tokenizer class allows an
                             * application to break a string into tokens
                             */
            st.nextToken();
            String filePrefix = st.nextToken();
            System.out.println("Url: " + currentURL);

            boolean moreFilesAvailable = true; /**
                                                 * check condition for all
                                                 * log files available in
                                                 * the server
                                                 */

            for (int i = 0; moreFilesAvailable; i++) {

                File file = null;

                if (i != 0) { /** Handle the condition */
                    URLObj = new URL(currentURL + filename + "." + i);

                } else {
                    URLObj = new URL(currentURL + filename);

                }


问:
java 8 findFirst vs map on optional
Given this code:

```<code>class Foo {
  Integer attr;
  public Integer getAttr() {return attr;}
}

List<Foo> list = new ArrayList<>();
list.add(new Foo());

list.stream().map(Foo::getAttr).findAny().orElse(null);  //A
list.stream().findAny().map(Foo::getAttr).orElse(null);  //B
</code>```

Line A throws

java.lang.NullPointerException: null

while line B returns null.

What is the cause of this behaviour? Both findAny() and map() return Optional<T>.

答:
```<code>list.stream().map(Foo::getAttr)
</code>```

... returns a stream with one element, with a value of null.

The JavaDoc for findAny() (and findFirst()) says:

Returns:

an Optional describing some element of this stream, or an
  empty Optional if the stream is empty

Throws:

NullPointerException - if the element selected is null

So findAny() is doing exactly as documented: it's selecting a null, and as a result, throwing NullPointerException.

This makes sense because Optional is (again according to JavaDoc, but emphasis mine):

A container object which may or may not contain a non-null value

... which means you can guarantee that Optional.ifPresent( x -> x.method()) will never throw NullPointerException due to x being null.

So findAny() could not return Optional.of(null). And Optional.empty() means that the stream was empty, not that it found a null.

Many parts of the Stream/Optional infrastructure are about discouraging the use of nulls.

You can get around this by mapping the nulls to Optionals, to yield an Optional<Optional<Foo>> -- which looks a bit convoluted, but is an accurate representation of your domain. Optional.empty() means the stream was empty. Optional.of(Optional.empty()) means it found one null element:

```<code>list.stream().map(Foo::getAttr).map(Optional::ofNullable).findAny()
</code>```

Title: java 8 findFirst vs map on optional

Body:
Given this code:

class Foo {
  Integer attr;
  public Integer getAttr() {return attr;}
}

List<Foo> list = new ArrayList<>();
list.add(new Foo());

list.stream().map(Foo::getAttr).findAny().orElse(null);  //A
list.stream().findAny().map(Foo::getAttr).orElse(null);  //B

Line A throws

java.lang.NullPointerException: null

while line B returns null.

What is the cause of this behaviour? Both findAny() and map() return Optional<T>.

Body:
list.stream().map(Foo::getAttr)

... returns a stream with one element, with a value of null.

The JavaDoc for findAny() (and findFirst()) says:

Returns:

an Optional describing some element of this stream, or an
  empty Optional if the stream is empty

Throws:

NullPointerException - if the element selected is null

So findAny() is doing exactly as documented: it's selecting a null, and as a result, throwing NullPointerException.

This makes sense because Optional is (again according to JavaDoc, but emphasis mine):

A container object which may or may not contain a non-null value

... which means you can guarantee that Optional.ifPresent( x -> x.method()) will never throw NullPointerException due to x being null.

So findAny() could not return Optional.of(null). And Optional.empty() means that the stream was empty, not that it found a null.

Many parts of the Stream/Optional infrastructure are about discouraging the use of nulls.

You can get around this by mapping the nulls to Optionals, to yield an Optional<Optional<Foo>> -- which looks a bit convoluted, but is an accurate representation of your domain. Optional.empty() means the stream was empty. Optional.of(Optional.empty()) means it found one null element:

list.stream().map(Foo::getAttr).map(Optional::ofNullable).findAny()


问:
Why does this code return a list index error?
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

```<code>if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)
</code>```

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

```<code>def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result
</code>```

答:
The canonical way to avoid this kind of off-the-board testing is to have a buffer zone of one or two rows/columns at the edges of the board. The board positions would have, as well as the usual values of "empty" or which side owned the square with what type of piece, a special "invalid" code. This would usually be coupled with a board representation as a ONE-dimensional array.

For example, chess would use an array of size 120 (10 columns x 12 rows). You need a margin of 2 to cater for knights ... 2 rows at each end but you need only one vertical margin as it can be shared.

E.g.

```<code>KNIGHT_DELTAS = (-21, -19, -12, -8, 8, 12, 19, 21)
# I have a knight at "currpos"; what are its options?
for delta in KNIGHT_DELTAS:
    newpos = currpos + delta
    target = board[newpos]
    if target & EMPTY:
        can_move_to(newpos)
    elif target & OTHER_TEAM:
        can_capture(at=newpos, captured_piece=target & PIECE_VALUE)
    else:
        # Either off the board or occupied by MY_TEAM.
        # Notice that we didn't even need to test explicitly for "off the board".
        pass
</code>```

Body:
Basically it's supposed to take a set of coordinates and return a list of coordinates of it's neighbors. However, when it hits here:

if result[i][0] < 0 or result[i][0] >= board.dimensions:
    result.pop(i)

when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?

def neighborGen(row,col,board):
    """
    returns lists of coords of neighbors, in order of up, down, left, right
    """

    result = []
    result.append([row-1 , col])
    result.append([row+1 , col])
    result.append([row , col-1])
    result.append([row , col+1])

     #prune off invalid neighbors (such as (0,-1), etc etc)
     for i in range(len(result)):
        if result[i][0] < 0 or result[i][0] >= board.dimensions:
            result.pop(i)
        if result[i][1] < 0 or result[i][1] >= board.dimensions:
            result.pop(i)

    return result

Body:
The canonical way to avoid this kind of off-the-board testing is to have a buffer zone of one or two rows/columns at the edges of the board. The board positions would have, as well as the usual values of "empty" or which side owned the square with what type of piece, a special "invalid" code. This would usually be coupled with a board representation as a ONE-dimensional array.

For example, chess would use an array of size 120 (10 columns x 12 rows). You need a margin of 2 to cater for knights ... 2 rows at each end but you need only one vertical margin as it can be shared.

E.g.

KNIGHT_DELTAS = (-21, -19, -12, -8, 8, 12, 19, 21)
# I have a knight at "currpos"; what are its options?
for delta in KNIGHT_DELTAS:
    newpos = currpos + delta
    target = board[newpos]
    if target & EMPTY:
        can_move_to(newpos)
    elif target & OTHER_TEAM:
        can_capture(at=newpos, captured_piece=target & PIECE_VALUE)
    else:
        # Either off the board or occupied by MY_TEAM.
        # Notice that we didn't even need to test explicitly for "off the board".
        pass


问:
Cannot implement delete in Rails controller
I'm following this tutorial to built a simple blogger side.

However, I am unable to implement the delete function as shown by the tutorial.

The steps given are as follows:

Let’s define the destroy method in our ArticlesController so it:

Uses params[:id] to find the article in the database

Calls .destroy on that object

Redirects to the articles index page

Do that now on your own and test it.

This is my code:

```<code>class ArticlesController < ApplicationController
    include ArticlesHelper

    def index
        @articles = Article.all
    end

    def show
        @article = Article.find(params[:id])
    end

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)
        @article.save
        flash.notice = "Article '#{@article.title}' Created!"
        redirect_to article_path(@article)
    end

    def destroy
        @article = Article.find(params[:id])
        @article.destroy
        redirect_to articles_path
    end
end
</code>```

show.html.erb

```<code><h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<%= link_to "<< Back to Articles List", articles_path %>
<%= link_to "delete", article_path(@article), method: :delete %>
</code>```

article_helper.rb

```<code>module ArticlesHelper

  def article_params
    params.require(:article).permit(:title, :body)
  end

end
</code>```

I have browsed through other solutions online but I don't see any code which I might have missed out.

In my case, clicking on the delete link only results in the page refreshing.

答:
I figured out the issue:

The setup was running on Windows. I applied a fix previously as the page would not load.

This fix caused the error here :

ActionController::RoutingError (No route matches [GET]
  "/javascripts/default.js"):

The way to fix this is to undo the previous changes above and follow the fix here.

Apparently, coffee-script-source 1.9 and above does not work on Windows.

Body:
I'm following this tutorial to built a simple blogger side.

However, I am unable to implement the delete function as shown by the tutorial.

The steps given are as follows:

Let’s define the destroy method in our ArticlesController so it:

Uses params[:id] to find the article in the database

Calls .destroy on that object

Redirects to the articles index page

Do that now on your own and test it.

This is my code:

class ArticlesController < ApplicationController
    include ArticlesHelper

    def index
        @articles = Article.all
    end

    def show
        @article = Article.find(params[:id])
    end

    def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_params)
        @article.save
        flash.notice = "Article '#{@article.title}' Created!"
        redirect_to article_path(@article)
    end

    def destroy
        @article = Article.find(params[:id])
        @article.destroy
        redirect_to articles_path
    end
end

show.html.erb

<%= @article.title %>

<%= @article.body %>

<%= link_to "<< Back to Articles List", articles_path %>
<%= link_to "delete", article_path(@article), method: :delete %>

article_helper.rb

module ArticlesHelper

  def article_params
    params.require(:article).permit(:title, :body)
  end

end

I have browsed through other solutions online but I don't see any code which I might have missed out.

In my case, clicking on the delete link only results in the page refreshing.