text:
Q: update List of heterogeneous types I have a List filled with n numbers of different object records. I want to pass this list to execute the method of the batch class and update the records.
for eg: there are 3 objects object A, B, C are added into one list (sObject)
I need to cast into each object dynamically and then do the update.

A: You can just update your list of sObjects, SF is capable of doing it. Just make sure that the elements in your collection are sorted per object type and not chaotic. Chunking will only allow you to have up to 10 chunks for the DML, and each chunk is up to 200 records of the same object type.
So, for example, if you have 201 Accounts, 50 Leads and 399 Contacts in your list, you will use 5 chunks out of allowed 10. This will only be true if the list is sorted/ordered by object type. So if you would have a list like [Account, Lead, Contact, Account, Lead, Contact, Account, Contact, Account, Lead, Contact, Lead, Contact, Account, Lead], then update on your list will fail because the first 10 records will use all 10 of the allowed chunks.

A: If what you want is to access SObjects that are part of a List<SObject> you can probably use a factory or the switch statement
Before that you need to get SObjects names by doing something like this:
List<SObject> objects = new List<SObject>();
Account account = new Account(Name = 'AccountSObject');
Contact contact = new Contact(LastName = 'ContactSObject');

objects.add(account);
objects.add(contact);
System.debug(objects.size());

List<SObject> sObjectAccounts = new List<SObject>();
List<SObject> sObjectContacts = new List<SObject>();

List<Account> castedAccounts = new List<Account>();
List<Account> castedContacts = new List<Account>();

for(SObject sObjectTypes : objects) {
    String sObjName = sObjectTypes.getSObjectType().getDescribe().getName();
    System.debug(sObjName);
    if(sObjName == 'Account') {
        sObjectAccounts.add(sObjectTypes);
    } else if(sObjName == 'Contact') {
        sObjectContacts.add(sObjectTypes);
    }
}

System.debug('SObject Accounts: ' + sObjectAccounts.size());

for(Account a : (List<Account>) sObjectAccounts) {
    castedAccounts.add(a);
}

System.debug('Casted accounts: ' + castedAccounts.size());

Output:

Notice that the SObjects are not inserted to the database yet but you still get the running SObject name which you can use latter on different processes.
As how or what you want to do with these SObjects on a Database.Batchable is really up to you.
I haven't test this but here is an example for you to play around:
global class DynamicSObjectsBatchableOperations implements Database.Batchable<SObject> {

private List<SObject> objTypes;
private List<SObject> sObjectAccounts = new List<SObject>();
private List<SObject> sObjectContacts = new List<SObject>();
private List<Account> castedAccounts = new List<Account>();
private List<Account> castedContacts = new List<Account>();

// We can use the constructor to pass our list of SObjects
public DynamicSObjectsBatchableOperations(List<SObject> objList){
    objTypes = objList;
 }

global Database.QueryLocator start(Database.BatchableContext BC) {
    String query;

    for(SObject sObjectTypes : objTypes) {
        String sObjName = sObjectTypes.getSObjectType().getDescribe().getName();

           if(sObjName == 'Account') {
            sObjectAccounts.add(sObjectTypes);

           } else if(sObjName == 'Contact') {
            sObjectContacts.add(sObjectTypes);
        }
     }

    for(Account a : (List<Account>) sObjectAccounts) {
        castedAccounts.add(a);
    }

    for(Contact c : (List<Contact>) sObjectContacts) {
        castedContacts.add(c);
    }

    if (!castedAccounts.isEmpty()) {

        query = 'SELECT Id, Name ' +
                'FROM Account ' +
                'WHERE Id IN: castedAccounts';

        return Database.getQueryLocator(query);

    } else if (!castedContacts.isEmpty()) {

        query = 'SELECT Id, LastName ' +
                'FROM Contact ' +
                'WHERE Id IN: castedContacts';

        return Database.getQueryLocator(query);

    } else {

        return Database.getQueryLocator(query);

    }

}

global void execute(Database.BatchableContext BC, List<SObject> objList) {

  List<SObject> accountsToupdate = new List<SObject>();
  List<SObject> contactsToupdate = new List<SObject>();

    for(SObject sObjectTypes : objList) {
        String sObjName = sObjectTypes.getSObjectType().getDescribe().getName();

           if(sObjName == 'Account') {
            accountsToupdate.add(sObjectTypes);

           } else if(sObjName == 'Contact') {
            contactsToupdate.add(sObjectTypes);
        }
     }

     if(!accountsToupdate.isEmpty()) {
        for(Object a : accountsToupdate) {
            Account acc = (Account) a;

            if (acc.Name != 'FromBatch') {
                acc.Name = 'FromBatch';
            }
        }

        Database.update(accountsToupdate, false);

       } else if (!contanctsToUpdate.isEmpty()) {
         for(Object c : contanctsToUpdate) {
            Contact con = (Contact) c;

            if (c.LastName != 'FromBatch') {
                c.LastName = 'FromBatch';
            }
        }

        Database.update(contactsToupdate, false);

     }
  }

  global void finish(Database.BatchableContext BC) {}

}


text:
Q: Minkowski Difference with 3D convex Polyhedrons I do not know much about collision detection and I am trying to resolve 3D collisions exactly. To do so, I am using the Minkowski difference. The thing is, I am having problems calculating the difference between two shapes.
What I tried doing:
In 2D you can calculate the M. difference of 2 polygons (A and B) by looping in the edges of A finding the correct support vertex of B by using the reversed edge normal of A and then substrating the edge of A by the supporting vertex of B. And then do something similar by looping through the edges of B.
So basically, in 3D I tried doing the same thing by using triangles instead of edges. It seems to kinda work and kinda fail (here is M. difference of a cube with the same cube turned 45 degrees):
Click to view image.
As seen in the image, there is a weird hole in the middle. I don't think this is normal because we are supposed to end up with a closed shape.
Here below is my code (note that the code is very unoptimised because I'm not sure about how to choose the supporting vertices, so I don't choose, I take all of them).
Here is the class which takes care of the Minkowski stuff (if there is an //OK over the method, I'm pretty sure that it works):
#include "TransformedPolyhedron.h"
#include "Array.h"
#include "graphics/MeshLoader.h"
#include <iostream>

using namespace graphics;

namespace math
{
  TransformedPolyhedron::TransformedPolyhedron(Polyhedron& polyhedron)
  {
    this->polyhedron = &polyhedron;
  }

  //OK
  ArrayList<int>& TransformedPolyhedron::getIndices() const
  {
    return polyhedron->getIndices();
  }

  //OK
  ArrayList<Vector3> TransformedPolyhedron::getTransformedPositions() const
  {
    ArrayList<Vector3>& positions = polyhedron->getPositions();
    ArrayList<Vector3> result(positions.size());

    for(int i=0;i<result.size();i++)
    {
      result[i] = transformation.transform(positions[i]);
    }
    return result;
  }

  //OK(?)
  ArrayList<TriangleFace> TransformedPolyhedron::getTriangleFaces(const ArrayList<Vector3>& positions) const
  {
    ArrayList<int>& indices = getIndices();
    ArrayList<TriangleFace> result;
    for(int i=0;i<indices.size();i+=3)
    {
      Vector3& v1 = positions[indices[i]];
      Vector3& v2 = positions[indices[i + 1]];
      Vector3& v3 = positions[indices[i + 2]];
      result.add(TriangleFace(v1, v2, v3));
    }
    return result;
  }

  ArrayList<Vector3> TransformedPolyhedron::getSupportingVertex(const Vector3& normal, const ArrayList<Vector3>& positions) const
  {
    double maxDot = normal.dot(positions[0]);
    for(int i=0;i<positions.size();i++)
    {
      double dot = normal.dot(positions[i]);
      if(dot > maxDot)
      {
        maxDot = dot;
      }
    }
    ArrayList<Vector3> result;
    for(int i=0;i<positions.size();i++)
    {
      Vector3& position = positions[i];
      double dot = normal.dot(position);
      if(dot >= maxDot)
      {
        result.add(position);
      }
    }
    return result;
  }

  Polyhedron TransformedPolyhedron::minkowskiDifference(const TransformedPolyhedron& poly) const
  {
    ArrayList<int> resultIndices;
    ArrayList<Vector3> resultPositions;

    ArrayList<Vector3> thisPositions = getTransformedPositions();
    ArrayList<TriangleFace> thisTriangleFaces = getTriangleFaces(thisPositions);

    ArrayList<Vector3> polyPositions = poly.getTransformedPositions();
    ArrayList<TriangleFace> polyTriangleFaces = poly.getTriangleFaces(polyPositions);
    //this
    for(int i=0;i<thisTriangleFaces.size();i++)
    {
      TriangleFace& triangle = thisTriangleFaces[i];
      Vector3 normal = triangle.getNormal();
      normal*=(-1);
      ArrayList<Vector3> supportingVectors = poly.getSupportingVertex(normal, polyPositions);
      for(int k=0;k<supportingVectors.size();k++)
      {
        Vector3& supportingVector = supportingVectors[k];
        for(int j=0;j<3;j++)
        {
          Vector3 toAdd = triangle[j] - supportingVector;

          resultIndices.add(resultPositions.size());
          resultPositions.add(toAdd);
        }
      }
    }
    //poly
    for(int i=0;i<polyTriangleFaces.size();i++)
    {
      TriangleFace& triangle = polyTriangleFaces[i];
      Vector3 normal = triangle.getNormal();
      normal*=(-1);
      ArrayList<Vector3> supportingVectors = getSupportingVertex(normal, thisPositions);
      for(int k=0;k<supportingVectors.size();k++)
      {
        Vector3& supportingVector = supportingVectors[k];
        for(int j=0;j<3;j++)
        {
          Vector3 toAdd = triangle[j] - supportingVector;

          resultIndices.add(resultPositions.size());
          resultPositions.add(toAdd);
        }
      }
    }

    return Polyhedron(resultPositions, resultIndices);
  }

  //OK
  void TransformedPolyhedron::transform(const Matrix4& transformation)
  {
    this->transformation = transformation;
  }

  //ok
  GLuint TransformedPolyhedron::loadToGPU(int* amount) const
  {
    ArrayList<int>& indices = getIndices();
    ArrayList<Vector3> positions = getTransformedPositions();
    ArrayList<float> textures(positions.size()*2);
    ArrayList<float> positionsArray(positions.size()*3);
    for(int i=0;i<positions.size();i++)
    {
      positionsArray[3*i] = positions[i].getX();
      positionsArray[3*i + 1] = positions[i].getY();
      positionsArray[3*i + 2] = positions[i].getZ();
    }
    Array<float> apos(positionsArray.toArray(), positionsArray.size());
    Array<int> aind(indices.toArray(), indices.size());
    Array<float> atex(textures.toArray(), textures.size());
    *amount = indices.size();
    return MeshLoader::loadIndexedVertices(apos, atex, aind);
  }
}

Thanks for helping!

A: Ok i found what was wrong with the algorithm, basicly i was only calculating the "translated faces" and wasn't calculating the part done by sweeping the edges, here is a paper talking about the minkowski sum and how to compute it: liris.cnrs.fr/Documents/Liris-3813.pdf (look at the part about the CVMS algorithm)
In the end for collision detection this is very bad performence-wise, so as someone pointed out in the comments, i implemented the GJK algorithm for collision detection and the EPA algorithm for collision response, works petty well.
GJK + EPA: http://hacktank.net/blog/?p=93

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why there is no Linux Handbook? Look e.g. onto the BSD's family:
FreeBSD Handbook: http://www.freebsd.org/doc/en/books/developers-handbook/debugging.html
OpenBSD FAQ, nearby FreeBSD's Handbook: http://www.openbsd.org/faq/index.html
I'm really discouraged what can be called official Linux documentation. Information scattered around the network. Where is the core?
Is it
ii  linux-doc                                                   3.11.0-14.21                               all          Linux kernel specific documentation for version 3.11.0
of my Ubuntu?

A: Linux isn't a complete OS. The latter is provided with userland part and is often called "distribution". Different distributions have their own documentation which could be more advanced that handbooks you mentioned. Personally for Ubuntu, there is at least on-site documentation.


text:
Q: Can't configure antMatchers after anyRequest (Multiple antMatcher) I am trying to configure Spring Security and get this following error:

Caused by: java.lang.IllegalStateException: Can't configure antMatchers after anyRequest

This is my SecurityConfig class:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

            auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{

        http
            .csrf().disable();
        http
            .httpBasic()
                .and()
            .authorizeRequests()
                .antMatchers("/rest/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .authorizeRequests()
                .antMatchers("/secure/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .permitAll();

        http
            .authorizeRequests()
                .antMatchers("/login").permitAll();
    }

    @Bean
    public BCryptPasswordEncoder encodePWD(){
        return new BCryptPasswordEncoder();
    }
}

I already tried call httpSecurityauthorizeRequests().anyRequest().authenticated() as mentioned here,
still didn't work
...any suggestion would be helpfull.

A: It might help someone for same kind of Exception
Here is my code:-
    @Override
      protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

         http.authorizeRequests()
             .antMatchers("/**")
             .hasAnyRole()
             .and()
             .formLogin();
    }

I just removed the call to super class :- super.configure(http); It worked for me. Just remove that line.

A: Modify the rule as follows . .anyRequest().authenticated() to be used only once .
    http
        .httpBasic()
            .and()
        .authorizeRequests()
            .antMatchers("/rest/**").permitAll()
            .and()
        .authorizeRequests()
            .antMatchers("/secure/**").hasAnyRole("ADMIN")
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .permitAll();

A:   protected void configure(HttpSecurity http) throws Exception {

        http.csrf()
            .disable()
            .cors()
            .disable()
            .authorizeRequests()
            .antMatchers("/login", "/user/createUser")
            .permitAll()
            .antMatchers(HttpMethod.OPTIONS)
            .permitAll()
            .anyRequest()
            .authenticated()
            .and().exceptionHandling()
            .authenticationEntryPoint(unautorizeHandler)
            .and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

       http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}

A: Authenticated should come last
httpSecurity.csrf().disable()
                 .cors()
                .and().authorizeRequests()
                .antMatchers("xyz").permitAll()
                .antMatchers("abc")
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);


text:
Q: Read lines from Text file I just want to read some specific lines from a text file not all the lines.
I tried the following code:
public class BufferedReaderDemo {

    public static void main(String[] args) throws IOException {

        FileReader fr = new FileReader("Demo.txt");
        BufferedReader br = new BufferedReader(fr);
        String line = br.readLine();

        while(line!=null)
        {
            System.out.println(line);
            line = br.readLine();
        }

        br.close();
    }
}

Using this code I am able to get all the lines. But I want to print some specific 2–3 lines in console that start with "namespace" and end with "Console".
How can I achieve this?

A: You have no choice, if you want to know if a line contains some specific words, you have to read it.
If you want only print these lines, you can add a condition before printing them.
String line = br.readLine();

while(line!=null){
    if (line.startsWith("namespace") && line.endsWith("Console")){
       System.out.println(line);
    }
    line = br.readLine();
}

A: Use String.startsWith and String.endsWith:
while(line!=null)
{
    if(line.startsWith("namespace") && line.endsWith("Console")) {
        System.out.println(line);
    }
    line = br.readLine();
}


text:
Q: input radio does not hide content when unchecked input radio does not hide content when unchecked, i can't make the content be hidden when the radio input is unchecked
how can I hide the content of the unmarked radio input?
clicking on another radio input is unchecked but does not hide the content

$('#alternar').click(function () {
    $('#prueba').toggle();
});

$('#alternarx').click(function () {
    $('#pruebax').toggle();
});

/* commented out because this select doesn't appear in the HTML:
  $(".placeholder").select2({
  placeholder: "Make a Selection",
  allowClear: true
  });
*/

function uncheckAndCheck(event) {

    // gets all radios with the name prefix like 'custom-radio-'
    // and uncheck all of them
    document.querySelectorAll("input[type='radio'][name^='custom-radio-']").forEach(radio => {
        radio.checked = false;
    });

    // checks the radio that triggered the click event
    event.target.checked = true;

}
#prueba{

           display:none
        }
        #pruebax{

          display:none
        }

         <input type="radio" class="new-control-input" name="custom-radio-1" id="alternarx" onclick="uncheckAndCheck(event)"/>

 Content1

        <input type="radio" class="new-control-input" name="custom-radio-2" id="alternar" onclick="uncheckAndCheck(event)"/>

 Content2

A: This is actually possible entirely with CSS. You can use the adjacent sibling combinator +, which affects an element immediately following the first.

#prueba{
    display: none;
}
#pruebax{
    display: none;
}
input:checked + #prueba,
input:checked + #pruebax {
    display: block;
}
<input type="radio" class="new-control-input" name="custom-radio-1" id="alternarx" onclick="uncheckAndCheck(event)"/>

 Content1

<input type="radio" class="new-control-input" name="custom-radio-2" id="alternar" onclick="uncheckAndCheck(event)"/>

 Content2

A: George's solution works, but is reliant upon the HTML never changing. If you add any element between the radio button and the div, it will break the functionality.
To answer your question related to JavaScript:
It's unnecessary to check and uncheck the other radio inputs. You just need to give them the same name attribute.
Second, you're .toggle()ing the divs on click. That might be why they're acting strangely. You're not checking if the radio button is selected or not, and that's going to result in them toggling even when you click them when they're already selected. Luckily, you can just listen for them to change states.
Third, you can hold a selector for the target of the radio button you want to show/hide in a data attribute, and use one function for all of this.
Fourth, why mix inline onclick attributes, when you're using jQuery? Just listen for the event using the built-in listeners in jQuery.

//jQuery shorthand for $(document).ready(function(){ to be sure your DOM has loaded:
$(function() {

    //run this on page load, too. Necessary because browsers will remember which one is checked on a page *refresh*, and hides the target divs initially when nothing is checked:

    $checkedRB = $(".rbToggleDiv:checked");

    if($checkedRB.length > 0) {
      toggleVisibleDivs($checkedRB);
    } else {
      toggleVisibleDivs(false);
    }

    //both radio buttons have the same class as well, so you can listen for either of them to change states:
    $(document).on("change", ".rbToggleDiv", function(e) {
      //this = radio button that has changed
      var $thisRB = $(this); //turn it into a jQuery object

      if($thisRB.prop("checked")) { //only do something if this RB is checked
        toggleVisibleDivs($thisRB);
      }
    });

    function toggleVisibleDivs($targetRB) {
      if ($targetRB === false) { //no target sent in

        //hide all
        $(".pruebaDiv").hide(); //hide all divs

      } else { //target sent in

        if ($targetRB.data("target-div")) { //make sure the data is set
          var targetSelector = $targetRB.data("target-div"), //grab the string from the data object
              $targetDiv = $(targetSelector); //use it to select the target div

              if ($targetDiv.length > 0) { //make sure the div is selected
                //hide all divs with the same class:
                $(".pruebaDiv").hide();

                //then, show only the one you want visible, the $targetDiv:
                $targetDiv.show();
              } else {
                console.error("Div not found!", targetSelector);
              }
        } else {
          //data not set:
          console.error("Data was not set.");
        }

      }
    }
  });
.pruebaDiv {
    display: none;
}

<input type="radio" class="rbToggleDiv" name="rb-toggle-div" id="alternarx" data-target-div="#prueba" />
<input type="radio" class="rbToggleDiv" name="rb-toggle-div" id="alternar" data-target-div="#pruebax" />

 Content1

 Content2


text:
Q: Are all Lightning to USB-C cables capable of the same charging power? My iPhone came with a Lightning to USB-C cable which looks similar to the cable that I got with my Apple Magic Keyboard and Apple Magic Mouse.
Are all of these cables capable of the high-speed charging of my iPhone, or do I need to be careful not to mix these cables up?

A: The 8 pin Lightning connector and assorted Apple cables will not be the limiting factor for charging any Apple device. The power adapter to which it connects will determine the fastest charging rate since the MFI program has certified manufacturers to ensure correct fast charging with embedded chips in the cables to identify them to the iPhone / iPad / keyboard or other accessory that charges via lightning connector.

Most third party cables (especially ones that are listed) will be just as good for charging - especially ones with MFI hardware and certification. Examine the connector with a magnifying device and the Apple ones have clean flat contacts and even side dimples for a snug fit.

*

*https://support.apple.com/en-us/HT204566


text:
Q: Save HTML tables locally in the Angular/Django I'm new in full-stack development and it's a lot of try and error. Now I'm struggling with HTML tables. For explanation:
I am building a simple web app that can show tables from Azure SQL Database. I am able to input the tables through a backend connection (Django) to the Frontend(Angular) for representation. but, every time I reload the app, all data from the table are gone and it starts calling the tables again. it would be great to save these tables permanently because the tables are so large and it takes a long time to fetch them again.
What's the best way to achieve this?


text:
Q: android upload image to amazon storage with image path I want to upload a image using it's file path. Most of the tutorial I have followed regarding upload image to amazon, there is select image option(image chooser from galary). But what i need is that:
But I want to skip this step. As I know the image path and name. Suppose I have a image in a directory in the device. When user click upload photo button, it will start uploading. I want to skip select image option. But  How Can I upload  image to amazon storage with image path instead of selecting image (Intent image/*)?
So in short I am just wanting to use file path directly instead of select image option to upload the image in amazon.
Any help will be greatly appreciated. Thanks in advance.
Edited:
Here is my activity:
public class SubmitActivity extends Activity {

Button submit;
ImageView thumbnailimage;
private AmazonS3Client s3Client = new AmazonS3Client(
        new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
                Constants.SECRET_KEY));

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // getActionBar().setDisplayShowTitleEnabled(false);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    s3Client.setRegion(Region.getRegion(Regions.US_WEST_2));
    setContentView(R.layout.submit);

    submit = (Button) findViewById(R.id.buttonsubmit);
    submit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Uri selectedImage = Uri.parse(Environment
                    .getExternalStorageDirectory().toString()
                    + File.separator + "cubicasa.jpg");
            new S3PutObjectTask().execute(selectedImage);
        }
    });
    thumbnailimage = (ImageView) findViewById(R.id.thumbimg);

    byte[] imageData = null;

    try {

        final int THUMBNAIL_SIZE = 150;
        // InputStream is=getAssets().open("apple-android-battle.jpg");
        FileInputStream fis = new FileInputStream(Environment
                .getExternalStorageDirectory().toString()
                + File.separator
                + "cubicasa.jpg");
        Bitmap imageBitmap = BitmapFactory.decodeStream(fis);

        Float width = new Float(imageBitmap.getWidth());
        Float height = new Float(imageBitmap.getHeight());
        Float ratio = width / height;
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap,
                (int) (THUMBNAIL_SIZE * ratio), THUMBNAIL_SIZE, false);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        imageData = baos.toByteArray();
        thumbnailimage.setImageBitmap(imageBitmap);
    } catch (Exception ex) {

    }

}

private class S3PutObjectTask extends AsyncTask<Uri, Void, S3TaskResult> {

    ProgressDialog dialog;

    protected void onPreExecute() {
        dialog = new ProgressDialog(SubmitActivity.this);
        dialog.setMessage(SubmitActivity.this.getString(R.string.uploading));
        dialog.setCancelable(false);
        dialog.show();
    }

    protected S3TaskResult doInBackground(Uri... uris) {

        if (uris == null || uris.length != 1) {
            return null;
        }

        // The file location of the image selected.
        Uri selectedImage = uris[0];

        ContentResolver resolver = getContentResolver();
        String fileSizeColumn[] = { OpenableColumns.SIZE };

        Cursor cursor = resolver.query(selectedImage, fileSizeColumn, null,
                null, null);

        cursor.moveToFirst();

        int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
        // If the size is unknown, the value stored is null. But since an
        // int can't be
        // null in java, the behavior is implementation-specific, which is
        // just a fancy
        // term for "unpredictable". So as a rule, check if it's null before
        // assigning
        // to an int. This will happen often: The storage API allows for
        // remote
        // files, whose size might not be locally known.
        String size = null;
        if (!cursor.isNull(sizeIndex)) {
            // Technically the column stores an int, but cursor.getString
            // will do the
            // conversion automatically.
            size = cursor.getString(sizeIndex);
        }

        cursor.close();

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(resolver.getType(selectedImage));
        if (size != null) {
            metadata.setContentLength(Long.parseLong(size));
        }

        S3TaskResult result = new S3TaskResult();

        // Put the image data into S3.
        try {
            s3Client.createBucket(Constants.getPictureBucket());

            PutObjectRequest por = new PutObjectRequest(
                    Constants.getPictureBucket(), Constants.PICTURE_NAME,
                    resolver.openInputStream(selectedImage), metadata);
            s3Client.putObject(por);
        } catch (Exception exception) {

            result.setErrorMessage(exception.getMessage());
        }

        return result;
    }

    protected void onPostExecute(S3TaskResult result) {

        dialog.dismiss();

        if (result.getErrorMessage() != null) {

            displayErrorAlert(
                    SubmitActivity.this
                            .getString(R.string.upload_failure_title),
                    result.getErrorMessage());
        }
    }
}

protected void displayErrorAlert(String title, String message) {

    AlertDialog.Builder confirm = new AlertDialog.Builder(this);
    confirm.setTitle(title);
    confirm.setMessage(message);

    confirm.setNegativeButton(
            SubmitActivity.this.getString(R.string.ok),
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {

                    SubmitActivity.this.finish();
                }
            });

    confirm.show().show();
}

private class S3TaskResult {
    String errorMessage = null;
    Uri uri = null;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public Uri getUri() {
        return uri;
    }

    public void setUri(Uri uri) {
        this.uri = uri;
    }
}

}

Here is my log cat error:

A: Try this:
Uri uriImg =Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ "/Images/img1.jpg");

    PutObjectRequest por = new PutObjectRequest( Constants.getPictureBucket(),

    Constants.PICTURE_NAME, new java.io.File( uriImg) );
    s3Client.putObject( por );

I hpoe this help:


text:
Q: If $u_n \rightharpoonup u$ in $L^2(0,T;L^2)$ and $u_n$ bounded in $L^\infty(0,T;L^2)$, does $u_n(t) \rightharpoonup u(t)$ in $L^2(\Omega)$ a.e. $t$? Let $u_n$ converge weakly to $u$ in $L^2(0,T;L^2(\Omega))$ and let $u_n$ be bounded in $L^\infty(0,T;L^2(\Omega))$.
Is it true that $u_n(t) \rightharpoonup u(t)$ in $L^2(\Omega)$ (weakly) for a.a. $t$?
It is true that $u_n(t) \rightharpoonup v(t)$ for some $v(t) \in L^2(\Omega)$, but I don't know how to identify.


text:
Q: How to control floating point precision when `Export`ing to obj format? Suppose we have a MeshRegion that we want to export to an obj file with, say double precision. Is that possible with Export? And how would we do that? The documentation on "OBJ" does not list any options. I am asking explicitly about Export. Of course, I could write my own OBJ exporter, but this would be somewhat awkward. (I've actually done it already.)
The default seems to export only about 6 decimal digits as the following example is supposed to show:
R = MeshRegion[
   {{0., 0., 0.}, {Sqrt[2.], 0., 0.}, {0., Sqrt[2.], 0.}},
   Triangle[{{1, 2, 3}}]
   ];
file = FileNameJoin[{$TemporaryDirectory, "a.obj"}];
Export[file, R];
MeshCoordinates[Import[file]] - MeshCoordinates[R]

{{0., 0., 0.}, {-3.60048*10^-6, 0., 0.}, {0., -3.60048*10^-6, 0.}}

A: Don't have the time to fully answer this yet, but here's a debug tool I developed previously. First off we can figure out how OBJ is exported
getFormatExportData["OBJ"]

{"FormatName" -> "OBJ", "DefaultElement" -> "Graphics3D",
 "DocumentedElements" -> None, "Function" -> System`Convert`OBJDump`ExportOBJ,
 "FunctionChannels" -> {"Streams"}, "HiddenElements" -> None,
 "Options" -> {"InvertNormals", "VerticalAxis", "Comments"},
 "Sources" -> \
{"/Applications/Mathematica.app/Contents/SystemFiles/Kernel/SystemResources/\
MacOSX-x86-64/Convert/Common3D.mx",
   "/Applications/Mathematica.app/Contents/SystemFiles/Kernel/SystemResources/\
MacOSX-x86-64/Convert/OBJ.mx"}, "BinaryFormat" -> True,
 "File" -> "/Applications/Mathematica.app/Contents/SystemFiles/Formats/OBJ/\
Export.m"}

Then we get the defs for that func (you may need to load the .mx first)
System`Convert`OBJDump`ExportOBJ // GeneralUtilities`PrintDefinitionsLocal

ExportOBJ[strm_, expr_, opts___] := Block[
    {res, nopts, method, a, expr1, obj},
    nopts = Flatten @ {opts};
    method = ("ImportExportMethod" /. nopts) /. {"ImportExportMethod" -> $ImportExportMethod};
nopts = DeleteCases[nopts, "ImportExportMethod" -> _];
a = Flatten[expr /. {RuleDelayed -> List}];
nopts = Union @ Flatten @ Join[nopts, Most @ a];
nopts = Select[nopts, Function[Equal[Head @ #, Rule]]];
obj = Last @ a;
expr1 = "Graphics3D" -> obj;
res = dispatchExportOBJ[method, strm, expr1, nopts];
res /; UnsameQ[res, $Failed]
];

Which means it's handled by dispatchExportOBJ and so looking at those defs we get back to either System`Convert`OBJDump`LegacyExportOBJ or System`Convert`OBJDump`ImprovedLgacyExportOBJ, the latter of which seems to delegate to GeometryTools`WGTAssimpExport and the former of which is just a bunch of WriteString calls which could be modified to have higher precision.
Can't get you to a full solution at this point in time though.


text:
Q: How to "insert" a date in the table which is 750 days before current date? I want to insert date in a table which is 750 days before the current date.

A: Use two simple functions:
CURDATE()
DATE_ADD()
Reference: MySQL Date and Time functions MySQL DATE_ADD() Function
create table dtTable (col datetime);
insert into dtTable values
(curdate()),
(date_add(curdate(), interval -750 day));

DB fiddle


text:
Q: Coding Bot, using Proxy over http or https i want to program a bot with proxies. The bot should buy things. For this it is important that he types in some user accounts and passwords. My problem here is that I don't know if it is problematic to use http-proxies. I red something about that http communication is not safe and the messages are not encoded. So everyone can see my username and my password. Am I right?
Does anyone have some tips or suggestions?


text:
Q: VIM: Indent and space within braces I'm trying to figure out a way to do the following since I've been doing a lot of javascript development.
given the following line:
var someFunc = function() {};

into:
var someFunc = function() {
  // proper indenting -- cursor placed here
};

I would like like to have vim do this from insert mode by just pressing the enter key.  It would be easy to remap the enter key for the actual spacing, but the issue that I'm finding is checking to make sure I'm within the braces.
Any help would be great!
Thanks!

A: There are many ways to do that. And many similar questions here and on superuser.
Supposing your cursor is there and you are in insert mode:
var someFunc = function() {|};

this mapping would do what you want:
inoremap <C-Return> <CR><CR><C-o>k<Tab>

Supposing your cursor is elsewhere on the line and you are still in insert mode, this mapping would work:
inoremap <C-Return> <Esc>$T{i<CR><CR><C-o>k<Tab>

Because it is more generic, this second mapping would provide a good solution to your immediate problem.
But you could also use a plugin like DelimitMate (there are others) that inserts the closing bracket and does the "bracket opening" for you.
Snippets (SnipMate (original, fork), UltiSnips and others) are also useful: typing fun followed by <Tabs> is certainly a nice way to write a complete function definition stub.


text:
Q: How to create an SSH in gcloud, but keep getting API error I am trying to set up datalab from my chrome book using the following tutorial https://cloud.google.com/dataproc/docs/tutorials/dataproc-datalab.  However when trying to set up an SSH tunnel using the following guidelines https://cloud.google.com/dataproc/docs/concepts/accessing/cluster-web-interfaces#create_an_ssh_tunnel I keep on receiving the following error.

ERROR: (gcloud.compute.ssh) Could not fetch resource:
   - Project 57800607318 is not found and cannot be used for API calls. If it is recently created, enable Compute Engine API by visiting https://console.developers.google
  .com/apis/api/compute.googleapis.com/overview?project=57800607318 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our sy
  stems and retry.

The error message would lead me to believe my "Compute Engine API" is not enabled. However, I have double checked and "Compute Engine API" is enabled.
Here is what I am entering into the cloud shell
gcloud compute ssh ${test-cluster-m} \
    --project=${datalab-test-229519} --zone=${us-west1-b}  -- \
    -4 -N -L ${8080}:${test-cluster-m}:${8080}

A: The ${} is for accessing the local environment variable. You set them in the step before with:
export PROJECT=project;export HOSTNAME=hostname;export ZONE=zone;PORT=number

In this case would be:
export PROJECT=datalab-test-229519;export HOSTNAME=test-cluster-m;export ZONE=us-west1-b;PORT=8080

Either try this:
gcloud compute ssh test-cluster-m \
    --project datalab-test-229519 --zone us-west1-b  -- \
    -D 8080 -N

Or access the enviroment variables with:
gcloud compute ssh ${HOSTNAME} \
    --project=${PROJECT} --zone=${ZONE}  -- \
    -D ${PORT} -N

Also check the VM you are trying to access is running.


text:
Q: There's only one other sth I have seen this sentence as, "Looks like there's only one other doorway. "
(Does it mean that there are two doorways? )

A: Not necessarily!
People might have come across five doorways that did not meet their expectations (too small, too narrow, too dark) and remark that there is just one further doorway to look at:

Looks like there's only one other doorway (that might be a suitable entrance).

In the same way, people often remark:

There's only one other possibility.

That doesn't mean that there is a total of two possibilities. It just means that all other possibilities have been excluded. In this sense, it's the same as saying: There's only one more possibility.

A: Yes, it typically means there are two doorways.
You would not need to specify one other doorway if there were only one at all, also, you would not say one other doorway if 6 total doorways existed.
Imagine you are lost in a big castle. You enter a room [through a doorway]. Trying to figure out where to go, you only see one other doorway, meaning there is only one new direction you can go. This is based off of the assumption that you are not trying to go back through the door you just came out of.


text:
Q: My first app. Error: Invalid start tag LinearLayout. Why? It was working perfectly but then I made some minor edits and now it isn't working... Here's the main layout xml file... It gives an error in line 3.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="6">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="2"
            android:background="#FFFF00"
            android:text="@string/yellow"
            android:textColor="#FFFFFF"
            android:gravity="center_horizontal"
            />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:background="#FFFFFF"
            android:text="@string/helo"
            android:textColor="#000000"
            android:gravity="center_horizontal"
            />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:background="#FFFF00"
            android:text="@string/yellow"
            android:textColor="#FFFFFF"
            android:gravity="center_horizontal"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="4">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:text="@string/blue"
            android:layout_weight="3"
            android:textColor="#FFFFFF"
            android:background="#0000FF" />

        <TextView
            android:background="#FFFFFF"
            android:text="@string/helo"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:textColor="#000000"
            android:layout_weight="1" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:textColor="#FFFFFF"
            android:text="@string/yellow"
            android:background="#FFFF00" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="@string/blue"
            android:background="#0000FF"
            android:textColor="#FFFFFF" />
    </LinearLayout>
</LinearLayout>

A: I think that you have your file in the wrong directory. The layout file should be in a res/layout/ directory within your project. My guess is that you have it in some other res/ directory.

A: Try @CommonsWare's suggestion. If that doesn't work, try deleting the error messages in Eclipse. (i.e. right-click and select delete.) I often find I fix a problem in XML layouts but the IDE doesn't notice, and keeps reporting the error preventing me from compiling. Just deleting the error message can fix this in this case. If that doesn't work, try making a clean build.


text:
Q: Binding problems using Angularjs I am trying do a dynamic bind a < tabset> based on the selected value of dropdownlist.
Here is my app.js
var app = angular.module('app',['ui.bootstrap']);
app.controller('tabCtrl',function($scope,$http){
    $scope.countryList=[{name:'Canada',id:'ca'},{name:'United States',id:'us'}];
    $scope.selectedCountry =$scope.countryList[1].id;
    $scope.init = function() {
       $scope.countries =[{countryName:"ca"},{countryName:"us"}];
       $scope.countries[0].tabs=[{title:"CA Title 1"},{title:"CA Title 2"}];
       $scope.countries[1].tabs=[{title:"US Title 1"},{title:"US Title 2"}];
    };
    $scope.switch = function(){
        console.log($scope.selectedCountry);
    }
});

And this is my jsp page.
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

    <link href="<c:url value="/resources/style/bootstrap.min.css" />" rel="stylesheet">
    <title></title>

    <form name="frm" ng-submit="submit()" data-ng-init="init()">

            <tabset>
                <tab ng-repeat="t in c.tabs" heading="{{t.title}}">

                </tab>
            </tabset>

        <button class="btn btn-primary" type="submit">Submit</button>
    </form>

I have two bindings, one is for dropdownlist, one is for tabset.
My problem is if I add < select >, then my tabset does not show up..
Please help.
Thank you

A: This is because ng-options tracks by object reference by default.  If you want to track by id then you should add the following track by clause:
ng-options="c.id as c.name for c in countryList track by c.id"

Then, when you initialize the selectedCountry you need an object with an id property:
$scope.selectedCountry = { id: $scope.countryList[1].id }

Otherwise, your filter ({countryName:selectedCountry}) is not matching anything in the countries array.  This causes <tabset> not to render.

A: Please make sure that you close select tag
<select ng-model="selectedCountry" ng-options="c.id as c.name for c in countryList" ng-change="switch()"></select>

Working demo below

var app = angular.module('app', ['ui.bootstrap']);

app.controller('tabCtrl', function($scope, $http) {
  $scope.countryList = [{
    name: 'Canada',
    id: 'ca'
  }, {
    name: 'United States',
    id: 'us'
  }];
  $scope.countries = [{
    countryName: "ca"
  }, {
    countryName: "us"
  }];
  $scope.selectedCountry = $scope.countryList[1].id;
  $scope.init = function() {

    $scope.countries[0].tabs = [{
      title: "CA Title 1"
    }, {
      title: "CA Title 2"
    }];
    $scope.countries[1].tabs = [{
      title: "US Title 1"
    }, {
      title: "US Title 2"
    }];
  };
  $scope.switch = function() {
    console.log($scope.selectedCountry);
  }
});

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <select ng-model="selectedCountry" ng-options="c.id as c.name for c in countryList" ng-change="switch()"></select>

    <form name="frm" ng-submit="submit()">

        <tabset>
          <tab ng-repeat="t in c.tabs" heading="{{t.title}}">

          </tab>
        </tabset>

      <button class="btn btn-primary" type="submit">Submit</button>
    </form>


text:
Q: Get post from facebook page via graph api and post it on other page Is there any way to get posts from pages feed and post it on other page like
Get post from Ladbible page and post it on my page

A: Sure. Execute GET
graph.facebook.com/theladbible/feed?fields=id&access_token=ACCESSTOKEN
That will give you a list of posts. eg
data: [
{
created_time: "2018-01-26T01:20:00+0000",
message: "This is so heartwarming ❤ ELLE",
id: "199098633470668_4420027538044402"
},
{
created_time: "2018-01-26T00:45:00+0000",
message: "It was the Twitter equivalent of a Rock Bottom and the
People's Elbow ",
id: "199098633470668_4420692437977912"
}]

You will be looking at the ID field which is in the form pageid_postid. You just want the post id so trim the page id_ to be left with just postid.
Then execute POST
graph.facebook.com/yourpageid/feed?link=https://www.facebook.com/ladbible/posts/POSTID&access_token=PAGEACCESSTOKEN
and that will result in you "sharing" the post from ladbible to your page.


text:
Q: Boundary value problem $u'(x)$ For this problem:

We have this graph:
What I am confused is what should $u'(0)$ and $u'(1)$ be?
1) For $u'(0)$ , the solution is $u'(0) = \frac{u_2-u_1}{\Delta x}$ , but why is it not $u'(0) = \frac{u_1-u_0}{\Delta x}$???
2) Same thing as $u'(1)$ , the solution is $u'(1) = \frac{u_4-u_3}{\Delta x}$ , but why is it not $u'(0) = \frac{u_5-u_4}{\Delta x}$???


text:
Q: Please explain output #include<stdio.h>

int main(void)
{
    int a=-3,b=5,c;
    c=a|b;
    printf("%d ",c);
    c=a&b;
    printf("%d ",c);
}

The output is -3 5, please explain how?

A: To understand the output, you need to become familiar with the Two's Complement which is used to represent negative binary numbers. The conversion from +x to -x is actually quite easy: Complement all bits and add one.
Now just assume your ints are of length 8 bits (which is sufficient to examine 5 and -3):
5: 0000 0101
3: 0000 0011 => -3: 1111 1101

Now lets take a look at the bitwise or:
1111 1101 | 0000 0101 = 1111 1101

Exactly the represantation of -3
And now the bitwise AND:
1111 1101 & 0000 0101 = 0000 0101

Exactly the binary representation of 5

A: It helps when you look at the binary representations alongside each other:

*

*-3 == 1111 1111 1111 1101

*+5 == 0000 0000 0000 0101
The thing to understand is that both | and & will leave a bit alone if it has the same value on both sides. If the values are different (ie one operand has a 0 at that position and the other has a 1), then one of them "wins", depending on whether you're using | or &.
When you OR those bits together, the 1s win. However, the 5 has a 0 in the same position as the 0 in -3, so that bit comes through the OR operation unchanged. The result (1111 1111 1111 1101) is still the same as -3.
When you do a bitwise AND, the zeroes win. However, the 1s in 5 match up with 1s in -3, so those bits come through the AND operation unchanged. The result is still 5.

A: Binary of 5 --is--> 0000 0101
3 --> 0000 0011 -- 1's Complement --> 1111 1100 -- 2's Complement (add 1) --> 1111 1101 == -3. This is how it gets stored in Memory.
Bitwise OR Truth Table:
           p OR q

p     ||    q      ||   p | q
T(1)  ||    T(1)   ||     T(1)
T(1)  ||    F(0)   ||     T(1)
F(0)  ||    T(1)   ||     T(1)
F(0)  ||    F(0)   ||     F(0)

1111 1101 | 0000 0101 = 1111 1101 == -3
Bitwise AND Truth Table:
          p AND q

p     ||    q      ||   p & q
T(1)  ||    T(1)   ||     T(1)
T(1)  ||    F(0)   ||     F(0)
F(0)  ||    T(1)   ||     F(0)
F(0)  ||    F(0)   ||     F(0)

1111 1101 & 0000 0101 = 0000 0101 == 5
Also, see - What Every Computer Scientist Should Know About Floating-Point Arithmetic.

A: Get some paper and a writing implement of your choice
Write out -3 and 5 in binary  ( See twos complement for how to do negative numbers)
hint: | means OR,  & means AND

A: -3 = 0xFFFD =  1111 1111 1111 1101   5 = 0101 so the bitwise or does not change the first argument ( just overlap one with ones ) and results is still -3
The bitwise and takes the coomon ones between 1101 and 0101 that is 0101=5 :) no reason to consider all the trailing one in -3 since 5 = 0000 0000 0000 0101

A: If you know all about 2's complements, then you should know

*

*how to write out 3 and 5 in 2's   complement as bit31 bit32 ... bit3n and bit51 bit52 .. bit5n

*how to compute the result  of bit3i | bit5i  for i = 0 ... n

*how to convert the result back to base 10

That should give you your answer for the first, do the same with & for the second.

A: Ever hear of DeMorgan's law...??? The hint is in the linky, it is the table that epitomises and embodies the raw cold truth of logic that is pinned into the syntaxes of major language compilers...
Even more worrying is the fact that you don't have the basic CS101 knowledge and posting this question (Sorry if you take this to be condescending but am not), I genuinely cannot believe you're looking at a C code and not told anything about two's complements, bitwise logic... something is very wrong here... If your college lecturer has not told you any of it, said lecturer should not be lecturing at all and find another job.... sigh


text:
Q: Internet explorer 11 adding random styles to elements, etc I have a couple of pages with tables containing checkboxes in the first column, in internet explorer 11 the table appears like this:
Some images are changed, some removed, checkboxes change colour, etc.

but in chrome and firefox it appears like this, as it should:

When inspecting the source in IE11 it all looks fine, sometimes the colours of the checkboxes change when i move the mouse over an unrelated element, all very strange.
Update - the same thing happens on other computers in my office when they have IE11 installed
Update - Running IE11 on Windows 8.1
Any ideas?

A: This sounds like a "common" internet explorer rendering-artifact-bug. (I couldn't find a good article for it right now).
Almost all Internet Explorer's have problems with elements having a layout or not. A simple fix is usually to add a position: relative; to one or some of the parent elements (don't ask exactly which one)...

A: *

*It was a same issue with older MSIEs, when I moved the window outside of the screen, then back, the background color just disappeared (during the window moving, strange). MSIE "supports" two modes, and the standard mode can be triggered by defining any position/size attribute. The best way is to define something which has no effects, e.g. zoom to 1.

*Maybe you should set different HTML header for select the proper rendering mode.
If none of above works, there are plenty of MSIE-tricks yet!


text:
Q: How to copy one storage account's container's blobs to another storage account's container's blobs I have two storage accounts(storage1) and (storage2) and both of them have containers called data.
Now, storage1's data contains folder called database-files which contains lots of folders recursively. I mean it's kind of huge.
What I am trying to do is I want to copy database-files and everything that's in it from storage1's data container to storage2's data container. Note: both storage accounts are in the same resource group and subscription.
Here is what I've tried:
az storage blob copy start-batch --source-account-name "storage1" --source-container "data" --account-name "storage2" --destination-container "data"
This worked fine, but The problem is time it takes is ridiculously big and I can't wait this much because I want to do this command for one of my release . Which means that i need this as soon as fast, so that my deployment happens fast.
Is there any way to make it faster? maybe zip it/copy it/unzip it? Even If I use AzCopy, I have no idea how it's going to help with timing. All it helps is it doesn't have point of failure and also I have no idea how to use it via azure cli.
How can I proceed?


text:
Q: Two factor authentication with ssh.net I am trying to connect from a Windows app to a unix server, to run some commands (automating checks on server status).  I am using the ssh.net library, and have this code to connect to the server:
using (SshClient ssh = new SshClient("myserver.univ.edu", "myusername", "My!maginaryPa55wrd"))
{
    ssh.Connect();
    var result = ssh.RunCommand("df -h");
    LogText.Text = result.Result;  // puts result of command into multiline textbox
    ssh.Disconnect();
}

But when I run this, it times out on the connect.  I am guessing this is because the server requires two factor authentication.  When I log into it with Putty, it will prompt for username and password, it then prompts for a choice of factors ... enter a passcode or "1" for Duo push to xxx-xxx-1212 or "2" for phone call to xxx-xxx-1212.
The SSH.net library says it supports two-factor authentication, but I have searched all over for a way to do it, and I am coming up empty.  Any clues as to how to solve this, I'd appreciate it.

A: The problem is that you don't have two factor authentication, you have single factor and a bunch of interactive options, which is non-standard and not supported by ssh.net. It's not expecting to have to make choices.
To make this work, you would need to modify the ssh.Net code, or better, setup Public Key Authentication with the remote servers, in which case it won't need a password or 2FA.
Any reasonable size organization almost certainly has PKI setup. You would need to check with the admins and see about getting your Public Key added to the servers you'll be checking.
ssh.Net supports public key auth and would eliminate all the problems you're having.


text:
Q: iCloud sharing among other users From what i know, iCloud is like a personal storage and you uses your own Apple ID for it.
What i want to ask is that, is it possible for users to store for example an image and be shared with other users?
Which means something like DropBox. You upload files into your DropBox account and there will be a url that allows other people to download the file.
Does iCloud has this kind of function?

A: Probably better answered on https://apple.stackexchange.com/.
However, as of right now, the answer is no. iCloud isn't a multi-user file sharing service. The only way to share documents, photos, or other data is to email, tweet, or MMS a copy.

A: Just out of curiosity ... they seem to be sharing iClouds ... how does this work or does apple support this now ?
http://www.busymac.com/busycal/userguide/index.html

A: It looks like you can share calendar data through iCloud. Don't know about any other apps.
http://www.busymac.com/busycal/userguide/caldav-sharing.html


text:
Q: Display base64 image HTML from source Is it possible to display a base64 image in html from a textfile containing the information?The only way I know is to paste the whole content in html.
for instance:

Taken from wikpedia

Maybe I have to use JS?

A: 'use strict';

 const fs = require('fs');

 let buff = fs.readFileSync('test-image.png');
 let base64data = buff.toString('base64');

 console.log('Image converted to base 64 is:\n\n' + base64data);

Have you ever use NodeJs? If you don't know you have to install it. (https://nodejs.org/it/)
You can put where you want the output string also inside the attribute src of the tag img.


text:
Q: green or white screen with processing + kinect I am in win7 x64 Pro
Kinect xbox 360 is connected and samples (openNI and NITE) run well. When i use Processing 2.1, sketch with kinect  run without error notification but there nothing on screen and he is gray or white... Yet all simple processing samples (without kinect) run well...What is wrong? I'm disappointed
intalled :
OpenNI-Win32-1.5.7-Dev.msi
NITE-Win32-1.5.2-Dev.msi
SensorKinect093-Bin-Win32-v5.1.2.1.msi
SimpleOpenNI 1.96
KinectSDK-v1.7
Ms Visual Studio 2012
Processing 2.1
I tried
OpenNIx64-1.5.7-Dev.msi
NiTE-Windows-x64-2.0.0
Sensor-Win64-5.1.6.6
but I have same problem
kinect run well (all samples from openNI and Nite) but whith Processing 2.1 (or 2.0.3 and 1.5.1) It still doesn't work : nothing on screen (gray or white) without notification error.
All simple processing samples (without kinect) run well...
Thank you for your help

A: I would recommend that you use the J4K (Java for Kinect) library in Processing. J4K is an open-source library and communicates with the native Microsoft Kinect SDK. You can download the j4k-processing.zip from here: j4k-processing.zip
There is a Green-Screen example in the examples folder (you need to unzip the j4k-processing.zip) called example5_basicAugmentedReality. This example shows you in the middle of a simple 3D virtual scene. In addition there are other examples for 2D interaction, reading the values of the accelerometer, etc.

A: Try to use SimpleOpenNI 0.27 on Processing 1.5.1
You can download SimpleOpenNI 0.27 from this link
if it didn't solve your problem. You should write more detail about your system that you use such as the version of SimpleopenNI, Kinect driver, etc


text:
Q: What intent should be used to open the Call accounts screen in Android? I am building an app with VoIP, using a system managed ConnectionService. When registering the PhoneAccount, the user needs to manually enable the PhoneAccount somewhere in the Android system settings (or Dialer app settings?). If not enabled, the TelecomManager will not route VoIP calls.
How can I send the user to this "Call accounts" settings screen using an intent? I do not want the user to have to find this setting on his own.

A: After some searching, I found this in a Google Group:
if (Build.MANUFACTURER.equalsIgnoreCase("Samsung")) {
    Intent intent = new Intent();
    intent.setComponent(new ComponentName("com.android.server.telecom",
        "com.android.server.telecom.settings.EnableAccountPreferenceActivity"));
    startActivity(intent);
} else {
    startActivity(new Intent(TelecomManager.ACTION_CHANGE_PHONE_ACCOUNTS));
}

https://groups.google.com/forum/#!topic/android-contrib/C7qbnnAGzsk


text:
Q: Lane-Emden. Quasi-linearization method ow to prove this theorem? I have a doubt.
Theroem: Suppose that $w(x,\alpha)$ solved
$\ddot{w}+\frac{2}{x}\dot{w}+\alpha^{2}w=0$ with $w(0)=1$,
$\dot{w}(0)=0$, $w(1)=0$.
Then $v(x,\alpha) := \omega w(x,\alpha)$ solves
$\ddot{v}+\frac{2}{x}\dot{v}+\Theta^{2}v^{n}=0$ with $v(0)=\omega$,
$\dot{v}(0)=0$, $v(1)=0$ provided that
\begin{equation}
  \omega = \left(\frac{\alpha^{2}}{\Theta^{2}}\right)^{1/(n-1)}.
  \end{equation}
Demonstration:

*

*\begin{equation} v(0) = \omega w(0) = \omega 1 = \omega\end{equation}

*\begin{equation} \dot{v}(0) = \omega \dot{w}(0) = \omega 0 = 0\end{equation}

*\begin{equation} v(1) = \omega w(1) = \omega 0 = 0\end{equation}

*Substituting $v=\omega w$ into $\ddot{v}+\frac{2}{x}\dot{v}+\Theta^{2}v^{n}=0$ and cancelling common factors, we obtain $\ddot{w}+\frac{2}{x}\dot{w}+\alpha^{2}w^{n}=0$.

My question is:
$\ddot{w}+\frac{2}{x}\dot{w}+\alpha^{2}w=0$ then $\ddot{w}+\frac{2}{x}\dot{w}+\alpha^{2}w^{n}=0$? I guess not. I can´t demostrate this last part of the theorem.
Referene: Boyd, J. P. (2011). Chebyshev spectral methods and the Lane-Emden problem. Numerical Mathematics: Theory, Methods and Applications, 4(2), 142-157.


text:
Q: Avoid neighbor fragment creation in Actiobar nav mode Tabs or Strips? I'm using actionbar navigation mode Tabs and I'm having 3 tabs using async tasks that loads stuff from the internet.
When launching the activity the fragments next to the current one are created thus launching their own async task.
Is there any way to provente neighbor fragments creation?


text:
Q: How can I display a font awesome glyph in XAML/C# I have tried many things in Visual Studio, but I still can not display a glyph.

*

*Do I need to add a NuGet package? Which?

*Do I need a 'using ...;' in C#?

*Do I need a 'xmlns:...' in XAML?

*Should I display it with a "Label"?

I know in HTML, you just add a class to your element.  But I am stumped in XAML.
(It's cross-platform, right?)
This should a simple thing but I can not get any answers to function.  Please provide an answer if you can do this and answer all points.

A: There is a correct plugin for Xamarin.Forms. This plugin not only has FontAwesome Font.
According to this example in github you must do the following:
<StackLayout Orientation="Horizontal">
        <iconize:IconLabel FontSize="20" Text="{Binding Key}" TextColor="Green" VerticalTextAlignment="Center" />
</StackLayout>

[UPDATE]
On request from user3247130 I leave the complete example:
From Visual Studio or Xamarin Studio, install the following packages:

*

*Xam.Plugin.Iconize

*Xam.Plugin.Iconize.FontSwesome

*Xam.FormsPlugin.Iconize

In the Android project, MainActivity class, OnCreate() method add:

FormsPlugin.Iconize.Droid.IconControls.Init(Resource.Id.toolbar);
Plugin.Iconize.Iconize.With(new Plugin.Iconize.Fonts.FontAwesomeModule());

In the iOS project, AppDelegate class, FinishedLaunching() method, add similar lines:

FormsPlugin.Iconize.iOS.IconControls.Init();
Plugin.Iconize.Iconize.With(new Plugin.Iconize.Fonts.FontAwesomeModule());

Also, in iOS project, info.plist add

<key>UIAppFonts</key>
<array>
    <string>iconize-fontawesome.ttf</string>
</array>

Now, in your XAML where your have your toolbar, in tag, add

<ContentPage ...
xmlns:iconize="clr-namespace:FormsPlugin.Iconize;assembly=FormsPlugin.Iconize">

and

<iconize:IconLabel Text="fa-search"  />

[UPDATE 2]
This plugin has an issue on UWP platform.
To run this plugin on UWP platform follow these steps:
First, create a folder called Plugin.Iconize.FontAwesome.UWP into %userprofile%\.nuget\packages\xam.plugin.iconize.fontawesome\2.0.0.29-beta\lib\UAP10\
Second, create another folder called Assets into Plugin.Iconize.FontAwesome.UWP folder
Third create anoother folder called Fonts into Assets folder
And finally copy iconize-fontawesome.ttf file (you shouldn't change their name).

Additionally, you have to add a Fonts folder in the Assets folder in your UWP project and then paste the same ttf file
This is not necessary on Android or iOS it is only a issue of the UWP platform

A: Try Plugin.Glypher it has Font Awesome 5 Free/Pro and WeatherIcons support.

*

*Plugin.Glypher.FontAwesome5Free

*Plugin.Glypher.FontAwesome5Pro

*Plugin.Glypher.WeatherIcons
xmlns:fontAwesome5Free="clr-namespace:Plugin.Glypher.FontAwesome5Free;assembly=Plugin.Glypher.FontAwesome5Free"
xmlns:glypher="clr-namespace:Plugin.Glypher;assembly=Plugin.Glypher"

<Label glypher:FontGlyph.Glyph="{x:Static fontAwesome5Free:GlyphList.Fab_Bluetooth}"
       FontSize="Large"
       TextColor="CornflowerBlue" />

<Button glypher:FontGlyph.Glyph="{x:Static fontAwesome5Free:GlyphList.Fab_Bitcoin}"
        FontSize="Large"
        TextColor="IndianRed" />

<Image>
    <Image.Source>
        <FontImageSource Size="32"
                         Color="Orange"
                         glypher:FontGlyph.Glyph="{x:Static fontAwesome5Free:GlyphList.Far_Bell_Slash}" />
    </Image.Source>
</Image>

It's all in shared code. But it depends on Xamarin.Forms (>= 3.6.0.344457)


text:
Q: Insert Process into Queue to work Asynchronously I am trying to make a simple web page in which when we enter the text value in the textbox, and as soon as a user inserts a comma between the two texts, a new button gets generated. When the user presses the enter key, the buttons class should toggle between warning and danger.
I am able to achieve it so I also tried to add a delay, but the problem is all buttons class toggling takes place together and not one by one in a random manner. To create a random toggling sequence I created a random permutation of numbers for it, but since all buttons classes are toggling simultaneously I am not getting the required result.
The required result is that first for one buttons toggling should be completed and then for another button - how can I achieve this?

let element = document.querySelector('.textarea');
let cont = document.querySelector('.groupofbtns');
let lastlen = 0;
const pause = (timeoutMsec) => new Promise(resolve => setTimeout(resolve, timeoutMsec))
async function main(grp) {
// here is the delay I am trying to create between toggling but it is executing for all buttons simultaneously.
    grp.classList.remove("btn-warning");
    grp.classList.add("btn-danger");
    await pause(3 * 1000)
    grp.classList.remove("btn-danger");
    grp.classList.add("btn-warning");
}
element.addEventListener("keyup", function (event) {
    if (event.keyCode === 13) {
        let grp = document.querySelectorAll('.btn')
        let l = grp.length - 1, arr = [];
        console.log(grp.length)
        do {
            let num = Math.floor(Math.random() * l + 1);
            arr.push(num);
            arr = arr.filter((item, index) => {
                return arr.indexOf(item) === index
            });
        } while (arr.length < l);
       // console.log(arr);
        arr.push(0)
        for (let i = 0; i <= l; i++) {

            main(grp[arr[i]])

        }
    }
    else if (event.keyCode === 8) {
        let val = element.value;
        //console.log(val)
        let strArr = val.split(',')
        let b, f;
        let grp = document.querySelectorAll('.btn');
        if (strArr.length > 1) {
            b = strArr;
            while (b[b.length - 1] == "")
                b.pop()
            if (b.length < strArr.length) {
                cont.removeChild(grp[grp.length - 1]);
                lastlen--;
            }
            f = b[b.length - 1];
        }

        if (grp.length == b.length)
            grp[grp.length - 1].innerText = `${f}`;
        else {
            let diff = grp.length - b.length
            let i = 0;
            while (diff > 0) {
                cont.removeChild(grp[grp.length - 1 - i]);
                i++;
                diff--;
                lastlen--;
            }
        }
    }
});
element.addEventListener('input', function (event) {
    let val = element.value;
    //console.log(val)
    let strArr = val.split(',')
    let b, f;
    if (strArr.length > 1) {
        b = strArr;
        while (b[b.length - 1] == "")
            b.pop()
        f = b[b.length - 1];

        if (event.keyCode !== 8) {
            if (strArr.length > lastlen) {
                let butt = document.createElement('button');
                butt.classList.add('btn')
                butt.classList.add('btn-warning')
                //butt.classList.add('container')
                butt.classList.add('active')
                butt.innerText = `${f}`
                cont.appendChild(butt)
                lastlen = strArr.length
                //cont.innerHTML += `<button type="button" class="btns" >${f}</button>`;
            }//element.value = val;
            else {

                let b = document.querySelectorAll('.btn')
                b[b.length - 1].innerText = `${f}`
            }
        }
    }
})
.h
{
    display:flex;
    flex-direction: column;
    width: 50%;
    margin-top:30%;
    align-items: center;
    text-align: center;
}
.lab
{
    color:white;

}
.btn
{
    margin: 0.8% 0.8%;
}
.groupofbtns
{
    width:50%;
    margin-top: 2%;
    align-items: center;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <title>Random color picker</title>
    <link rel="stylesheet" href="randomcolorcss.css">

            Enter your choices here separate them with
                commas, Press
                Enter when you are
                done

            <textarea cols="5" rows="5" class=" textarea form-control" placeholder="Enter Choices here" name="text"
                style="width: fit-content; display: block;"></textarea>


text:
Q: How to compute similarity in quanteda between documents for adjacent years only, within groups? I have a diachronic corpus with texts for different organizations, each for years 1969 to 2019.
For each organization, I want to compare text for year 1969 and text for 1970, 1970 and 1971, etc.
Texts for some years are missing.
In other words,
I have a corpus, cc, which I converted to a dfm
Now I want to use textstat_simil:
ncsimil <- textstat_simil(dfm.cc,
                           y = NULL,
                           selection = NULL,
                           margin = "documents",
                           method = "jaccard",
                           min_simil = NULL)

This compares every text with every other text, resulting in a 2.6+ million lines.
I really only need to compare certain texts with the text immediately above, like this:
TextA
TextB
TextC
TextD (has NA)
TextE
So, I want the jaccard statistic for
A and B
B and C, and (since some have NA values)
D and E
I am curious about the y =  in textstat_simil
Quanteda package says

"y is an optional target matrix matching x in the margin on which the
  similarity or distance will be computed."

It is not clear to me what this means.
Does it mean I can create two different data frames
A
B
C
D
E
and
B
C
D
E
F
So that I will get a similarity statistic for
A and B
B and C
and so forth?
Or is there a better way to do this?
Edited starting here...
I converted to a data.frame:
df <- convert(dfm.cc, to = "data.frame")

I did bind_cols to add docvars and token counts (2,405 columns -- short texts).
I have isolated the initial texts in a series, e.g.,
OrgA 1970, 1st_in_Series_Yes, TokCount 1...etc.
OrgA 1971,  1st_in_Series_No,  TokCount 1...etc.
OrgA 1972,  1st_in_Series_No, TokCount 1...etc.
OrgA 1973, NA
OrgA 1974,  1st_in_Series_Yes, TokCount 1...etc.
OrgZ 1975,  1st_in_Series_No, TokCount 1...etc.
So as not to compare
OrgA 1973 NA with OrgA 1972
or
OrgA 1974 with OrgA 1973
Manually computing Jaccard should work from here, but there's probably a smarter way. Please share solutions. Thanks.

A: Interesting question.  I don't have a reproducible example to work with, but I think I can create one using the built-in inaugural corpus dataset.  Here, I will use the document variables Year for the time variable, and the unique president (full) name as an analog for your organization (since you don't want year-to-year comparisons of different organizations.  So if you substitute your organization and time variable for the ones below this should work.
Note that I make the outer "loop" an lapply, and the inner is an actual loop, but there are clever ways to make the inner part also an lapply.  Here I've left it as a for loop for simplicity.
First, get a unique name, since some (different) presidents share the same last names.
library("quanteda")
## Package version: 2.0.1

data_corpus_inaugural$president <- paste(data_corpus_inaugural$President,
  data_corpus_inaugural$FirstName,
  sep = ", "
)
head(data_corpus_inaugural$president, 10)
##  [1] "Washington, George" "Washington, George" "Adams, John"
##  [4] "Jefferson, Thomas"  "Jefferson, Thomas"  "Madison, James"
##  [7] "Madison, James"     "Monroe, James"      "Monroe, James"
## [10] "Adams, John Quincy"

If we make that set unique, then we can iterate across the unique presidents to subset them one at a time. (This is what you will do with each of your organizations.)  We can do this using corpus_subset() before creating the dfm, and within that, select just adjacent year pairs.  The sorting of the years means that the i and i+1 will be adjacent.  Most of the presidents have only a pair of years, but Franklin Roosevelt who had four inaugural addresses has three pairs.  And single-term presidents, such as Carter 1977, do not have any pairs.
simpairs <- lapply(unique(data_corpus_inaugural$president), function(x) {
  dfmat <- corpus_subset(data_corpus_inaugural, president == x) %>%
    dfm(remove_punct = TRUE)
  df <- data.frame()
  years <- sort(dfmat$Year)
  for (i in seq_along(years)[-length(years)]) {
    sim <- textstat_simil(
      dfm_subset(dfmat, Year %in% c(years[i], years[i + 1])),
      method = "jaccard"
    )
    df <- rbind(df, as.data.frame(sim))
  }
  df
})

Now when we join them, you can see that we have computed only what we need.
do.call(rbind, simpairs)
##          document1       document2    jaccard
## 1  1789-Washington 1793-Washington 0.09250399
## 2   1801-Jefferson  1805-Jefferson 0.20512821
## 3     1809-Madison    1813-Madison 0.20138889
## 4      1817-Monroe     1821-Monroe 0.29436202
## 5     1829-Jackson    1833-Jackson 0.20693928
## 6     1861-Lincoln    1865-Lincoln 0.14055885
## 7       1869-Grant      1873-Grant 0.20981595
## 8   1885-Cleveland  1893-Cleveland 0.23037543
## 9    1897-McKinley   1901-McKinley 0.25031211
## 10     1913-Wilson     1917-Wilson 0.21285564
## 11  1933-Roosevelt  1937-Roosevelt 0.20956522
## 12  1937-Roosevelt  1941-Roosevelt 0.20081549
## 13  1941-Roosevelt  1945-Roosevelt 0.18740157
## 14 1953-Eisenhower 1957-Eisenhower 0.21566976
## 15      1969-Nixon      1973-Nixon 0.23451777
## 16     1981-Reagan     1985-Reagan 0.24381368
## 17    1993-Clinton    1997-Clinton 0.24199623
## 18       2001-Bush       2005-Bush 0.24170616
## 19      2009-Obama      2013-Obama 0.24739195

For computing similarity you might want to add more options to the dfm creation line - I only removed punctuation here but you could also remove stopwords, numbers, etc. if that is what you want.


text:
Q: How to get intersection of rows from two tables by using Matlab or Excel? I have been googling but so far results found not fully match to my need. If someone has posted answer for the same question, can someone let me know ? Thank you very much.
I have two tables from two excel files that one contains only numerical values and the other contains both txt and numerical values. For example file1.xlsx has only a column vector of studentid which are integer number such as,
1
3
5
11
20 ....

And the file2.xlsx contains a worksheet as:
 studentID   Name     score    email
 1           Cassie   60       test@gmail.com
 2           John     100      john@gmail.com
 3           Marry    80       ...
 4           Bob      70       ...
 5           Kevin    99       ....

I would like to find rows of students whose studentID are in the file1.xlsx so the final resulted table should be looked like:
studentID  Name    score  email
1          Cassie  60      test@gmail.com...
3          Marry   80      Marry@gmail.com
5          Kevin   99     kevin@gmail.com
...

I do not have script languages such as SQL or Perl. I know in matlab, there is a interset function, however, it only work with numerical matrix. For my file2.xlsx, it contains both numerical and txt values. I do not want to separate them. And I do not know how to read a excel file into a cellarray either since the table has both numerical and txt parts. If there is anyone who knows how to solve this problem either by using Matlab or Excel is fine with me, I just need to get the final resulted table.
Thank you so very much,

A: In Excel you create a new column in file2.xlsx with a formula:
=MATCH(A2,[\path\file1.xlsx]Sheet1!$A$2:$A$20,0)

where $A$2:$A$20 is a range with student IDs in file1.xlsx. Last 0 means exact match. Distribute this formula to all the rows. The function returns #N/A in rows if ID is not in file1. You can filter those rows out using this column.
For easier filtering you can add ISERROR function:
=NOT(ISERROR(MATCH(A2,[\path\file1.xlsx]Sheet1!$A$2:$A$20,0)))

Then the TRUE will correspond to existing IDs, and FALSE to missing IDs.
If you have additional column in file1.xlsx and want to combine it with data in file2 you can use INDEX function:
=INDEX([\path\file1.xlsx]Sheet1!B$2:B$20,MATCH($A2,[\path\file1.xlsx]Sheet1!$A$2:$A$20,0),1)

Note that MATCH/INDEX combination does not require the data in search column to be sorted, as in case of VLOOKUP.

In MATLAB you can use ISMEMBER function.
Let's say you have imported both files to MATLAB and you have cell arrays file1 and file2. Then you can do:
[~,~,file1] = xlsread('file1.xlsx');
[~,~,file2] = xlsread('file2.xlsx');
[idx2, idx1] = ismember(file2(:,1), file1(:,1));
filtered2 = file2(idx2,:);

To find the rows in file1.xlsx existing in file2.xlsx and sort them in the same order:
idx1(idx1==0) = [];
filtered1 = file1(idx1,:);

If you want to keep the order of rows in file1.xlsx just switch file2 and file1 in the ismember statement.

A: You can try Excels VLOOKUP (english) / SVERWEIS (german) function.
Considering the following layout of your Excel documents:
1.xlsx
 |  A|  B|  C|  D|
1|  1|   |   |   |
2|  3|   |   |   |
3|  5|   |   |   |
4| 11|   |   |   |
5| 20|   |   |   |

2.xlsx
 |  A|  B|   C|      D|
1|  1|  C|  60| a@b.de|
2|  2|  J| 100| b@c.de|
3|  3|  M|  80| c@d.de|
4|  4|  B|  70|       |
5|  5|  K|  99|       |

to populate 1.xlsx with students' details from 2.xlsx assign following formulas to 1.xlsx:
B1: =VLOOKUP($A1;[<PATH_TO_2.xlsx>]<NAME_OF_SHEET_IN_2.xlsx>!$A$1:$D$5;2;TRUE)
B2: =VLOOKUP($A2;[<PATH_TO_2.xlsx>]<NAME_OF_SHEET_IN_2.xlsx>!$A$1:$D$5;2;TRUE)
...
C1: =VLOOKUP($A1;[<PATH_TO_2.xlsx>]<NAME_OF_SHEET_IN_2.xlsx>!$A$1:$D$5;3;TRUE)
C2: =VLOOKUP($A2;[<PATH_TO_2.xlsx>]<NAME_OF_SHEET_IN_2.xlsx>!$A$1:$D$5;3;TRUE)
...
D1: =VLOOKUP($A1;[<PATH_TO_2.xlsx>]<NAME_OF_SHEET_IN_2.xlsx>!$A$1:$D$5;4;TRUE)
D2: =VLOOKUP($A2;[<PATH_TO_2.xlsx>]<NAME_OF_SHEET_IN_2.xlsx>!$A$1:$D$5;4;TRUE)
...

VLOOKUP searches for occurrences of first parameter ($A1, ..) in sheet specified by second parameter and copies n-th value (3rd param) in matrix specified in 2nd param. 4th boolean param specifies whether exact match is required.
you need to replace '< PATH_TO_2.xlsx >' and '< NAME_OF_SHEET_IN_2.xlsx >' with correct values, '[]' and '!' must stay in place
further explanation: http://www.techonthenet.com/excel/formulas/vlookup.php
good luck :)


text:
Q: How to solve "Element project must be declared" issue in Android Studio? I usually run my apps without any kind of problems. But, recently, I faced this problem in colors.xml : "Element project must be declared"..... How can I solve it???
oi

A: This color file in your picture is not so related to colors.xml - it should look like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#795548</color>
    <color name="colorPrimaryDark">#6B4A3E</color>
    <color name="colorAccent">#FF000000</color
</resources>


text:
Q: Many to many navigation property is null I have these two classes in my EF 6 code-first model:
public class Category {

    public int CategoryId { get; set; }

    [Required, MaxLength( 128 ), Index( IsUnique = true)]
    public string CategoryName { get; set; }

    public string Description { get; set; }

    public virtual ICollection<Article> Articles { get; set; }
}

public class Article {

    [DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
    public int ArticleId { get; set; }

    [Required, MaxLength( 128 ), Index( IsUnique = true )]
    public string ArticleName { get; set; }

    public virtual ICollection<Category> Categories { get; set; }

    public string Description { get; set; }

}

I have this code in my data access layer to create a new article:
public Article AddArticle( string articleName, int[] categoryIds ) {
    if ( string.IsNullOrWhiteSpace( articleName ) )
        throw new ArgumentNullException( nameof( articleName ), Properties.Resources.ArticleNameWasNull );
    if ( categoryIds == null )
        throw new ArgumentNullException(nameof(categoryIds), Properties.Resources.CategoryIdsAreNull );

    using ( var context = new ArticleContext() ) {
        var article = new Article {
            ArticleName = articleName
        };
        foreach ( var category in context.Categories.Where( c => categoryIds.Contains( c.CategoryId ) ) )
            article.Categories.Add( category );
        context.Articles.Add( article );
        context.SaveChanges();
        return article;
    }
}

When I call this method, I get a NullReferenceException on the line in the foreach loop that adds the Category object to the article.Categories collection.
Obviously the Categories collection isn't initialized in the call to new Article().  What am I missing?

A: You can't add an item to a null collection. You need to initialize article.Categories as a new collection.
article.Categories = new List<Category>();

foreach ( var category in context.Categories.Where( c => categoryIds.Contains( c.CategoryId ) ) )
    article.Categories.Add( category );

Alternatively add it where you are creating the object:
var article = new Article {
    ArticleName = articleName,
    Categories = new List<Category>()
};

A: To avoid that kind of exception I always initialize the collection properties in a empty constructor:
public class Article
{
   public Article()
   {
      Categories =new List<Category>();
   }
   //...
}


text:
Q: Cursor jumps around on Macbook Pro mid-2010, without trackpad installed to solve my erratic cursor on my mid-2010 MacBook Pro, I brought my computer to the local apple store and had the trackpad completely uninstalled. Does anybody know what it means for the trackpad to completely uninstalled? Ok, anyways I'm going to post a question I never got a reply to on the apple support page. Here it goes.
Macbook Pro mid 2010 15 inch
Processor: 2.4 GHz Intel Core i5
Memory: 8 GB
Software: Mac OS X Lion 10.7.5
Graphics: NVIDIA GeForce GT 330M 256 MB
Ok all the problems started two years ago, after I bought the computer. For the first four months everything was all dandy until I notices that my cursor behaving erratically, even though I was using a mouse. So I thought that the problem was a bulging battery, even though the trackpad still appeared normal. So using the universal access preferences, I completely turned off the trackpad completely, (using the option to switch off the trackpad when a mouse was in use).
BTW, the mouse was new and corded; used on other computers, it behaved normally.
Another year and a half goes by, and I start encountering another problem. This time the computer would occasionally power off. This occurred randomly, with no preference as to which program or application was more susceptible. In the console it read as a kernel panic, (I had no idea what that meant) and as usual I ignored the problem, blaming it on a faulty battery that would soon need to be replaced. Finally one day I mustered up the courage to go to my peach mac provider and understand the problem.
I was duly shocked to hear green checks all round. Everything was fine in fact (including the battery) expect the trackpad; a problem, which employees assured me, was common enough. Trackpads on my type of macbook pro would occasionally go haywire and just screw up. The estimate for replacement was $170, which was too deep for my pocket, so I politely declined and asked for any other solution. After some prodding, they said they could "unscrew" the trackpad, and I was all ears for this, because I gotten used to working without one. So the trackpad was uninstalled and I returned happy to my house. Also, they told me that a kernel panic was a software issue that could be the fault of the OS X or a third party application.
I forgot to mention, along with the panics, came the general erratic behavior of the cursor. Not as before, where the cursor would go around clicking and dragging mayhem everywhere, but just general skipping around and inaccuracy. So to solve this problem, I bought a new mouse. It was a G100s.
Set to discover the reason behind the kernel panics, I did everything I could to solve the problem. In fact I deleted my entire hard-drive and reinstalled the OS and backed-up the backup. After this, the kernel panics have not yet reoccured (will edit if one does) but the mouse foolishness did. I was afraid to reset the VRAM or whatever you call it, since it also deletes the error log, something that I may want to keep as proof for any techies that may have the solution to the problem.
Once, I started up in safe mode and the mouse worked fine, in fact gloriously accurate, however I was not and could not perform any cpu intensive programs to heat things up. I say this because the mouse problem only occurs after about 30 minutes on the computer. I notice that the general mouse performance is subpar compared to using it on another computer.
If anyone can provide any possible solutions or anything please feel free. And I forgot to include a vital piece of information or something is written in a confusing manner, tell me.

A: I have a similar problem with my 2009 MacBook Pro. I've been told by an aftermarket apple dealer that it is the graphics card. The card is damaged by overheating. The overheating is due an erratic fan. The erratic fan is caused by a damaged logic board.


text:
Q: how to import the excel file to sql database using vb.net? I have a more data in excel file .so i have to import it into sql database using vb.net.can anyone send the source code?

A: Dim ExcelConnection As New

System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\MyExcelSpreadsheet.xlsx; Extended Properties=""Excel 12.0 Xml; HDR=Yes""")
ExcelConnection.Open()

Dim expr As String = "SELECT * FROM [Sheet1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader

Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=MMSQL1; Initial Catalog=DbName; User Id=UserName; Password=password;"
SQLconn.ConnectionString = ConnString
SQLconn.Open()

Using bulkCopy Asd SqlBulkCopy = New SqlBulkCopy(SQLConn)
bulkCopy.DestinationTableName = "TableToWriteToInSQLSERVER"

  Try
    objDR = objCmdSelect.ExecuteReader
    bulCopy.WriteToServer(objDR)
    objDR.Close()
    SQLConn.Close()

  Catch ex As Exception
    MsgBox(ex.ToString)
  End Try
End Using

A: If it's a one-off job, use DTS or SSIS. No code required.
Otherwise, you can open Excel as a data source, suck up its contents and insert into your database.


text:
Q: jquery ui draggable and bxslider not working i have slider in bxSlider, and the item of the slider is draggable using jquery ui.
for better understanding, here is the slider in action http://comicedu.com/htmlcropper/v2/
try to drag the dog in dogs tab to the background (brick) you will see the dog now inside the brick, then move to cats tab, after that click the left arrow then drag the 3rd image and now you will see the draggable is not working, what is wrong with that? i investigate that bxSlider add bx-clone class to the container div.

A: This is just a guess, but it looks like to me, jquery is attaching the drag and drop events first to the 'true' (not cloned) images, then bxslider is creating the clones AFTER jquery has registered the images for drag and drop, so the cloned images aren't being attached to the drag/drop events?
Try loading things in order.
$(function(){
    loadSlider();
    loadDragDrop();
};

function loadSlider{
    //Load the slider
}

function loadDragDrop(){
    //Load the drag/drop
}

OR Attach the drag/drop on page load as you are now, then try re-attaching the drag/drop on this event of the bxslider:
onSlideAfter: function() {},

Hopefully this will force the drag/drop to be added to clones as well since they would have been created by the slider already.
Clones are created to fill in the empty slots in your slider. say your slider can fit 6 images and you have 8 images, 4 clones will be created so when you skip to the second group, the slider is full.
If my guess is way off (and it could be), you can do 2 things to 'quick' fix until a better sloution comes along:

*

*Hide any bx-clone elements with css
.bx-clone { display:none; }

*Make sure you have the correct amount of images to fill the slider. For cats, it looks like you have 10 images, the others are clones, so make the number of cat images 16 so the slider doesn't have to create any clones.


text:
Q: Cypress cucumber - how to run mutiple tags in single comment(in terminal) feature1.feature(file)
@feature1
Scenario:Running first feature file
feature2.feature(file)
@feature2
Scenario:Running second scenario file
Need to run the two feature file using tags in a single comment
tried:npx cypress-tags run -e TAGS='@feature1, @feature2'


text:
Q: Composer symlink dependency of dependency I am trying to work on a subdependency. This is the package structure:
my-project > nova-impersonate > laravel-impersonate.
At first, I just added laravel-impersonate to my require-dev and set dev-master as version, but that clashed with the ^1.2 version in nova-impersonate.
So I also cloned the nova-impersonate, and updated the version to dev-master. I also added both these repos to my composer.json.
"repositories": [
    {
        "type": "path",
        "url": "../laravel-impersonate"
    },
    {
        "type": "path",
        "url": "../nova-impersonate"
    }
],

Upon installing, composer outputs:

Installing lab404/laravel-impersonate (dev-master 05fc39f): Downloading (100%)
Installing kabbouchi/nova-impersonate (dev-master): Symlinking from ../nova-impersonate

So, the laravel-impersonate is not being symlinked, it is being loaded from Github instead.
How can I symlink a dependency of one of my dependencies?
Edit:
I have updated my composer.json according to rob004s comment.
"require": {
    // ...
    "kabbouchi/nova-impersonate": "^1.0",
    "lab404/laravel-impersonate": "dev-master as 1.2"
},
"repositories": [
    // ...
    {
        "type": "path",
        "url": "../laravel-impersonate"
    }
],

In my composer.lock, I can still see the following:
"name": "lab404/laravel-impersonate",
"version": "dev-master",
"dist": {
    "type": "zip",
    "url": "https://api.github.com/repos/404labfr/laravel-impersonate/zipball/05fc39ff90430aaec35553c12d94121356a6af7a",
     "reference": "05fc39ff90430aaec35553c12d94121356a6af7a",
     "shasum": ""
 },


text:
Q: MariaDB 10 replication strange behaviour I have following MariaDB 10 replication setup.
Server A MariaDB 10 (master), Server B MariaDB 10 (master), Server C MariaDB 10 (slave/master), Server D MariaDB 10 (slave).
A and B are getting new data from different sources (Percona Server, AWS RDS) using Tungsten replicator and replicate this data to C. C replicates to D.
My steps:

*

*mysqldump from A and B

*import to C and configure multi-source replication

*mysqldump from C

*import to D configure replication

After a while A and B are getting new data, but this data is not replicating neither to C or D (from C).
If I go to A or B and create fake tables and insert fake data everything replicates up to D.
No errors in mysql error log, no errors in replication status.
What can be possible wrong?

A: Ensure you have --log-slave-updates and --log-bin enabled in the servers.

Normally, a slave does not write to its own binary log any updates
  that are received from a master server. This option causes the slave
  to write the updates performed by its SQL thread to its own binary
  log. For this option to have any effect, the slave must also be
  started with the --log-bin option to enable binary logging. Prior to
  MySQL 5.5, the server would not start when using the
  --log-slave-updates option without also starting the server with the --log-bin option, and would fail with an error; in MySQL 5.6, only a warning is generated. (Bug #44663) --log-slave-updates is used when
  you want to chain replication servers. For example, you might want to
  set up replication servers using this arrangement:
A -> B -> C
Here, A serves as the master for the slave B, and B serves as the
  master for the slave C. For this to work, B must be both a master and
  a slave. You must start both A and B with --log-bin to enable binary
  logging, and B with the --log-slave-updates option so that updates
  received from A are logged by B to its binary log.

Source: http://dev.mysql.com/doc/refman/5.6/en/replication-options-slave.html#option_mysqld_log-slave-updates


text:
Q: using pipes for unique() function Below is the code i used to do a mode imputation for the column status group of the dataset tan1.
How do I rewrite the same using pipes? the unique() function does not seem to work in pipes.
NA_stat <- unique(tan1$status_group[!is.na(tan1$status_group)])

mode <- NA_stat[which.max(tabulate(match(tan1$status_group, NA_stat)))]

tan1$status_group[is.na(tan1$status_group)] <- mode

Also, how do I apply this same process for multiple columns?

A: Here are some examples of determining and imputing the mode in a pipe.
Functions to calculate mode:
library(tidyverse)

# Single mode (returns only the first mode if there's more than one)
# https://stackoverflow.com/a/8189441/496488
# Modified to remove NA
Mode <- function(x) {
  ux <- na.omit(unique(x))
  ux[which.max(tabulate(match(x, ux)))]
}

# Return all modes if there's more than one
# https://stackoverflow.com/a/8189441/496488
# Modified to remove NA
Modes <- function(x) {
  ux <- na.omit(unique(x))
  tab <- tabulate(match(x, ux))
  ux[tab == max(tab)]
}

Apply the functions to a data frame:
iris %>%
  summarise(across(everything(), Mode))
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1            5           3          1.4         0.2  setosa

iris %>% map(Modes)
#> $Sepal.Length
#> [1] 5
#>
#> $Sepal.Width
#> [1] 3
#>
#> $Petal.Length
#> [1] 1.4 1.5
#>
#> $Petal.Width
#> [1] 0.2
#>
#> $Species
#> [1] setosa     versicolor virginica
#> Levels: setosa versicolor virginica

Impute missing data using the mode. But note that we use Mode, which returns only the first mode in cases where there are multiple modes. You may need to adjust your method if you have multiple modes.
# Create missing data
d = iris
d[1, ] = rep(NA, ncol(iris))

head(d)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1           NA          NA           NA          NA    <NA>
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa

# Replace missing values with the mode
d = d %>%
  mutate(across(everything(), ~coalesce(., Mode(.))))

head(d)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#> 1          5.0         3.0          1.5         0.2 versicolor
#> 2          4.9         3.0          1.4         0.2     setosa
#> 3          4.7         3.2          1.3         0.2     setosa
#> 4          4.6         3.1          1.5         0.2     setosa
#> 5          5.0         3.6          1.4         0.2     setosa
#> 6          5.4         3.9          1.7         0.4     setosa


text:
Q: how to stop delayed job to execute duplicate records   counter.times do
              count_var+= 1
              range1 = process_limit * count_var
              sms = Delayed::Job.enqueue(SmsManager.new(arr_msg_array[i1...range1], recipients[i1...range1], student_type[i1...range1], reciver_type[i1...range1], reciver_id[i1...range1], created_by[i1...range1])) i1= range1
            end

----------

 class SmsManager
  attr_accessor :recipients, :message, :astudent_type, :areciver_type, :areciver_id, :acreated_by

def initialize(message, recipients, student_type, caregiver_type, receiver_id, created_by)
end
      def perform
          begin
            recipients.each_with_index do |recipient,i|
            end
              end
            end
            end

A: On every failure job , delayed handler tries to re execute the whole array of jobs as per the number of  defined reattempts.