text:
Q: taskSnapshot.getDownloadUrl() method not working private void uploadImageToFirebaseStorage() {
    StorageReference profileImageRef =
        FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");

    if (uriProfileImage != null) {
        progressBar.setVisibility(View.VISIBLE);
        profileImageRef.putFile(uriProfileImage)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                    progressBar.setVisibility(View.GONE);
                    profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
    }
}

taskSnapshot.getDownloadUrl() method not working comes up with red line under it

A: Edit: see this comment on why the approach in this answer doesn't work:

firebaser here This answer is wrong. While it at first may appear to work (since it compiles) the result of getDownloadUrl().toString() is not a download URL, but a string representation of a Task object. For a better answer, see stackoverflow.com/a/55503926 or the sample in the Firebase documentation.

Original answer below...

In Firebase Storage API version 16.0.1,
the getDownloadUrl() method using taskSnapshot object has changed.
now you can use,
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

to get download url from the firebase storage.

A: I faced the similar error I solved it with this method. Hope it helps
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Task<Uri> task = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                task.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String photoLink = uri.toString();
                        Map userInfo = new HashMap();
                        userInfo.put("profileImageUrl", photoLink);
                        mUserDatabase.updateChildren(userInfo);
                    }
                });
                finish();
                return;
            }
        });

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

                        taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                            @Override
                            public void onComplete(@NonNull Task<Uri> task) {
                                changeProfilePic(String.valueOf(task.getResult()));//gives image or file string url
                            }
                        });

try this code will work for sure

A: To get imageUrl path from storage use this code:
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        if (taskSnapshot.getMetadata() != null) {
            if (taskSnapshot.getMetadata().getReference() != null) {
                Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String imageUrl = uri.toString();
                        //createNewPost(imageUrl);
                    }
                });
            }
        }
    }});

that is all

NOTE: Do not forget initialize StorageReference and UploadTask in your uploadFile method.

A: My Google Firebase Plugins in build.gradle(Module: app):
implementation 'com.firebaseui:firebase-ui-database:3.3.1'
implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-database:16.0.1'
implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.0.1'

build.gradle(Project):
 classpath 'com.google.gms:google-services:3.2.1'

My upload() function and fetching uploaded data from Firebase storage :
private void upload() {
    if (filePath!=null) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        final StorageReference ref = storageReference.child(new StringBuilder("images/").append(UUID.randomUUID().toString()).toString());
        uploadTask = ref.putFile(filePath);

        Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()) {
                    throw task.getException();
                }

                return ref.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    progressDialog.dismiss();
                    // Continue with the task to get the download URL
                    saveUrlToCategory(downloadUri.toString(),categoryIdSelect);
                } else {
                    Toast.makeText(UploadWallpaper.this, "Fail UPLOAD", Toast.LENGTH_SHORT).show();
                }
            }
        }).addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                progressDialog.setMessage("Uploaded: ");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                progressDialog.dismiss();
                Toast.makeText(UploadWallpaper.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

FOR THOSE WHO ARE USING LATEST FIREBASE VERSION taskSnapshot.getDownloadUrl() method is DEPRECATED or OBSOLETE !!

A: I'm using Firebase Storage API version 16.0.5 and the task has to be referenced as
 someTask.getResult().getMetadata().getReference().getDownloadUrl().toString();

hope this helps!

A: Try Using this it will download the image from FireBase storage
FireBase Libraries versions 16.0.1
Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
      @Override
      public void onSuccess(Uri uri) {
             String photoStringLink = uri.toString();
      }
});

A: taskSnapshot.**getDownloadUrl**().toString(); //deprecated and removed

use below code for downloading Url
final StorageReference profileImageRef= FirebaseStorage.getInstance().getReference("profilepics/" + "abc_10123" + ".jpg");

profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
        {
            @Override
            public void onSuccess(Uri downloadUrl)
            {
               //do something with downloadurl
            }
        });

A: You wont get the download url of image now using
profileImageUrl = taskSnapshot.**getDownloadUrl**().toString();

this method is deprecated.
Instead you can use the below method
    uniqueId = UUID.randomUUID().toString();
    ur_firebase_reference = storageReference.child("user_photos/" + uniqueId);

    Uri file = Uri.fromFile(new File(mphotofile.getAbsolutePath()));
    UploadTask uploadTask = ur_firebase_reference.putFile(file);

    Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
        @Override
        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
            if (!task.isSuccessful()) {
                throw task.getException();
            }

            // Continue with the task to get the download URL
            return ur_firebase_reference.getDownloadUrl();
        }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                Uri downloadUri = task.getResult();
                System.out.println("Upload " + downloadUri);
                Toast.makeText(mActivity, "Successfully uploaded", Toast.LENGTH_SHORT).show();
                if (downloadUri != null) {

                    String photoStringLink = downloadUri.toString(); //YOU WILL GET THE DOWNLOAD URL HERE !!!!
                    System.out.println("Upload " + photoStringLink);

                }

            } else {
                // Handle failures
                // ...
            }
        }
    });

A: //upload button onClick
public void uploadImage(View view){
    openImage()
}

private Uri imageUri;

ProgressDialog pd;

//Call open Image from any onClick Listener
private void openImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent,IMAGE_REQUEST);
}

private void uploadImage(){
    pd = new ProgressDialog(mContext);
    pd.setMessage("Uploading...");
    pd.show();

    if (imageUri != null){
        final StorageReference fileReference = storageReference.child(userID
                + "."+"jpg");

        // Get the data from an ImageView as bytes
        _profilePicture.setDrawingCacheEnabled(true);
        _profilePicture.buildDrawingCache();

        //Bitmap bitmap = ((BitmapDrawable) _profilePicture.getDrawable()).getBitmap();

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

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] data = baos.toByteArray();

        UploadTask uploadTask = fileReference.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
                pd.dismiss();
                Log.e("Data Upload: ", "Failled");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
                // ...
                Log.e("Data Upload: ", "success");
                Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String downloadLink = uri.toString();
                        Log.e("download url : ", downloadLink);
                    }
                });

                pd.dismiss();

            }
        });

    }else {
        Toast.makeText(getApplicationContext(),"No Image Selected", Toast.LENGTH_SHORT).show();
    }
}

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

    Bitmap bitmap = null;
    if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
        imageUri = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
            _profilePicture1.setImageBitmap(bitmap);
            _profilePicture1.setDrawingCacheEnabled(true);
            _profilePicture1.buildDrawingCache();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (uploadTask != null && uploadTask.isInProgress()){
            Toast.makeText(mContext,"Upload in Progress!", Toast.LENGTH_SHORT).show();
        }
        else {
            try{
                uploadImage();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

A: for latest version try
profileImageUrl = taskSnapshot.getStorage().getDownloadUrl().toString();

A: Try using this:
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

A: Only that...
taskSnapshot.getStorage().getDownloadUrl();
Task<Uri> result = taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
   @Override
   public void onSuccess(Uri uri) {
       String photoStringLink = uri.toString();
       mDatavaseRef.push().setValue(photoStringLink);
   }
});

A: FirebaseStorage Library version 19.0.1 works with
String download_image_path = task.getResult().getUploadSessionUri().toString();

A: //firebase database
implementation 'com.google.firebase:firebase-database:15.0.0'
//firebase storage
implementation 'com.google.firebase:firebase-storage:15.0.0'

.getDownloadUrl() method is removed from later versions , i have changed it to 15.0.0 and works perfectly fine.You can find these in build.gradle(module:app)

A: This will work:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String photoStringLink = uri.toString();
                        Log.i("urlimage", photoStringLink);
                    }
                });
            }
        });

A: Try this:
Uri download_uri ;

final Map<String, String> userData = new HashMap<>();
    if (task != null) {
       //download_uri = task.getResult().getDownloadUrl();
      download_uri = task.getResult().getUploadSessionUri();
    }
    else {
        download_uri= imageUri;
    }

userData.put("Image", download_uri.toString());
userData.put("name",username);
userData.put("category",category);
userData.put("status",status);

A: this is help help me with the last dependencies in 04/2020
     // Get a reference to store file at chat_photos/<FILENAME>
     final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
     photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //When the image has successfully uploaded, get its downloadURL
                        photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                Uri dlUri = uri;
                                FriendlyMessage friendlyMessage = new
                                  FriendlyMessage(null, mUsername, dlUri.toString());

A: Use Firebase storage version 15.0.0.
Uri downloadUrl=taskSnapshot.getDownloadUrl().toString();

A: you can also use Picasso dependencies . its easy to use for uploading image in firebase.
ActivityFile:
 Picasso.get().load(uriImage).into(ImageUri);

app-gradle:
com.squareup.picasso:picasso:2.71828

A: This will Solve Your Problem....
if(uploadTask.isSuccessfull()){
Task<Uri> uriTask=uploadTask.getResult().getStorage().getDownloadUrl();                                               while(!uriTask.isSuccessful());
Uri downloadUri=uriTask.getResult();
final String download_url=downloadUri.toString();
}

A:  private void uploadImageTask() {
    Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/Pictures/OnShot.jpg"));
    StorageReference storageReference = this.storageReference.child("images/" + UUID.randomUUID().toString());
    storageReference.putFile(uri)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                        @Override
                        public void onComplete(@NonNull Task<Uri> task) {
                            Log.d(TAG, "Download URL: " + String.valueOf(task.getResult()));
                        }
                    });
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                    // ...
                }
            });
}

A: I still having this error. What might be wrong? I already changed the permissions, and users to anonymous.

A: For Java Code
String downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();

For Kotlin
val downloadUrl = taskSnapshot.getMetadata()?.getReference()?.getDownloadUrl()?.toString()

A: there is nothing wrong with the depencies. You just have to downgrade your firebase depencies. This is because it hasnt been updated yet..


text:
Q: HTMLCollection not working properly for created elements I populate a section of my HTML with cells.
Then I use getElementsByClassName to get a list of all my cerated cells.
My goal is to access elements of these cells through that list BUT when I try to get an element from HTMLCollection it returns undefined (the cells are all created without a problem and have all the features).
Strange is that console.log(cells) works well, I can see in the chrome console each of my created cells listed BUT as soon as I try to access it, it returns undefined and console.log(cells.length) returns 0.

let Uwidth = document.documentElement.clientWidth;
let Uhight = document.documentElement.clientHeight;
let maxGridLen = Math.floor(Uwidth * (15 / 700))
let maxGridHight = Math.floor(Uhight * (1 / 60))
let grid = document.getElementsByClassName("actualGrid")[0]
let cells = document.getElementsByClassName('cell')

window.addEventListener('load', populate)

function populate() {
  let column = 0
  let row = 0
  for (let i = 0; i < maxGridLen * maxGridHight; i++) {
    createCell(column, row)
    column++
    if (column === maxGridLen) {
      row++
      column = 0
    }
  }
}

function createCell(column, row) {
  const cell = document.createElement("div")
  cell.classList.add("cell")
  cell.setAttribute("data-column", `${column}`)
  cell.setAttribute("data-row", `${row}`)
  cell.setAttribute("data-status", "dead")
  cell.setAttribute("onclick", "convertCell(this)")
  grid.appendChild(cell)
}

I have tried with no success waiting DOM loading, copying HTMLCollection (returns an empty array) and using querySelectorAll("cell")/querySelectorAll(".cell")
Please help I am desperate :'(

A: You've probably linked javascript file with html in head tag, like so:
<html>
  <head>
     <script src="script.js">
  </head>
</html>

The problem with this access is that all your javaScript is loaded and executed before html is rendered, therefore that causes all html elements to be undefined (since they still don't exist). In order to avoid that problem you have few options:

*

*Use existing way to link the script file, but the inside of script file should be like so:
  document.addEventListener('DOMContentLoaded', () => {
    // all of your functions and initialization of html elements goes in here
  });

*Load script file asynchronously:
 <html>
   <head>
      <script src="script.js" async>
   </head>
 </html>

*Defer loading script file:
 <html>
   <head>
      <script src="script.js" defer>
   </head>
 </html>

*Link script file after all html elements:
 <html>
   <head>

   </head>
   <body>
   <!-- content -->
   <script src="script.js">
   </body>
 </html>

A: Make sure your JavaScript is located after the elements you are trying to interact with, otherwise they will not be available by the time your script tries to execute. It's easiest if you keep your scripts at the bottom of any page you might create, otherwise you are asking for something that does not yet exist.

A: I ended up putting cells = document.getElementsByClassName('cell') in my populate() function, I still don't know why console.log(cells) was working but now at least my code is stable.
And for those wondering I did have my script at the end of the body...
let Uwidth = document.documentElement.clientWidth;
let Uhight = document.documentElement.clientHeight;
let maxGridLen = Math.floor(Uwidth * (15 / 700))
let maxGridHight = Math.floor(Uhight * (1 / 60))
let grid = document.getElementsByClassName("actualGrid")[0]
let cells = document.getElementsByClassName('cell')

window.addEventListener('load', populate)

function populate() {
  let column = 0
  let row = 0
  for (let i = 0; i < maxGridLen * maxGridHight; i++) {
    createCell(column, row)
    column++
    if (column === maxGridLen) {
      row++
      column = 0
    }
  }
  cells = document.getElementsByClassName('cell')
}

function createCell(column, row) {
  const cell = document.createElement("div")
  cell.classList.add("cell")
  cell.setAttribute("data-column", `${column}`)
  cell.setAttribute("data-row", `${row}`)
  cell.setAttribute("data-status", "dead")
  cell.setAttribute("onclick", "convertCell(this)")
  grid.appendChild(cell)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: npm install etherlime fails I am trying to install etherlime on Ubuntu 16.04 and npm 6.5.0:
sudo npm install etherlime

Even if I run the above command with sudo it gives me this error:
npm ERR! code 1
npm ERR! Command failed: /usr/bin/git clone --depth=1 -q -b master git://github.com/LimeChain/solidity-coverage.git /home/username/.npm/_cacache/tmp/git-clone-823333ab
npm ERR! /home/username/.npm/_cacache/tmp/git-clone-823333ab/.git: Permission denied
npm ERR!

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/username/.npm/_logs/2019-01-07T08_00_45_775Z-debug.log

A: I've never used etherlime but you do not need to use sudo when using the npm command. Maybe npm is installed in a wrong way or You have an error due to the permissions of your directory.
Try with this:
sudo chown -R username directory.
I need the error logs to understand what the problem is, but remember to use npm in a sub-directory and not in the user's home directory.
mkdir folderName
cd folderName
npm install etherlime

You can found this answer useful.
Obviously before to try this You have to install etherlime globally (npm install -g etherlime)

A: Try this one
npm i -g etherlime

or refer this link https://www.npmjs.com/package/etherlime


text:
Q: reinitialize system wide environment variable in linux I just want my apache to register some of my predefined environment so that i can retrieve it using getenv function in php. How can i do this? I tried adding /etc/profile.d/foo.sh with export FOO=/bar/baz using root and restarted apache.

A: Environment variables are inherited by processes in Unix. The files in /etc/profile.d are only executed (in the current shell, not in a subshell) when you log in. Just changing the value there and then restarting a process will not update the environment.
Possible Fixes:

*

*log out/log in, then start apache

*source the file: # . /etc/profile.d/foo.sh, then restart apache

*source the file in the apache init script

You also need to make sure that /etc/profile.d/ is sourced when Apache is started by init rather than yourself.
The best fix might also depend on the distribution you are using, because they use different schemes for configuration.

A: You can use SetEnv in your config files (/etc/httpd/conf.d/*.conf, .htaccess ...). Additionally you should be able to define them in /etc/sysconfig/httpd (on RPM-based distribs) and export them (note: not tested).
Note: it wouldn't surprise me if some distributions tried quite hard to hide as much as possible, as far as system config is concerned, from a publically accessible service such as Apache. And if they don't, they might start doing this in a future version. Hence I advise you to do this explicitly. If you need to share such a setting between Apache and your shells, you could try sourcing /etc/profile.d/yourprofile.sh from /etc/sysconfig/httpd

A: Apache config files allow you to set environment variables on a per site basis.
So if your web server is serving pages from two logical sites you can have the same environment variable set differently for each site and thus get your PHP to react differently.
See the Apache mod_env for details:

A: If you need env vars for Apache only, what worked for me was editing the /etc/apache2/envvars and restart of Apache. I added these settings:
export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'


text:
Q: Como buscar subcadenas exspecificas en una cadena en Angular 8? Estoy realizando un buscador utilizando Angular 8 y el metodo Apply Filter, la busqueda en general va bien pues como sabemos se hace una comparacion entre el metodo filter y los datos que traemos, en este caso por ejemplo de una tabla. El problema radica en que si yo tengo, por ejemplo, el nombre "Cesar Camacho Diaz" y tecleo en el input "Cesar Camacho" si regresa el resultado al front end, pues si va cocordando lo ingresado con lo que existe en la cadena de alguna fila, ahora bien, si yo llego a poner "Cesar Diaz", por oviedad, ya no me lo trae.
Entonces la pregunta es, como puedo hacer que me traiga "Cesar Camacho Diaz" aun si yo pongo "Cesar Diaz"?
Eh estado dandole vueltas pero no encuentro la manera.
mi codigo HTML es:
<mat-form-field>
                <input matInput autocomplete="off" maxlength="256" (keyup)="applyFilter($event.target.value)">
              </mat-form-field>

            <ng-container matColumnDef="nombre">
              Nombre
               {{element.nombre}}
            </ng-container>

            <ng-container matColumnDef="email">
              Email
               {{element.email}}
            </ng-container>

            <ng-container matColumnDef="rol">
              Rol
               {{element.rol}}
            </ng-container>

            <ng-container matColumnDef="foros">
              Foros Activos

                <mat-form-field>
                <mat-label>Foros</mat-label>
                <mat-select [formControl]="toppings">
                <mat-option *ngFor="let dato of element.optionsForos" [value]="dato.val" disabled hidden>

done
                clear{{dato.label}}

                </mat-option>
              </mat-select>
              </mat-form-field>
            </ng-container>

            <ng-container matColumnDef="editar">
              Editar
              <button *ngIf="element.rol =='Administrador'" style="color:#0046af;font-size: 20px;border: none;background-color:transparent;" (click)="openModalEdit()">
                 edit</button>
                 <button *ngIf="element.rol =='Super Administrador'" style="color:#0046af;font-size: 20px;border: none;background-color:transparent;opacity:0.7;" (click)="openModalEdit()" disabled>
                 edit</button>

            </ng-container>

            <ng-container matColumnDef="eliminar">
              Eliminar
              <button *ngIf = "element.rol == 'Administrador'" style="border: none;background-color: transparent;">
              <ng-template #reactivacion></ng-template></button>
              <button *ngIf = "element.rol == 'Super Administrador'" style="border: none;background-color: transparent;" disabled>
              </button>

            </ng-container>

mi codigo TS es:
  public async obtenerUsuarios(){

    let data;
    this.tablaUsuarios = await this.forosServicio.getUsuarios(data);
    this.tablaUsuarios = this.transfromData(this.tablaUsuarios);
    this.dataSource = new MatTableDataSource<any>(this.tablaUsuarios);

    this.dataSource.filterPredicate = (data: any, filter: string): boolean => {
      console.log(data);
      const dataStr = Object.keys(data).reduce((currentTerm: string, key: string) => {
        return (currentTerm + (data as { [key: string]: any })[key] + '◬');
      }, '').normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();

      const transformedFilter = filter.trim().normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();

      return dataStr.includes(transformedFilter);
    }

    this.dataSource.paginator = this.paginator;
  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

A: Puedes convertir tus cadenas de texto a un arreglo de palabras para facilitar la búsqueda utilizando funciones del Array.prototype como en el siguiente ejemplo
let name = "Cesar Camacho Diaz".split(" ");
let query = "Cesar Diaz".split(" ");

let matches = query.every((item) => name.includes(item));

Aqui la función Array.prototype.every nos dice si todas las palabras que están en el query son parte de el nombre al cual estamos comparando.
Dicho esto podemos decir que dados los siguientes inputs

*

*"Cesar"

*"Camacho"

*"Diaz"

*"Diaz Camacho"

*"Camacho Diaz Cesar"

O cualquier combinación de las primeras tres palabras nos dará como resultado true.

En este ejemplo no tome en cuenta la distinción entre mayúsculas y minúsculas, acentos, ni errores búsqueda


text:
Q: Error while start rails console libIlmImf.so.6: cannot open shared object file I am trying to setup a rails project, after successfully bundle install when I try to run a rails c it gives me following error.
`require': libIlmImf.so.6: cannot open shared object file: No such file or directory - /home/user/.rvm/gems/ruby-2.3.0/gems/rmagick-2.16.0/lib/RMagick2.so (LoadError)

I have installed "rmagick" but still gives me same error.
I have also installed "openexr" as suggested in one of the SO post but didn't work for me.
Any suggestions about how to fix this?

A: I have found the solution, the issue is the package is missing which contain libIlmImf.so.6, I have googled for so long and found package link
Pakage: libopenexr6 which contain libIlmImf.so.6
I have then installed that package sudo apt-get install libopenexr6 so that it solve the problem.
Hope this will help someone else in the future.

A: I ran into the same issue. Installed rmagick and openexr successfully. bundle install completed. I actually saw the file RMagick2.so in the printed path. It turned out that it's a broken ImagicMagic after the system is upgraded. The way I fixed the issue is by reinstalling ImageMagic following the instruction on http://www.imagemagick.org/script/install-source.php. I also reinstall rmagic gem afterward, but I'm not sure if that's necessary.


text:
Q: MailMerge not working on Office 2016 I have one program which uses mailmerge in Word and it works perfectly in office 2007 and tested in 2010. But in office 2016 it throws an error

Code is below
ASSIGN lv_cDocument = fiFile.                 /* chosen from program select */
ASSIGN lv_cDataFile = "C:\a\data.dat".
ASSIGN lv_cMailMergeFile = "C:\a\dataOutput.doc".

MailMerge(lv_cDocument,                      /* Main Document */
          lv_cDataFile,                      /* File that holds all the data */
          lv_cMailMergeFile,                 /* File to hold new mail merge document */
          NO).

DEFINE VARIABLE oWord AS COM-HANDLE NO-UNDO.

CREATE "Word.Application" oWord.
oWord:Documents:Open("C:\a\dataOutput.doc").
oWord:Visible = True.

RELEASE OBJECT oWord.

Any thoughts what is "new" in new office so i can modify my program that it works on all version of MS-Offices?

A: When doing COM, both applications (OrenEdge and Word) should be same "bitness". To be safe, both products should be 32 bit - I'm not 100% sure if 64 bit Word supports Automation interfaces.
The alternative on 11.6 might be the Interop API's (.NET): https://msdn.microsoft.com/de-de/library/microsoft.office.interop.word(v=office.11).aspx

A: The problem was in Word options.
Steps to resolve the auto launch errors:

*

*Open MS Word.

*Click on File > Options.

*In the General section under Start up options, uncheck the "Open e-mail attachments and other uneditable files in reading view" box.

*Close Word and try to export and auto launch your document again. It may take a couple of tried for Word to realize the setting has been changed.

Source

A: Problem for me was although it shows only ms office 2016 is installed and only one version of it. When I looked under start and went to outlook it showed the normal icon for outlook and the another one that said outlook 2016.
So I set up the user profile on the normal outlook, made sure that is open and not the outlook 2016 one and now the mail merge works for me.
Hope this helps someone out.


text:
Q: Printing Query Results in a Table If I had a MySQL table called "info" as described below and I wanted to print out an HTML table as described below, how would I do it?
Fields in MySQL table:
id subject category actions date status

HTML table structure: Two columns, first containing the field "subject", next containing the field "actions," sorted by "actions" descending.  Only showing entries where "category" matches what the user entered as the variable "$find"
Here is where I would start, but I'm not sure where to go next:
$result=mysql_query("SELECT subject, actions FROM info WHERE category='$find' ORDER BY votes DESC")
or die(mysql_error());

if(mysql_num_rows($result)>0){
while($table=mysql_fetch_row($result)){

Thanks in advance,
John

A: Like this:
<?php
$result = mysql_query("SELECT subject, actions FROM info WHERE category='$find' ORDER BY votes DESC") or die(mysql_error());

if(mysql_num_rows($result) > 0): ?>

        Subject
        Actions

    <?php while($row = mysql_fetch_assoc($result)): ?>

        <?php echo $row['subject']; ?>
        <?php echo $row['actions']; ?>

    <?php endwhile; ?>

<?php endif; ?>


text:
Q: How to make it so when the view loads, it displays something based on the value of an NSInteger? I am making a quiz app that displays a saying at the end of the quiz based on the value of the NSInteger myScore. How would I code this? Any help would be helpful 'haha'. Thanks!

A: Use an array that stores your witty remarks, and calculate an array index out of the score. Something like this:
NSArray *wittyNotes = [NSArray arrayWithObjects:
                       NSLocalizedString(@"Foo", nil),          // 0 - 99
                       NSLocalizedString(@"Bar", nil),          // 100 - 199
                       NSLocalizedString(@"Baz", nil),          // 200 - 299
                       NSLocalizedString(@"Over 9000", nil),    // 300 - ...
                       nil];
NSInteger index = myScore / 100;
if (index >= [wittyNotes count]) {
    index = [wittyNotes count] - 1;
}
NSString *wittyNote = [wittyNotes objectAtIndex:index];

Depending on your wishes you could make the myScore-to-index calculation more complicated.


text:
Q: MyGet pre-build script written in PowerShell? My pre-build script originally was a .bat. When I added the functionality to generate the version number, I wrote it in PowerShell (I really don't like batch). So I tried to convert the whole pre-build script into PowerShell but I'm running into difficulties.
## pre-build.ps1
function SetPackageVersion
{
    if(gitversion /output json /showvariable PreReleaseTagWithDash)
    {
       ##myget[buildNumber "$(gitversion /output json /showvariable Major).$(gitversion /output json /showvariable Minor).$(gitversion /output json /showvariable CommitsSinceVersionSource)-$(gitversion /output json /showvariable PreReleaseTagWithDash)"]
    }
    else
    {
       ##myget[buildNumber "$(gitversion /output json /showvariable Major).$(gitversion /output json /showvariable Minor).$(gitversion /output json /showvariable CommitsSinceVersionSource)"]
    }

    GitVersion /updateassemblyinfo true
}

set config=Release

SetPackageVersion

## Package restore
NuGet restore Library\packages.config -OutputDirectory %cd%\packages -NonInteractive

Build "%programfiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe" MakeMeATable.sln /p:Configuration="%config%" /m /v:M /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:false

## Package
mkdir Build
nuget pack "Library\MakeMeATable.csproj" -symbols -o Build -p Configuration=%config% %version%

I get these errors in the MyGet build log (among others)

Build : The term 'Build' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At D:\temp\fcd4ee1\pre-build.ps1:24 char:1
+ Build "%programfiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe" MakeMeATable ...
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (Build:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The term 'Verbosity=Normal' is not recognized as the name  of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At D:\temp\fcd4ee1\pre-build.ps1:24 char:140
+ ... onfig%" /m /v:M /fl /flp:LogFile=msbuild.log;Verbosity=Normal /nr:fal ...
+                                                  ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Verbosity=Normal:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I do not understand why I can't find any good reference about the way to create a PowerShell prebuild script for MyGet? All the examples are written in class batch!

*

*Are there any resources online that I missed ?

*What is the proper (official/most simple) way, in PowerShell, to build and package a library with MyGet?

A: I don't have experience with MyGet, but a can give you some advice on the errors and your code in general.

*

*
Build : The term 'Build' is not recognized as the name of a cmdlet, function, script file, or operable program.

The interpreter doesn't recognize Build as a command. Where is it defined? Is it an alias? Included somewhere? An executable in a different path? Also, your commandline doesn't look like it would be required in the first place. Try replacing it with the call operator (&).

The term 'Verbosity=Normal' is not recognized as the name  of a cmdlet, function, script file, or operable program.

The semicolon in PowerShell has the same meaning as the ampersand in batch: it's the operator for daisy-chaining commands. Because of that PowerShell tries to execute Verbosity=Normal as a new statement instead of handling it as part of the argument for the parameter /flp. Put the parameter in quotes to avoid this.
Also, you cannot use CMD builtin variables (%cd%) or batch variable syntax in general (%var%) in PowerShell. The equivalent for %cd% is $pwd (more specifically $pwd.Path), and the general syntax for variables is $var or ${var} (the latter must be used if the variable name contains non-word characters like spaces, parentheses, etc.).
Change the statement to something like this:
& "${ProgramFiles(x86)}\MSBuild\14.0\Bin\MSBuild.exe" MakeMeATable.sln "/p:Configuration=$config" /m /v:M /fl "/flp:LogFile=msbuild.log;Verbosity=Normal" /nr:false

and it should work. Better yet, use splatting for passing the arguments:
$params = 'MakeMeATable.sln', "/p:Configuration=$config", '/m', '/v:M',
          '/fl', '/flp:LogFile=msbuild.log;Verbosity=Normal', '/nr:false'
& "${ProgramFiles(x86)}\MSBuild\14.0\Bin\MSBuild.exe" @params

*Variable assignments in PowerShell and batch are different. While set config=Release won't produce an error (because set is a builtin alias for the cmdlet Set-Variable) it doesn't do what you expect. Instead of defining a variable config with the value Release it defines a variable config=Release with an empty value.
Change
set config=Release

to
$config = 'Release'


text:
Q: How to change n consecutive elements in a list without creating a new one? Basically, I have to use a function to modify a list in a way where I change n-consecutive elements. The problem is, however, that I cannot return the list (the function can't return anything really), so to my understanding, I cannot create a new list, because that will not change the list that I got through my function argument.
I've done it with a while loop like this:
while i < length:
     my_list[index+i] = element
     i += 1

I was wondering if there are any other solutions to this, similar to a list comprehension or something like that. I'm new to Python so this is purely for exploration purposes.

A: You could use a slice assignment for this:
my_list[index:index + length] = (e for _ in range(length)) # or (e,) * length

The line above will replace the elements of my_list at positions within the [index, index + length) interval with elements from the iterable at the right hand side of the assignment. Note that the length of the slice and the length of the iterable must match. Otherwise, some of the elements will be removed (if the iterable is shorter) or more elements will be added (in case the iterable is longer).
Example:
In [14]: my_list = [1, 2, 3, 4, 5, 6]

In [15]: index, length, element = 1, 3, 0

In [16]: my_list[index:index + length] = (element for _ in range(length))

In [17]: my_list
Out[17]: [1, 0, 0, 0, 5, 6]


text:
Q: How do I define my pool of Actions in such a way that they depend on variables in GOAP? I'm attempting to implement GOAP in my game. The game is a simulation-type game that would not only benefit from GOAP, but is almost essentially a requirement based on the scope of what an agent can do.
I have the following code. There's no planner in here, just the definitions of Actions, State etc
#include <vector>
#include <string>
#include <unordered_map>

class Condition
{
public:

    bool operator()(const int value) const
    {
        return m_min <= value && value <= m_max;
    }

    enum class OP : std::uint8_t
    {
        EE, LT, GT, LE, GE
    };

    Condition(const int min, const int max, const OP op)
    :
        m_op(op),
        m_min(min),
        m_max(max)
    {}

    static Condition CreateEE(const int goal)
    {
        return Condition(goal, goal, OP::EE);
    }

    static Condition CreateGT(const int goal)
    {
        return Condition(goal+1, std::numeric_limits<int>::max(), OP::GT);
    }

    static Condition CreateLT(const int goal)
    {
        return Condition(std::numeric_limits<int>::min(), goal-1, OP::LT);
    }

    static Condition CreateGE(const int goal)
    {
        return Condition(goal, std::numeric_limits<int>::max(), OP::GT);
    }

    static Condition CreateLE(const int goal)
    {
        return Condition(std::numeric_limits<int>::min(), goal, OP::LT);
    }

private:

    OP m_op;
    int m_min;
    int m_max;
};

class Effect
{
public:

    enum class OP : std::uint8_t
    {
        ADD, SUB, MUL, DIV, EQ
    };

    Effect(OP op, int value)
    :
        m_op(op),
        m_value(value)
    {

    }

protected:
    OP m_op;
    int m_value;
};

class Action
{
public:
    void AddPrereq(const std::string& name, Condition value)
    {
        m_prereqs.emplace_back(name,value);
    }

    void AddEffect(const std::string& name, Effect effect)
    {
        m_effects.emplace_back(name,effect);
    }

    void SetCost(const float cost)
    {
        m_cost = cost;
    }

private:

    float m_cost;

    std::vector<std::pair<std::string,Condition>> m_prereqs;
    std::vector<std::pair<std::string,Effect>> m_effects;
};

class WorldState
{
public:

    void AddFact(const std::string& name, const int value)
    {
        m_facts[name] = value;
    }

private:

    std::unordered_map<std::string,int> m_facts;
};

class GoalState
{
public:

    void AddCondition(const std::string& name, const Condition condition)
    {
        m_conditions.emplace_back(name, condition);
    }

private:
    std::vector<std::pair<std::string,Condition>> m_conditions;
};

int main()
{
    Action goTo;
    goTo.AddEffect("isAtPosition", Effect(Effect::OP::EQ, 1));

    Action pickUp;
    pickUp.AddPrereq("isAtPosition", Condition::CreateEE(1));
    pickUp.AddEffect("itemInPossession", Effect(Effect::OP::EQ, 1));

    Action drop;
    drop.AddPrereq("itemInPossession", Condition::CreateEE(1));
    drop.AddEffect("itemAtPosition", Effect(Effect::OP::EQ, 1));

    WorldState ws;
    ws.AddFact("itemAtPosition", 0);

    GoalState gs;
    gs.AddCondition("itemAtPosition", Condition::CreateGE(1));

    return 0;
}

For now I'm just using boolean values, because for my test-case, it's about the agent moving to a position, picking up an item, and moving it to another position. Later on, a goal might be to move n items or something.
Actions would be:

*

*Goto (puts agent in position)

*PickUp (puts item in possession)

*Goto (puts agent in position)

*Drop (puts item in location) Goal Met!

But how do I use the Goto action here twice? It's effect is the same, setting the "isAtPosition" variable. Would I need to create a new state variable for "isAtItemPosition" vs "isAtDestinationPosition"?
Because that seems like I would be effectively crafting specific Actions for each possible Goal, with the effect of me determining all the possible sequences of Actions.
How do I encode the state information in such a way that the same actions from the pool can be applied at different stages, having a different effect? (Goto the item position vs goto the destination position).

A: Yes, if you only have boolean values, then you need separate action for each location.
If you can, I would consider using a slightly more powerful representation, such as STRIPS, or PDDL. That will make it a lot easier to describe somewhat more complex scenarios, and it will have the added benefit that you can use off-the-shelf solvers to develop plans for your agents.
In PDDL you could have an action (move ?agent ?from ?to), with the precondition that the agent is at location ?from and the effect that they will be at location ?to after the action has been performed. For picking up an object you could have (pick-up ?agent ?object) with the precodition that both the agent and the object are at the same location. This is far more generic than fixed boolean actions, and will allow later extensions more easily.


text:
Q: Exponent of a direct product of groups Prove that if the group $G=\prod_{i=1}^nH_i$, where each $H_i$ is a finite group, then the exponent of $G$ which is
$\exp(G)=\min\{n \in \mathbb{N}:g^n=e, \forall g \in G\}$ is equal with $\operatorname{lcm}(\exp(H_1),\ldots,\exp(H_n))=M$
I proved that $\exp(G) \leqslant M$
Can someone help me with the other direction ?
Thank you in advance!

A: Since this problem is a little subtler than I (and others) assumed at first glance, let me provide a detailed answer as penance.
Suppose that $p$ is a prime and $p^a$ is the largest power of $p$ dividing $M$.  I claim there is an element of $G$ with (positive) exponent divisible by $p^a$.  From this it follows that $p^a$ divides the exponent of $G$.  Applying this to all primes $p$ dividing $M$, we see that $M$ must divide the exponent of $G$; in particular, the exponent of $G$ is at least $M$.
Since $p^a$ divides $M$ and $M$ is the lcm of some numbers, $p^a$ divides one of these numbers, say the exponent of $H_i$.  Then there is some element $h \in H_i$ whose exponent is divisible by $p^a$.  It follows that $(1, \ldots, 1, h, 1, \ldots, 1) \in G$ has exponent divisible by $p^a$, so $G$ itself has exponent divisible by $p^a$.

A: You show the other direction by identifying an element of the product which has order M.  Hint: Find a tuple that maximizes each coordinate.


text:
Q: How to run a fortran program using ifort compiler? Recently, Intel released Ifort compiler for free, for everyone to use. As I have been using gfrotran for quite some time, I decided to install it. I installed the two packages that intel says they are needed (using Windows 10). In the console, as ifort was not recognised (I tried to set up the path to the executable ifort.exe to no avail), i decided to use intel one api tool console.
In that console, ifort is recognised, and you can acces help options and the likes. However, when I try to run a simple test program, it runs with fatal error LNK1104, where imageHlp.lib is missing.
I also tried to run it form the VS17 interface, but it was futile.
I don't know what I am doing wrong, and Intel support forums are in permanent "we are experiencing network issues".
I just want to compile a text file to an executable, no libraries involved, nothing fancy.

A: I am not seeing any issue with the Intel forums. Make sure you have configured VS2019 for the "C++ Desktop Workload" - see https://software.intel.com/content/www/us/en/develop/articles/installing-microsoft-visual-studio-2019-for-use-with-intel-compilers.html  Or for VS2017, https://software.intel.com/en-us/articles/intel-c-fortran-compilers-for-windows-integration-into-microsoft-visual-studio-2017
After you have installed the oneAPI HPC Toolkit, there is a shortcut created Intel oneAPI > Intel oneAPI command prompt. Use this to establish the environment. But you will probably find that the default directory with that shortcut is C:\Program Files (x86)\Intel\oneAPI, which is unusable for compilation, so "cd" to a writable directory. (I like to copy that shortcut to my desktop and modify the "Start in" location.)


text:
Q: How do I change the default format for an date time value copied from SSMS to Excel I often copy the results of a query from Sql Server Management Studio to Excel because I can fiddle with sorting and filtering of results faster using Excel's built in tools than by changing the query I'm running in SSMS.  To do this I select everything in the SSMS results grid and just paste it into Excel.  For the most part it works correctly; the one exception is that the formatting picked for date time columns isn't suitable and needs to be changed manually afterwards.
My date time values look like:  11/2/2012  3:34:39 PM
Excel defaults to showing 34:39.0 (MM:SS.S)
I want a format that shows the full date and time.  I do this by selecting the date time columns, selecting format cells from the context menu and picking one of the formats that show both available under the Number-Date or Number-Time options (normally 3/14/01 13:30; the last option under time).
I'd like to change the default format Excel picks when encountering a time value to that so I don't need to fix it up every time.

A: I develop SSMSBoost add-in for SSMS and I have implemented "Export ResultsGrid to Excel" function, that simply scripts ResultsGrid contents as XML Spreadsheet format. (Right click the grid->Script as -> XML Spreadsheet). (Add-in can be used for free.)
Data is exported to Excel with preserved datatypes, so Date, Strings and Numbers remain so and can be formatted in excel. This might already help, as far as excel will apply default formatting on date and time and it will be taken from regional settings (at least according to excel manual).
Here is description how default formatting is applied and where it can be changed:
http://office.microsoft.com/en-us/excel-help/change-the-default-date-time-number-or-measurement-format-HA010351415.aspx#BM2


text:
Q: aggregating values in dictionary I have a deep dictionary like this:
myDict = { '123456': {
              '348adbd39r' : {
                    'LONDON': {
                          'c_name': 'abc',
                          'acct': '84720'
                          },
                    'PARIS': {
                          'c_name': 'xyz',
                          'acct': '73642'
                          }
                     },

              '2862aef3' : {
                    'NYC': {
                          'c_name': 'hhdls3',
                          'acct': '92742'
                          }
                     },

              '82gfg24' : {
                    'NYC': {
                          'c_name': 'hquer',
                          'acct': '34567'
                          },
                    'PARIS': {
                          'c_name': 'ljad',
                          'acct': '93742'
                          }
                     }
        }

I want to 'aggregate' it based on the city names. The output should look like below:
outDict = {
            'LONDON': {
                'c_name': ['abc'],
                'acct': ['84720']
             },
            'PARIS': {
                'c_name': ['xyz', 'ljad'],
                'acct': ['73642', '93742']
             },
            'NYC': {
                'c_name': ['hhdls3', 'hquer'],
                'acct': ['73642', '34567']
             }
         }

This is what I did:
cust_fields = ['c_name', 'acct']
field_dict = {field: [] for field in cust_fields}
aggregated_dict = {}

city_names = ['LONDON', 'PARIS', 'NYC']
for city in city_names:
   aggregated_dict[city] = field_dict

for id, an_dict in myDict.iteritems():
    for alphaNum, city_dict in an_dict.iteritems():
        for city, acct_dict in city_dict.iteritems():
            for field, val in acct_dict.iteritems():
                aggregated_dict[city][field].append(val)

But, the above is updating the field-values for all the cities...rather than just the particular city it is working on. Not sure where the logic is wrong. Any help is appreciated (either correct where my mistake is or any new logic...).
Thanks!

A: The problem you have is you are assigning field_dict to the value of aggregated_dict[city] in your loop over city_names, which is simply assigning the same dictionary to each city.  And when you update any reference (for any city) all references are updated.
An easy fix for this is to change
for city in city_names:
   aggregated_dict[city] = field_dict

To:
for city in city_names:
   aggregated_dict[city] = {field: [] for field in cust_fields}

I would also look at collections.defaultdict for this type of aggregation.
from collections import defaultdict

collected = defaultdict(lambda: defaultdict(list))

for _, city_records in myDict['123456'].items():
    for city_name, records in city_records.items():
        for record_name, record_value in records.items():
            collected[city_name][record_name].append(record_value)

for city_name, records in collected.items():
    print city_name
    print dict(records)

A: for key,val in myDict.items():
    for key1,val1 in val.items():
        for key2,val2 in val1.items():
            d = final_dict[key2] if key2 in final_dict else defaultdict(list)
            for k,v in val2.items():
                d[k].append(v)
            final_dict[key2] = d

A: You can use recursion:
from collections import defaultdict
d1 = defaultdict(dict)
def aggregate(d):
   for a, b in d.items():
      if a in ['LONDON', 'PARIS', 'NYC']:
         global d1
         if a not in d1:

             d1[a] = {}

             d1[a]['c_name'] = [b['c_name']]
             d1[a]['acct'] = [b['acct']]
          else:
             d1[a]['c_name'].append([b['c_name']])
             d1[a]['acct'].append(b['acct'])
        else:
           aggregate(b)

aggregate(myDict)
print(dict(d1))

Output:
{'PARIS': {'acct': ['73642', '93742'], 'c_name': ['xyz', ['ljad']]}, 'NYC': {'acct': ['92742', '34567'], 'c_name': ['hhdls3', ['hquer']]}, 'LONDON': {'acct': ['84720'], 'c_name': ['abc']}}


text:
Q: Does calling a method on a value type result in boxing in .NET? I was just participating in Stack Overflow question Is everything in .NET an object?.
And one poster (in comments of accepted answer) seemed to think that performing a method call on a value type resulted in boxing. He pointed me to Boxing and Unboxing (C# Programming Guide) which doesn't exactly specify the use case we're describing.
I'm not one to trust a single source, so I just wanted to get further feedback on the question. My intuition is that there is no boxing but my intuition does suck. :D
To further elaborate:
The example I used was:
int x = 5;
string s = x.ToString(); // Boxing??

Boxing does not occur if the struct in question overrides the method inherited from the object as the accepted answer here states.
However if the struct doesn't override the method, a "constrain" CIL command is executed prior to a callvirt. According to the documentation, OpCodes.Constrained Field, this results in boxing:

If thisType is a value type and
  thisType does not implement method
  then ptr is dereferenced, boxed, and
  passed as the 'this' pointer to the
  callvirt method instruction.

A: @ggf31316

"I believe that calling ToString,
  Equals and Gethashcode result in
  boxing if the structure does not
  override the methods."

I have checked ToString for you. Int32 does override ToString, so I made a struct that doesn't. I used .NET Reflector to ensure that the struct wasn't somehow magically overriding ToString(), and it wasn't.
So the code was like this:
using System;

namespace ConsoleApplication29
{
    class Program
    {
        static void Main(string[] args)
        {
            MyStruct ms = new MyStruct(5);
            string s = ms.ToString();
            Console.WriteLine(s);
        }
    }

    struct MyStruct
    {
        private int m_SomeInt;

        public MyStruct(int someInt)
        {
            m_SomeInt = someInt;
        }

        public int SomeInt
        {
            get
            {
                return m_SomeInt;
            }
        }
    }
}

And the MSIL (via ILDASM) for the Main method is this:
  IL_0000:  ldloca.s   ms
  IL_0002:  ldc.i4.5
  IL_0003:  call       instance void ConsoleApplication29.MyStruct::.ctor(int32)
  IL_0008:  ldloca.s   ms
  IL_000a:  constrained. ConsoleApplication29.MyStruct
  IL_0010:  callvirt   instance string [mscorlib]System.Object::ToString()
  IL_0015:  stloc.1
  IL_0016:  ldloc.1
  IL_0017:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_001c:  ret

Now, despite no boxing call taking place, if you check the documentation about a constrained + a call virt, you will find it states that boxing DOES take place. oOo
Quote:

If thisType is a value type and
  thisType does not implement method
  then ptr is dereferenced, boxed, and
  passed as the 'this' pointer to the
  callvirt  method instruction.

A: I believe that calling ToString, Equals and Gethashcode result in boxing if the structure does not override the methods.

A: Here's the IL for your code:
L_0001: ldc.i4.5      // get a 5 on the stack
L_0002: stloc.0       // store into x
L_0003: ldloca.s x    // get the address of x on the stack
L_0005: call instance string [mscorlib]System.Int32::ToString()  // ToString
L_000a: stloc.1       // store in s

So the answer in this case is no.

A: In the case you have given the answer is no, as plinth pointed out.
However, it will if you call a method through an interface pointer.
Consider the code:
interface IZot
{
    int F();
}

struct Zot : IZot
{
    public int F()
    {
        return 123;
    }
}

Then
Zot z = new Zot();
z.F();

Does not result in boxing:
.locals init (
    [0] valuetype ConsoleApplication1.Zot z)
L_0000: nop
L_0001: ldloca.s z
L_0003: initobj ConsoleApplication1.Zot
L_0009: ldloca.s z
L_000b: call instance int32 ConsoleApplication1.Zot::F()
L_0010: pop
L_0011: ret

However, this does:
IZot z = new Zot();
z.F();

   .locals init (
        [0] class ConsoleApplication1.IZot z,
        [1] valuetype ConsoleApplication1.Zot CS$0$0000)
    L_0000: nop
    L_0001: ldloca.s CS$0$0000
    L_0003: initobj ConsoleApplication1.Zot
    L_0009: ldloc.1
    L_000a: box ConsoleApplication1.Zot
    L_000f: stloc.0
    L_0010: ldloc.0
    L_0011: callvirt instance int32 ConsoleApplication1.IZot::F()
    L_0016: pop


text:
Q: How can I subset for a row that has a target value within a group, and if there are none, subset for a different row within the same group? I am trying to subset a grouped dataframe so that I end up with one row for each group. For each group, I would like to subset a row if it has a specific value, but if no such row exists, then I would subset an alternative row.
The data is grouped by year and season, and I would like to subset a row with Month == 2 from the Season 1 group, a row with Month == 4 from Season 2, a row with Month == 8 from Season 3, and a row with Month == 10 from Season 4.
If there is no row with the requirements, then the row in the season group with the largest value would be subset. For example, of rows 4 and 5, row 4 would be subset.
Year Season Month value
2012 1      1     3.4
2012 1      2     6.1
2012 1      3     9.0
2012 2      5     4.4
2012 2      6     1.2
2012 3      8     4.9
2012 4      10    2.7
2013 1      3     8.3
2013 1      3     2.4
2013 2      4     7.0
2013 3      7     12.1
2013 3      8     5.7
2013 4      10    6.3
2013 4      11    3.3

The desired output is:
Year Season Month value
2012 1      2     6.1
2012 2      5     4.4
2012 3      8     4.9
2012 4      10    2.7
2013 1      3     8.3
2013 2      4     7.0
2013 3      8     5.7
2013 4      10    6.3

I've tried the following code but couldn't figure out how to include my alternative requirement in the same bit of code (which I think would need an if and else if?)
df %>%
  group_by(Year, Season) %>%
  slice(which(Month == 2 | Month == 4 | Month == 8 | Month == 10))
  #slice(which.max(value)) #selects row with largest value in each group

A: Check this solution:
data %>%
  mutate(cond = case_when(
    Season == 1 & Month == 2 ~ 1,
    Season == 2 & Month == 4 ~ 1,
    Season == 3 & Month == 8 ~ 1,
    Season == 4 & Month == 10 ~ 1,
    TRUE ~ 0
  )) %>%
  group_by(Year, Season) %>%
  arrange(desc(cond), desc(Value)) %>%
  slice(1) %>%
  ungroup()


text:
Q: powershell convert array of hastables into csv Have done googling but have not found suitable answer
I have
     $a = @(
           @{"name"="a"; "value"="1"},
           @{"name"="b"; "value"="2"}
       )

    Foreach($x in $a){
          $obj = New-object psobject
          Foreach($key in $x.keys) {
                 $obj ¦ add-member -membertype NoteProperty -name $key -value $x[$key]
           }
           $obj ¦ export-cvs test.csv
     }

I get only last line in cab. I want all the lines

A: It's truth that Export-Csv won't append (< v3), but I do not think ConvertTo-Csv will solve the problem... In the end you will get file with headers repeated for every object in your array. I would suggest one of two things:

*

*move Export-Csv outside foreach {} (need to put it in subexpression though, because it won't be possible to pipe it by default)

*use Foreach-Object instead and get same results

I would also suggest to use New-Object PSObject -Property parameter instead of adding members later: because you use hashtable as a base you are half way there, see attached code samples:
# Using $( foreach ($x in $a) {} ) | Export-Csv
$(Foreach($x in $a){
    New-object psobject -Property $x
}) | Export-Csv test.csv

# Using $a | Foreach-Object {} | Export-Csv
$a | ForEach-Object {
    New-Object PSObject -Property $_
} | Export-Csv test.csv

A: You're overwriting the csv file each time.  Try using convertTo-CSV each time (instead of export-csv) and appending that to a file.

A: 2022 update

*

*You always need to use the -append parameter if you are iterating through a collection

*using powershell 7.2 and later you don`t need to parse the hashtable again, it matches the repeating properties and writes to csv.

so this will work automatically
$hashtable=@()
$hashtable += $pscustomobject

$hashtable | export-csv


text:
Q: An exception occured while executing "DRILL Through" query While executing "Drill Through" query by using ajax post am getting the below exception(Error.). I'm using the msmdpump.dll and SQL server 2012. I have attached code snippet below. Using simple "DrillThrogh" query in SSAS 2012 getting the below exception (SSAS2012_Error)
<script>
var query = "DRILLTHROUGH Select([Date].[Fiscal].[Fiscal Year].&[2002],[Measures].[Reseller Sales Amount]) on 0 From [Adventure Works]RETURN[Reseller Sales].[Reseller Sales Amount],[Reseller Sales].[Reseller Order Quantity],[Reseller Sales].[Reseller Extended Amount],[Reseller Sales].[Reseller Tax Amount],[Reseller Sales].[Reseller Freight Cost],[Reseller Sales].[Discount Amount],[Reseller Sales].[Reseller Total Product Cost],[Reseller Sales].[Reseller Standard Product Cost],[$Date].[Date]";
var data = "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\"> <Header></Header> <Body> <Execute xmlns=\"urn:schemas-microsoft-com:xml-analysis\"> <Command> <Statement> " + query + " </Statement> </Command> <Properties> <PropertyList> <Catalog>Adventure Works DW</Catalog></PropertyList> </Properties></Execute> </Body> </Envelope>";

$.ajax({
    type: "POST",
    url: "http://localhost/Olap/msmdpump.dll",
    contentType: "text/xml",
    dataType: "xml",
    data: data,
    complete: ej.proxy(function (onComplete) {

    }, this),
    success: $.proxy(onSuccess, this),
    error: $.proxy(function (msg, textStatus, errorThrown) {

    }, this)
});

function onSuccess(e) {

}
</script>

A: Does the following section need to be standard mdx? - it isn't standard:
Select([Date].[Fiscal].[Fiscal Year].&[2002],[Measures].[Reseller Sales Amount]) on 0 From [Adventure Works]


text:
Q: Relationships between roots: How to solve a polynomial with a variable second coefficient? I'm trying to find all of the the roots to the following polynomial with a variable second coefficient:
$$P(x)=4x^3-px^2+5x+6$$
All of the roots are rational, and $p$ is too. It is also given that the difference of 2 roots equals the third, e.g. $r-s=t$. I would like to solve for the roots using relationships between roots & the rational roots theorem.
I know from relationships between roots (Vieta's formula) that $p/4=r+s+t$, which can be reduced to $p/4=2r$ per the previous equation, and therefore $p/8$ is a root. However, I'm not sure where to go from here-- performing the substitution with the other coefficients does not seem to yield anything that lets me solve for a root or $p$. For example, we know from the coefficient of $x^0$ that
$$5/4=rs+rt+st=rs+(r+s)(r-s)$$
but there is no obvious substitution that can be made here that would put things in terms of one variable.
How do I solve for the roots and $p$ using relationships between roots and the rational roots theorem here? Thanks!

A: Since $\frac p8$ is a root, we can perform long division on the polynomial and obtain
$$4x^3-px^2+5x+6=\left(x-\frac p8\right)\left(4x^2-\frac p2x+5-\frac{p^2}{16}\right)$$
where
$$\left(5-\frac{p^2}{16}\right)\left(-\frac p8\right)=-\frac{5p}8+\frac{p^3}{128}=6$$
$$p^3-80p-768=0$$
Since $p$ is rational, by the rational root theorem we only need to try the factors of 768. It turns out that $p=12$ is the only rational real root of this equation (the others are $6\pm2\sqrt7i$), so the only possibility for the original cubic is
$$4x^3-12x^2+5x+6=4\left(x-\frac32\right)\left(x+\frac12\right)(x-2)$$
and its roots are $-\frac12,\frac32,2$. Indeed, the difference between $\frac32$ and $-\frac12$ is 2.

A: Turns out it actually was possible to use relationships between roots here to help factor the equation, I just wasn't looking hard enough.
Since $r - s = t$, then $r = s + t$. As mentioned, $\frac 54 = rs + st + rt = st + (s + t)^2$. Now, both $st$ and $s + t$ can be written in terms of $r$, since
$$
-\frac 32 = rst
$$
$$
-\frac 3{2r} = st
$$
and $s + t = r$. So substituting those values in, we get
$$
\frac 54 = -\frac 3{2r} + r^2
$$
$$
\frac 54 r = -\frac 32 + r^3
$$
$$
0 = r^3 - \frac 54 r - \frac 32
$$
$$
0 = 4r^3 - 5r - 6
$$
at which point we can use synthetic division to solve for $r$ (since all roots are rational). Then we get $r = \frac 32$ as a root, and factoring out $2x - 3$ and using the quadratic formula to solve for the remaining roots, $s = -\frac 12$ and $t = 2$.


text:
Q: Make bold the header rows in all tables using cls tex document class I am k novice in LaTeX. I have a tex document that has a cls tex format sheet beside it and create journal articles. Is it possible to make a change that affect all the tables in document have bold header row? If yes which part of cls file should change? There is only one part that refer to tables and figures so I think that the change should be happen here.
Thank you in advance for your help.
% Graphics, tables and other formatting
\RequirePackage{graphicx,xcolor}
\RequirePackage{colortbl}
\RequirePackage{booktabs}
 \RequirePackage{algorithm}
\RequirePackage[noend]{algpseudocode}
\RequirePackage{changepage}
\RequirePackage[left=48pt,% right=42pt,% top=46pt,% bottom=60pt,%
                headheight=15pt,% headsep=10pt,% letterpaper,twoside]
                {geometry}%
\RequirePackage[labelfont={bf,sf},%
                labelsep=period,%
                figurename=Fig.,%
                singlelinecheck=off,%
                justification=RaggedRight]{caption}
\setlength{\columnsep}{24pt} % Distance between the two columns of text
\setlength{\parindent}{12pt} %

Paragraph indent

A: The following updates the tabular environment and assumes the first line - everything up to the first \\ - contains the header. The header is updated to insert whatever you supply to \setheaderformat{<format>} at the start of each cell, taking care to always keep \hline (or \toprule, from booktabs) as the first entry within the header. \multicolumn header entries are partially supported (via \mc; see below), but nothing else (like multi-line headers, or whatever).

\documentclass{article}

\usepackage{environ,etoolbox,regexpatch,booktabs}

\let\oldtabular\tabular
\let\endoldtabular\endtabular

\makeatletter
\newcommand{\setheaderformat}[1]{\def\header@format{#1}}

\def\format@header#1\\#2\relax{%
  \def\tabular@header{#1\\}%
  \def\tabular@other{#2\relax\relax}%
  \patchcmd{\tabular@header}{\hline}{\hline\TAB}{}{}% \hline support (insert \TAB *after* \hline)
  \patchcmd{\tabular@header}{\toprule}{\toprule\TAB}{}{}% \toprule support (for booktabs)
  \patchcmd{\tabular@other}{\\\relax\relax}{}{}{}% Remove possible ending \\
  \patchcmd{\tabular@other}{\relax\relax}{}{}{}%
}
\RenewEnviron{tabular}[2][c]{%
  \expandafter\format@header\BODY\\\relax% Extract header/other components
  \gdef\TAB{\header@format\gdef\TAB{& \header@format\ignorespaces}\ignorespaces}% Update how \TAB will work
  \xpatchcmd*{\tabular@header}{&}{\TAB}{}{}% Replace all & with \TAB in header
  \begin{oldtabular}[#1]{#2}
    \tabular@header
    \tabular@other
  \end{oldtabular}%
}
\makeatother

\setheaderformat{\bfseries}

\begin{document}

\begin{oldtabular}{ *{3}{c} }
  \hline
  a & b & c \\
  \hline
  d & e & f \\
  g & h & i \\
  \hline
\end{oldtabular}
\qquad
\begin{tabular}{ *{3}{c} }
  \hline
  a & b & c \\
  \hline
  d & e & f \\
  g & h & i \\
  \hline
\end{tabular}

\bigskip

\begin{oldtabular}{ *{3}{c} }
  \toprule
  a & b & c \\
  \midrule
  d & e & f \\
  g & h & i \\
  \bottomrule
\end{oldtabular}
\qquad
\begin{tabular}{ *{3}{c} }
  \toprule
  a & b & c \\
  \midrule
  d & e & f \\
  g & h & i \\
  \bottomrule
\end{tabular}

\bigskip

% How to manage \multicolumn
\newcommand{\mc}{& \multicolumn}

\setheaderformat{\itshape$\rightarrow$}%
\begin{oldtabular}{ *{3}{c} }
  \toprule
  a & b & \multicolumn{1}{r}{\bfseries c$\leftarrow$} \\
  \midrule
  d & e & f \\
  g & h & i \\
  \bottomrule
\end{oldtabular}
\qquad
\begin{tabular}{ *{3}{c} }
  \toprule
  a & b \mc{1}{r}{\bfseries c$\leftarrow$} \\
  \midrule
  d & e & f \\
  g & h & i \\
  \bottomrule
\end{tabular}

\end{document}

A: FWIW, in ConTeXt this is relatively straight forward to achieve. To make the first row of the table bold, you can use
\setupTABLE[row][first][style=bold]

However, it is not a good idea to make this change globally because there may be instances where you want the first row not to be bold. Instead, it is better to define a new setup and use that in tables:
\startsetups table:header
    \setupTABLE[row][first][style=bold]
\stopsetups

and then use it as:
\startTABLE[setups=table:header]

Here is a complete example showing the result.
\startsetups table:header
  \setupTABLE[each][each][frame=off, offset=0.25ex, rulethickness=1.5pt]
  \setupTABLE[row][first][style=bold, topframe=on, bottomframe=on]
  \setupTABLE[row][last] [bottomframe=on]
\stopsetups

\starttext

\startTABLE[setups=table:header]
  \NC Type \NC First \NC Second \NC Third \NC \NR
  \NC A    \NC B     \NC C      \NC D     \NC \NR
  \NC A    \NC B     \NC C      \NC D     \NC \NR
  \NC A    \NC B     \NC C      \NC D     \NC \NR
  \NC A    \NC B     \NC C      \NC D     \NC \NR
\stopTABLE

\stoptext

which gives

Unfortunately, as you have found out, none of the table mechanisms in LaTeX provide such a separation between content and presentation in tables.


text:
Q: Makefile: no rule to make target with variables I'm trying to write a Makefile that when I add some deps in my application I just have to change DEPS_NAME variable, but something is wrong and I can't figure out what. I know that this is not the only problem with this Makefile, I just started to study this technology.
This is my project structure
application/
├── deps/
│   ├── buffer/
│   │   ├── buffer.c
│   │   └── buffer.h
│   └── other/
│       ├── other.c
│       └── other.h
├── objs/
├── application.c
└── Makefile

This is my Makefile
CC = gcc
APP_NAME = application

OBJS_PATH = objs
DEPS_PATH = deps
DEPS_NAME = buffer other

DEPS = $(patsubst %,$(OBJS_PATH)/%.o,$(DEPS_NAME))

$(OBJS_PATH)/%.o: $(DEPS_PATH)/%/%.c
    $(CC) -o $@ -c $^

$(APP_NAME): $(DEPS)
    $(CC) -o $@ $@.c $^

all: $(APP_NAME)

This is the error when i type make:
make: *** No rule to make target `objs/buffer.o', needed by `application'.  Stop.

A: until you have determined the root cause of the problem, suggest a separate target for each *.c to *.o compile step.
you want the 'all' target to be the first target in the makefile.
(that is what a 'all' target is for, so can call the makefile with:
make

without specifying a target in the make file
Note: 'all' is a phony target (produces no file named 'all')
so should be written similar to:
.PHONY: all
all : $(app_name) $(DEPS)

When make performs the compile step(s)
It needs to know how to find the header files.
and since the header files are scattered,
it may be advisable to either 1) list all the paths/*.h files in the compile rule (simple but can result in unneeded compiles) or 2) generate dependancy files.(difficult, but best as the file count grows)  or 3) write a separate compile rule for each source file. (least flexable, but easy for those new to make)
the compile rule needs to have parameters indicating where to find the header files.   (in gcc, use '-I./other/.' and '-I./buffer/.)

A: I have never seen multiple stem references. Looks like it badly confuses the parser.
On a bright side it seems that
$(OBJS_PATH)/%.o: $($(DEPS_PATH)/%/%.c)

does the trick. Don't ask me why.

A: Putting the object files in the same directory of the source files I solved the problem with this Makefile
CC = gcc
CFLAGS = -Ideps
APP_NAME = application

DEPS_SOURCE = $(wildcard deps/*/*.c)
DEPS_OBJECT = $(DEPS_SOURCE:.c=.o)

all: $(APP_NAME)

$(APP_NAME): $(DEPS_OBJECT)
    $(CC) $@.c -o $@ $(DEPS_OBJECT) $(CFLAGS)

%.o: %.c
    $(CC) -o $@ -c $^

clean:
    rm -f $(DEPS_OBJECT) $(APP_NAME)

.PHONY: all clean

Whit this solution I don't have to change the Makefile when I add other deps in the project.


text:
Q: how to Detect selected item in ContentControl in wpf I'm trying to develop a HamburgerMenu. a ContentControl  that i restyled it.
my xaml code is something like this :
 <Style TargetType="local:HamburgerMenu">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:HamburgerMenu">
                <Grid x:Name="mainGrid" Background="{TemplateBinding Background}">
                    <!--HamburgerMenu button-->
                    <Border x:Name="border" Background="{TemplateBinding Background}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="40" Width="50">
                        <ToggleButton  x:Name="menuIcon" Background="Red" HorizontalAlignment="Left" VerticalAlignment="Top" Height="40" Width="50" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:HamburgerMenu}}, Path=IsOpen}">
                            <Path x:Name="path"  HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="Uniform" Width="30" Fill="{TemplateBinding MenuIconColor}" Data="M2,15.5L22,15.5 22,17.5 2,17.5 2,15.5z M2,10.5L22,10.5 22,12.5 2,12.5 2,10.5z M2,5.5L22,5.5 22,7.5 2,7.5 2,5.5z"/>
                        </ToggleButton>
                    </Border>
                    <!-- HamburgerMenu Items List-->
                    <ListBox x:Name="listbox" ItemsSource="{TemplateBinding Content}" HorizontalAlignment="Left" Margin="0,40,0,0" VerticalAlignment="Top" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectedIndex="0"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

 <Style TargetType="local:HamburgerMenuItem">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:HamburgerMenuItem">
                <Button x:Name="ListBoxItemButton" Command="{TemplateBinding SelectionCommand}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
                    <Grid x:Name="MainGrid">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="5" />
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Grid Grid.ColumnSpan="2">
                            <Grid Background="Transparent" Margin="0" Width="300">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="45" />
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Grid Grid.Column="1">
                                    <TextBlock Text="{TemplateBinding Text}" Margin="10,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" FontFamily="Segoe UI Light" FontSize="18" Foreground="{TemplateBinding Foreground}" TextWrapping="Wrap"/>
                                </Grid>
                                <Grid Grid.Column="0">
                                    <Image Source="{TemplateBinding Icon}" Margin="10,5,5,5"/>
                                </Grid>
                            </Grid>
                        </Grid>
                        <Grid Name="ItemSelectedIndicator"    Grid.Column="0" Background="{TemplateBinding SelectionIndicatorColor}" Visibility="Collapsed" />
                    </Grid>
                </Button>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

and this is my HamburgerMenu classes :
 public class HamburgerMenu : ContentControl
{

    public new List<HamburgerMenuItem> Content
    {
        get { return (List<HamburgerMenuItem>)GetValue(ContentProperty); }
        set { SetValue(ContentProperty, value); }
    }

    public new static readonly DependencyProperty ContentProperty =
        DependencyProperty.Register("Content", typeof(List<HamburgerMenuItem>), typeof(HamburgerMenu),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure));

    static HamburgerMenu()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(HamburgerMenu), new FrameworkPropertyMetadata(typeof(HamburgerMenu)));
    }

    public override void BeginInit()
    {
        Content = new List<HamburgerMenuItem>();
        base.BeginInit();
    }

}

public class HamburgerMenuItem : ListBoxItem
{
    static HamburgerMenuItem()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(HamburgerMenuItem), new FrameworkPropertyMetadata(typeof(HamburgerMenuItem)));
    }
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(HamburgerMenuItem), new PropertyMetadata(String.Empty));

}

my question is how i can find witch ListBox item is selected in my window where i used my custom Control.

A: You could add a "SelectedItem" dependency property to your custom control and bind the SelectedItem property of the ListBox in the ControlTemplate to this one:
<!-- HamburgerMenu Items List-->
<ListBox x:Name="listbox" ItemsSource="{TemplateBinding Content}"
                         SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource TemplatedParent}}"
                         HorizontalAlignment="Left" Margin="0,40,0,0" VerticalAlignment="Top" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectedIndex="0"/>

You then bind your new dependency property to the source property in your window:
<local:HamburgerMenuItem ... SelectedItem="{Binding YourSourceProperty}" />


text:
Q: MVC Api upload one image as json mvc How i can upload one image as json in api when im
i need to upload file to server folder and save file path in object of class after upload image
var data = $('#myForm').serialize();
$.ajax({

    url: "/api/CompaniesApi/"+id,
    type: "PUT",
    dataType:'json',
    data:data,
    contentType:'application/json',
    success: function () {
        debugger;
    },
    error: function () {
        debugger;
    }

});

            @Html.LabelFor(model => model.Image, PublicResource.Image, htmlAttributes: new { @class = "control-label col-md-2" })

                <input class="fileinput form-control" type="file" name="ImageUpload" id="ImageUpload" accept="image/*" />

*****this is class :*****
public class Company
{
    public int ID { get; set; }
    public int CompanyID { get; set; }

    public string Image { get; set; }

    public string NameAr { get; set; }
    public string NameEn { get; set; }
    public string DescAr { get; set; }
    public string DescEn { get; set; }
    public string Email1 { get; set; }
    public string Phone { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime UpdatedDate { get; set; }
    public int CreatedBy { get; set; }
    public int UpdatedBy { get; set; }
}

A: You Can Try this
Html & Scrips Code like this

        <input type="file" class="form-control" id="upload-image"  accept="image/*">

asp.net web Api code Like This
[HttpPost]
public String UploadFile(String Para1) {
    try{
         if (HttpContext.Current.Request.Files.AllKeys.Any()) {
                        var files = HttpContext.Current.Request.Files;
                        var fileSavePath=Path.Combine(HttpContext.Current.Server.MapPath("~/Folder1/Folder2/"), "My up Image.jpg");
                        files[Para1].SaveAs(fileSavePath);
                        return "Image Uploaded";
        }else{
            return "Image Not Found";
        }
    }catch(Exception ex){
        return "Error";
    }
}


text:
Q: Conjectured integral for Catalan's constant Numerical evidence suggests:
$$ \int_0^{\frac12}\int_0^{\frac12}\frac{1}{1-x^2-y^2} dy \, dx= \frac{G}{3}\qquad (1)$$
Couldn't find the indefinite integral, though maple simplifies (1) to
$$ \int _{0}^{1/2}\!-\arctan \left( 1/2\,{\frac {1}{\sqrt {-1+{x}^{2}}}} \right) {\frac {1}{\sqrt {-1+{x}^{2}}}}{dx}$$

Is (1) true?

A: Mathematica confirms the following:
Change the integral to polar coordinates to get
$$\frac{(1)}{2} = \int_0^{\pi/4} \int_0^{\sec(\theta)/2} \frac{1}{1-r^2}r\ dr\ d\theta = \frac{G}{6}.$$

A: After some trick substitutions, I've put the integral in the form:
$$\int_0^{\pi/6}{\coth^{-1}{(2\,\cos{t})}dt}$$
Mathematica (version 8) then returns the exact value $\frac{G}{3}$. A nice definite integral for Catalan's constant, anyway.

A: The proof of (1),  sketched in http://www.maths.lancs.ac.uk/~jameson/catalan.pdf, goes as follows.
With the substitution $x=x^\prime/2,\,y=y^\prime/2$, the integral (1) takes the form (we have omitted the primes)
$$I_2=\int_0^1\int_0^1\frac{dx\,dy}{4-x^2-y^2}.$$
Due to the $x\leftrightarrow y$ exchange symmetry of the integrand,
$$I_2=2\iint\limits_\Delta \frac{dx\,dy}{4-x^2-y^2},$$
where the triangular integration domain $\Delta$ is the lower half of the unit square $0\le x\le 1,\,0\le y\le 1$. Let us introduce the polar coordinates, as suggested by Aeryk, $x=r\cos{\theta},\,y=r\sin{\theta}$. Then
$$I_2=\int\limits_0^{\pi/4}d\theta\int\limits_0^{1/cos{\theta}}\frac{2r}{4-r^2}dr=\int\limits_0^{\pi/4}\ln{\frac{4\cos^2{\theta}}{4\cos^2{\theta}-1}}\,d\theta.$$
Now, by using $\sin{3\theta}=\sin{\theta}(3\cos^2{\theta}-\sin^2{\theta})=\sin{\theta}(4\cos^2{\theta}-1)$, we cen rewrite the above integral in the form $$I_2=\int\limits_0^{\pi/4}\ln{\frac{4\cos^2{\theta}\sin{\theta}}{\sin{3\theta}}}\,d\theta=\frac{\pi}{2}\ln{2}+2I_C+I_S-I_{3S},$$
where the integrals $$I_S=\int\limits_0^{\pi/4}\ln{\sin{\theta}}\,d\theta=-\frac{1}{2}\,G-\frac{\pi}{4}\,\ln{2},\;I_C=\int\limits_0^{\pi/4}\ln{\cos{\theta}}\,d\theta=\frac{1}{2}\,G-\frac{\pi}{4}\,\ln{2}$$
were calculated in http://www.maths.lancs.ac.uk/~jameson/catalan.pdf, while for $I_{3S}$ we have
$$I_{3S}=\int\limits_0^{\pi/4}\ln{\sin{3\theta}}\,d\theta=\frac{1}{3}
\int\limits_0^{3\pi/4}\ln{\sin{\theta}}\,d\theta=\frac{1}{3}\left[
\int\limits_0^{\pi/2}\ln{\sin{\theta}}\,d\theta+
\int\limits_{\pi/2}^{3\pi/4}\ln{\sin{\theta}}\,d\theta\right].$$
The substitution $\alpha=-(\pi/2-\theta)$ shows that the second integral equals to $I_C$, while for the first integral the following result can be found in http://www.maths.lancs.ac.uk/~jameson/catalan.pdf
$$\int\limits_0^{\pi/2}\ln{\sin{\theta}}\,d\theta=
\int\limits_0^{\pi/2}\ln{\cos{\theta}}\,d\theta=-\frac{\pi}{2}\,\ln{2}.$$
Therefore
$$I_{3S}=\frac{1}{3}\left[-\frac{\pi}{2}\,\ln{2}+\frac{1}{2}\,G-\frac{\pi}{4}\,\ln{2}\right]=\frac{1}{6}\,G-\frac{\pi}{4}\,\ln{2},$$ and
$$I_2=\frac{\pi}{2}\ln{2}+2\left(\frac{1}{2}\,G-\frac{\pi}{4}\,\ln{2}\right)+\left(-\frac{1}{2}\,G-\frac{\pi}{4}\,\ln{2}\right)-\left(\frac{1}{6}\,G-\frac{\pi}{4}\,\ln{2}\right)=\frac{G}{3}.$$
By the similar method, the following result was proved in http://www.maths.lancs.ac.uk/~jameson/catalan.pdf
$$I_1=\int_0^1\int_0^1\frac{dx\,dy}{2-x^2-y^2}=G.$$

A: There is also an interpretation of this integral in terms of hyperbolic geometry. In hyperbolic geometry, Catalan's constant $G$ is one quarter the (three dimensional) volume of a regular ideal octahedron (or the volume of an ideal tetrahedron with dihedral angles $\frac{\pi}{2}, \frac{\pi}{4}$, and $\frac{\pi}{4}$).
If $\Gamma$ is the group of orientation preserving isometries of a tessellation of $\mathbb{H}^3$ by regular ideal octahedra (aka $PGL(2,O_1)$), the quotient of $\mathbb{H}^3/\Gamma$ has volume: $$\frac{G}{6}=\int_0 ^\frac{1}{2}\int_0 ^\frac{1}{2}\int_\sqrt{1-x^2-y^2} ^\infty \frac{1}{z^3} dz dy dx = \frac{1}{2}\int_0 ^\frac{1}{2}\int_0 ^\frac{1}{2}\frac{1}{1-x^2-y^2} dy dx .$$
A decent reference for understanding this observation is Neumann and Reid's Notes on Adams' small volume orbifolds (page 312). Although not directly stated, their method relies on the observation that a certain manifold, the Whitehead link complement, is well known to be isometric to a regular ideal octahedron with faces identified in pairs, as noted above this means it has volume $4G$. The orbifold we are interested in is a 24 fold quotient of this manifold, and so it has volume $\frac{G}{6}$. The geometry of the orbifold is described in Colin Adams' paper Noncompact 3-Orbifolds of Small Volume (see figure 6(c) and Theorem 5.2).
However, an early reference is Borel's paper: Commensurability classes and volumes of hyperbolic 3-manifolds.


text:
Q: Getting `File not found` errors for an `asset`. How can this be? I'm about to go nuts with this. I keep getting errors when trying to open a text file that's in my assets directory, whose full path name is
C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\
   app\src\main\assets

Even though we can SEE filename Dictionary.dic in the assets folder for my  project...

... I keep getting errors that the file doesn't exist:
W/`````: Can't open <Dictionary.dic>
W/System.err: java.io.FileNotFoundException: Dictionary.dic
W/System.err:     at android.content.res.AssetManager.openAsset(Native Method)
W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err:     at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:328)
W/System.err:     at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:315)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:841)

Doc says you can use hierarchical name in the open statement:
W/`````: Can't open <C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic
W/System.err:     at android.content.res.AssetManager.openAsset(Native Method)
W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err:     at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err:     at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:330)
W/System.err:     at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:317)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)

Same problem.
Can you see any problem with my code? The problem HAS to be obvious, but after two days of trying this and that and utterly failing, and it LOOKS so good and therefore MUST be obvious, but I CAN'T SEE IT....

I've included this in case it's not obvious from above. If this doesn't help, I'm on my own.
Here is how DatabaseConnector gets called in onCreate in MainActivity:
assets = getAssets();

dbc = new DatabaseConnector(getApplicationContext(), assets); // to create DB if needed

Here's how mAssets and SOURCE_NAME are defined; also have DatabaseConnector definition and its call to dbOpenHelper.

Here's how LoadDatabase is called from createDbIfNecessary:
  LoadDatabase
      __loadDb;
      __loadDb = new LoadDatabase();
      __loadDb.execute((Object[]) null);

EDIT
Another opinion:

EDIT 2
Please note that changing the filename in the code to lowercase doesn't help. AND it's a DOS file, NOT ANDROID. AND File is never leaving drive C:
public static String DATABASE_SOURCE =
"C:\\Users\\Dov\\Desktop\\ServyHelperton\\app\\src\\main" +
  "\\assets\\dictionary.dic";

W/`````: Can't open <C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic>

W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic

I could add more code to prove what I just said, but trust me. The DATABASE_SOURCE name is ALL I changed.

A: It appears your path is for Dictionary.dic rather than dictionary.dic
See if that helps

A: In the end, the fix was sort of easy or maybe dumb luck, because I'm not sure why making the InputStream and Scanner local to doInBackground cured the problem.
Refer to the first picture in the original Question. I made no significant changes to MainActivity, but here is the interesting line in it:
dbc = new DatabaseConnector(getApplicationContext(), getAssets());

This is what worked:
public class DatabaseConnector
{
  static Context mContext;

  public DatabaseConnector(Context _context, AssetManager _assets)
  {
    mAssets   = _assets;
    mContext  = _context;

    mDbOpenHelper = new DbOpenHelper(_context, DATABASE_NAME, null, 1);

    createDbIfNecessary();
  }

  private class DbOpenHelper extends SQLiteOpenHelper
  {
    DbOpenHelper(Context _context, String _name, CursorFactory _factory, int _version)
    {
      super(_context, _name, _factory, _version);
    }

    private class LoadDatabase extends AsyncTask<Object, Integer, Void>
    {
      protected Void doInBackground(Object[] params)
      {
        Scanner scDict = null; // ***** MOVING/ADDING THESE
        InputStream stream;    // ***** TWO LINES HERE WAS KEY
        try{
          stream = mContext.getAssets().open(DATABASE_SOURCE);
          scDict = new Scanner(stream).useDelimiter("\r\n");
        }
        catch(IOException e){e.printStackTrace(); System.exit(69);}
      }
    }
  }
}


text:
Q: Cheerio scraper won't find any links in a sitemap I'm trying to fetch URLs from a sitemap (XML) that I want to scrape.
I tried using the standard Cheerio template for this but it keeps returning that no URLs are found.
Any idea why this happens?
const Apify = require("apify");
const cheerio = require("cheerio");

Apify.main(async () => {
  const input = await Apify.getInput();
  // Download sitemap
  const xml = await Apify.utils.requestAsBrowser({
    url: input?.url || "https://www.example.com/product-sitemap2.xml",
    headers: {
      "User-Agent": "curl/7.54.0",
    },
  });

  // Parse sitemap and create RequestList from it
  // const $ = cheerio.load(xml.toString());
  const $ = cheerio.load(xml);
  const sources = [];
  $("loc").each(function (val) {
    const url = $(this).text().trim();
    sources.push({
      url,
      headers: {
        // NOTE: Otherwise the target doesn't allow to download the page!
        "User-Agent": "curl/7.54.0",
      },
    });
  });
});

.

A: It seems you need to use xml.body instead of xml.
 Docs for Apify.utils.requestAsBrowser function.
const $ = cheerio.load(xml.body);

A: You trying outdated version, the latest is https://crawlee.dev/docs/examples/crawl-sitemap


text:
Q: Passing linked list that consists of three structures to a function I know how create a linked list with two structures
To do so, I declare a structure that contains all the necessary data. It looks like this:
struct Data{
    int numb;
    int date;
}

Second structure represents a node that has a head (i.e. first element of the list) and a link to the next node.
struct llist{
    Data d;
    llist *next;
}

I wonder what if I wanted to add my llist to another structure that would represent a list.
struct mainList{
    llist l;
}

I know it may create some difficulties as I'm not quite sure how to pass main list to a function.
Here, I've tried to print linked list
void show(mainlist *ml){
    llist *u = ml->l;
    while(u){
        printf("Date: %s\t Name: %s\n",  u->d.dat, u->d.uname/* u->d.dat, u->d.uname*/);
        u=u->next;
    }
}

But got an error saying that "I cannot 'llist' to 'llist*' in initialization'
So, I'm clueless here... Any ideas?

A: There are many issues - however, one pertaining to the error you are referring is the line:
llist *u = ml->l;  /* I guess you mean struct llist *u = ml->l */

in show function. Here u is a struct llist *, but ml->l is a struct llist , but NOT a pointer to it. You need to change the struct mainList as:
struct mainList{
    struct llist *l;
}

So that ml->l is a struct llist *.

A: Working solution below, your code snippet had some issues. pointed out in comments...
#include <iostream>
using namespace std;

struct Data {
    int numb;
    int date;
};

struct llist {
    Data d;
    llist *next;
};

struct mainList{
    llist *l; /*should be a pointer as you are referencing it as a pointer*/
};

void show(mainList *ml){ /*should be mainList, your code snippet shows 'mainlist'*/
    llist *u = ml->l;
    while(u){
        printf("Date: %d\t Name: %d\n",  u->d.date, u->d.numb/* u->d.dat, u->d.uname*/); /*your code snippet was using unavailable members of the struct*/
        u=u->next;
    }
}

int main ()
{

    mainList ml;

    show(&ml);

    return 0;
}


text:
Q: Scala SBT SparkContext error in IntelliJ for Windows - No configuration setting for 'akka.version' I've been training myself on Scala, IntelliJ, and Spark.
I downloaded 'org.apache.spark:spark-core_2.10:1.1.1' into my IntelliJ project, and I'm trying to apply some training that I've taken on Spark.  I'm trying to make it easy on myself by using either Scala worksheets (preferred) or Scala console to test out ideas.

Code snippet:
import org.apache.spark
import org.apache.spark._
val sc = new SparkContext("local[2]", "sc1")

When I try to create a SparkContext, I get an error:
In the scala worksheet:
com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'akka.version'
In the scala console:
java.lang.NoClassDefFoundError: Could not initialize class akka.actor.ActorCell$
I don't have any experience with akka, I didn't want to use akka.  Is it required for Spark?  Am I using the wrong scala library?

I read other questions with the same errors, but so far, the suggestions haven't helped.
I added the following dependencies to my build.sbt file:
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.4.0"
I'll be happy to answer further questions.  I'm not sure what else to add in order to make this question easier to answer.
Thanks,
David Webb

A: I got past this error by updating my SBT dependencies to:
libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.0"

I also downloaded org.apache.spark:spark-core_2.11-1.6.0.jar  IntelliJ was previously finding only spark-core_2.10-1.1.1.jar when it searched maven.
I'm still unable to create a spark context, but I'm getting a different error now.  I'll search on the new error and see what I can find before I post another question.
David Webb