Programs & Examples On #Parcel

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

All com.android.support libraries must use the exact same version specification

If the same error is on appcompat

implementation 'com.android.support:appcompat-v7:27.0.1'

then adding design solved it.

implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support:design:27.0.1'

For me, adding

implementation 'de.mrmaffen:vlc-android-sdk:2.0.6'

was including appcompat-v7:23.1.1 in

.idea/libraries

without vlc, appcompat alone is enough.

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

On Android >=6.0, We have to request permission runtime.

Step1: add in AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Step2: Request permission.

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
    //TODO
}

Step3: Handle callback when you request permission.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_READ_PHONE_STATE:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                //TODO
            }
            break;

        default:
            break;
    }
}

Edit: Read official guide here Requesting Permissions at Run Time

READ_EXTERNAL_STORAGE permission for Android

Step1: add permission on android manifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Step2: onCreate() method

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
    } else {
        readDataExternal();
    }

Step3: override onRequestPermissionsResult method to get callback

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_MEDIA:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                readDataExternal();
            }
            break;

        default:
            break;
    }
}

Note: readDataExternal() is method to get data from external storage.

Thanks.

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

The answer is

recyclerView.scrollToPosition(arrayList.size() - 1);

Everyone has mentioned it.

But the problem I was facing was that it was not placed correctly.

I tried and placed just after the adapter.notifyDataSetChanged(); and it worked. Whenever, data in your recycler view changes, it automatically scrolls to the bottom like after sending messages or you open the chat list for the first time.

Note : This code was tasted in Java.

actual code for me was :

//scroll to bottom after sending message.
binding.chatRecyclerView.scrollToPosition(messageArrayList.size() - 1);

Parcelable encountered IOException writing serializable object getactivity()

The exception occurred due to the fact that any of the inner classes or other referenced classes didn't implement the serializable implementation. So make sure that all the referenced classes must implement the serializable implementation.

Android - java.lang.SecurityException: Permission Denial: starting Intent

Add android:exported="true" in your 'com.example.lib.MainActivity' activity tag.

From the android:exported documentation,

android:exported Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

From your logcat output, clearly a mismatch in uid is causing the issue. So adding the android:exported="true" should do the trick.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

On newer versions of Android, I was receiving this error because the adapter was still discovering when I attempted to connect to the socket. Even though I called the cancelDiscovery method on the Bluetooth adapter, I had to wait until the callback to the BroadcastReceiver's onReceive() method was called with the action BluetoothAdapter.ACTION_DISCOVERY_FINISHED.

Once I waited for the adapter to stop discovery, then the connect call on the socket succeeded.

jQuery select change show/hide div event

Try this:

 $(function () {
     $('#row_dim').hide(); // this line you can avoid by adding #row_dim{display:none;} in your CSS
     $('#type').change(function () {
         $('#row_dim').hide();
         if (this.options[this.selectedIndex].value == 'parcel') {
             $('#row_dim').show();
         }
     });
 });

Demo here

Android: Pass data(extras) to a fragment

I prefer Serializable = no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable does not matter.

I would also always provide a helper method for a Fragment or Activity, this way you always know, what data has to be passed. Here an example for your ListMusicFragment:

private static final String EXTRA_MUSIC_LIST = "music_list";

public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_MUSIC_LIST, music);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public View onCreateView(...) { 
    ...
    Bundle bundle = intent.getArguments();
    List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
    ...
}

Android set bitmap to Imageview

    //decode base64 string to image
    imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
    Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    image.setImageBitmap(decodedImage);

  //setImageBitmap is imp

Passing data through intent using Serializable

Sending Data:

First make your serializable data by implement Serializable to your data class

public class YourDataClass implements Serializable {
String someText="Some text";
}

Then put it into intent

YourDataClass yourDataClass=new YourDataClass();
Intent intent = new Intent(getApplicationContext(),ReceivingActivity.class);
intent.putExtra("value",yourDataClass);
startActivity(intent);

Receiving Data:

YourDataClass yourDataClass=(YourDataClass)getIntent().getSerializableExtra("value");

Android + Pair devices via bluetooth programmatically

In my first answer the logic is shown for those who want to go with the logic only.

I think I was not able to make clear to @chalukya3545, that's why I am adding the whole code to let him know the exact flow of the code.

BluetoothDemo.java

public class BluetoothDemo extends Activity {

    ListView listViewPaired;
    ListView listViewDetected;
    ArrayList<String> arrayListpaired;
    Button buttonSearch,buttonOn,buttonDesc,buttonOff;
    ArrayAdapter<String> adapter,detectedAdapter;
    static HandleSeacrh handleSeacrh;
    BluetoothDevice bdDevice;
    BluetoothClass bdClass;
    ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
    private ButtonClicked clicked;
    ListItemClickedonPaired listItemClickedonPaired;
    BluetoothAdapter bluetoothAdapter = null;
    ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
    ListItemClicked listItemClicked;

    @Override 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listViewDetected = (ListView) findViewById(R.id.listViewDetected);
        listViewPaired = (ListView) findViewById(R.id.listViewPaired);
        buttonSearch = (Button) findViewById(R.id.buttonSearch);
        buttonOn = (Button) findViewById(R.id.buttonOn);
        buttonDesc = (Button) findViewById(R.id.buttonDesc);
        buttonOff = (Button) findViewById(R.id.buttonOff); 
        arrayListpaired = new ArrayList<String>();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        clicked = new ButtonClicked();
        handleSeacrh = new HandleSeacrh();
        arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
        /*
         * the above declaration is just for getting the paired bluetooth devices;
         * this helps in the removing the bond between paired devices.
         */
        listItemClickedonPaired = new ListItemClickedonPaired();
        arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
        adapter= new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_1, arrayListpaired);
        detectedAdapter = new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_single_choice);
        listViewDetected.setAdapter(detectedAdapter);
        listItemClicked = new ListItemClicked();
        detectedAdapter.notifyDataSetChanged();
        listViewPaired.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        getPairedDevices();
        buttonOn.setOnClickListener(clicked);
        buttonSearch.setOnClickListener(clicked);
        buttonDesc.setOnClickListener(clicked);
        buttonOff.setOnClickListener(clicked);
        listViewDetected.setOnItemClickListener(listItemClicked);
        listViewPaired.setOnItemClickListener(listItemClickedonPaired);
    }
    private void getPairedDevices() {
        Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();            
        if(pairedDevice.size()>0)
        {
            for(BluetoothDevice device : pairedDevice)
            {
                arrayListpaired.add(device.getName()+"\n"+device.getAddress());
                arrayListPairedBluetoothDevices.add(device);
            }
        }
        adapter.notifyDataSetChanged();
    }
    class ListItemClicked implements OnItemClickListener
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            bdDevice = arrayListBluetoothDevices.get(position);
            //bdClass = arrayListBluetoothDevices.get(position);
            Log.i("Log", "The dvice : "+bdDevice.toString());
            /*
             * here below we can do pairing without calling the callthread(), we can directly call the
             * connect(). but for the safer side we must usethe threading object.
             */
            //callThread();
            //connect(bdDevice);
            Boolean isBonded = false;
            try {
                isBonded = createBond(bdDevice);
                if(isBonded)
                {
                    //arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
                    //adapter.notifyDataSetChanged();
                    getPairedDevices();
                    adapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                e.printStackTrace(); 
            }//connect(bdDevice);
            Log.i("Log", "The bond is created: "+isBonded);
        }       
    }
    class ListItemClickedonPaired implements OnItemClickListener
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            bdDevice = arrayListPairedBluetoothDevices.get(position);
            try {
                Boolean removeBonding = removeBond(bdDevice);
                if(removeBonding)
                {
                    arrayListpaired.remove(position);
                    adapter.notifyDataSetChanged();
                }


                Log.i("Log", "Removed"+removeBonding);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /*private void callThread() {
        new Thread(){
            public void run() {
                Boolean isBonded = false;
                try {
                    isBonded = createBond(bdDevice);
                    if(isBonded)
                    {
                        arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
                        adapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace(); 
                }//connect(bdDevice);
                Log.i("Log", "The bond is created: "+isBonded);
            }           
        }.start();
    }*/
    private Boolean connect(BluetoothDevice bdDevice) { 
        Boolean bool = false;
        try {
            Log.i("Log", "service method is called ");
            Class cl = Class.forName("android.bluetooth.BluetoothDevice");
            Class[] par = {};
            Method method = cl.getMethod("createBond", par);
            Object[] args = {};
            bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
            //Log.i("Log", "This is: "+bool.booleanValue());
            //Log.i("Log", "devicesss: "+bdDevice.getName());
        } catch (Exception e) {
            Log.i("Log", "Inside catch of serviceFromDevice Method");
            e.printStackTrace();
        }
        return bool.booleanValue();
    };


    public boolean removeBond(BluetoothDevice btDevice)  
    throws Exception  
    {  
        Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
        Method removeBondMethod = btClass.getMethod("removeBond");  
        Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }


    public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  


    class ButtonClicked implements OnClickListener
    {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
            case R.id.buttonOn:
                onBluetooth();
                break;
            case R.id.buttonSearch:
                arrayListBluetoothDevices.clear();
                startSearching();
                break;
            case R.id.buttonDesc:
                makeDiscoverable();
                break;
            case R.id.buttonOff:
                offBluetooth();
                break;
            default:
                break;
            }
        }
    }
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Message msg = Message.obtain();
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                try
                {
                    //device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
                    //device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
                }
                catch (Exception e) {
                    Log.i("Log", "Inside the exception: ");
                    e.printStackTrace();
                }

                if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the
                {                                           // device to the arraylist.
                    detectedAdapter.add(device.getName()+"\n"+device.getAddress());
                    arrayListBluetoothDevices.add(device);
                    detectedAdapter.notifyDataSetChanged();
                }
                else
                {
                    boolean flag = true;    // flag to indicate that particular device is already in the arlist or not
                    for(int i = 0; i<arrayListBluetoothDevices.size();i++)
                    {
                        if(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress()))
                        {
                            flag = false;
                        }
                    }
                    if(flag == true)
                    {
                        detectedAdapter.add(device.getName()+"\n"+device.getAddress());
                        arrayListBluetoothDevices.add(device);
                        detectedAdapter.notifyDataSetChanged();
                    }
                }
            }           
        }
    };
    private void startSearching() {
        Log.i("Log", "in the start searching method");
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
        bluetoothAdapter.startDiscovery();
    }
    private void onBluetooth() {
        if(!bluetoothAdapter.isEnabled())
        {
            bluetoothAdapter.enable();
            Log.i("Log", "Bluetooth is Enabled");
        }
    }
    private void offBluetooth() {
        if(bluetoothAdapter.isEnabled())
        {
            bluetoothAdapter.disable();
        }
    }
    private void makeDiscoverable() {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);
        Log.i("Log", "Discoverable ");
    }
    class HandleSeacrh extends Handler
    {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 111:

                break;

            default:
                break;
            }
        }
    }
}

Here is the main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button 
        android:id="@+id/buttonOn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="On"/>
    <Button 
        android:id="@+id/buttonDesc"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Make Discoverable"/>
   <Button 
       android:id="@+id/buttonSearch"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Search"/>
   <Button 
       android:id="@+id/buttonOff"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Bluetooth Off"/>

   <ListView 
       android:id="@+id/listViewPaired"
       android:layout_width="match_parent"
       android:layout_height="120dp">

   </ListView>

   <ListView 
       android:id="@+id/listViewDetected"
       android:layout_width="match_parent"
       android:layout_height="match_parent">

   </ListView>
</LinearLayout>

Add this permissions to your AndroidManifest.xml file:

 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
 <uses-permission android:name="android.permission.BLUETOOTH" />  
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

The output for this code will look like this. Bluutooth Demo

How to pass ArrayList of Objects from one to another activity using Intent in android?

I do one of two things in this scenario

  1. Implement a serialize/deserialize system for my objects and pass them as Strings (in JSON format usually, but you can serialize them any way you'd like)

  2. Implement a container that lives outside of the activities so that all my activities can read and write to this container. You can make this container static or use some kind of dependency injection to retrieve the same instance in each activity.

Parcelable works just fine, but I always found it to be an ugly looking pattern and doesn't really add any value that isn't there if you write your own serialization code outside of the model.

What to do on TransactionTooLargeException

When I am dealing with the WebView in my app it happens. I think it's related to addView and UI resources. In my app I add some code in WebViewActivity like this below then it runs ok:

@Override
protected void onDestroy() {
    if (mWebView != null) {
        ((ViewGroup) mWebView.getParent()).removeView(mWebView);  
        mWebView.removeAllViews();  
        mWebView.destroy();
    }
    super.onDestroy();
}

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Does anyone know whether this is a bug or not?

ViewPager PagerAdapter not updating the View

ViewPager was not designed to support dynamic view change.

I had confirmation of this while looking for another bug related to this one https://issuetracker.google.com/issues/36956111 and in particular https://issuetracker.google.com/issues/36956111#comment56

This question is a bit old, but Google recently solved this problem with ViewPager2 . It will allow to replace handmade (unmaintained and potentially buggy) solutions by a standard one. It also prevents recreating views needlessly as some answers do.

For ViewPager2 examples, you can check https://github.com/googlesamples/android-viewpager2

If you want to use ViewPager2, you will need to add the following dependency in your build.gradle file :

  dependencies {
     implementation 'androidx.viewpager2:viewpager2:1.0.0-beta02'
  }

Then you can replace your ViewPager in your xml file with :

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

After that, you will need to replace ViewPager by ViewPager2 in your activity

ViewPager2 needs either a RecyclerView.Adapter, or a FragmentStateAdapter, in your case it can be a RecyclerView.Adapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private Context context;
    private ArrayList<String> arrayList = new ArrayList<>();

    public MyAdapter(Context context, ArrayList<String> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.tvName.setText(arrayList.get(position));
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tvName;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
        }
    }
} 

In the case you were using a TabLayout, you can use a TabLayoutMediator :

        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager, true, new TabLayoutMediator.OnConfigureTabCallback() {
            @Override
            public void onConfigureTab(@NotNull TabLayout.Tab tab, int position) {
                // configure your tab here
                tab.setText(tabs.get(position).getTitle());
            }
        });

        tabLayoutMediator.attach();

Then you will be able to refresh your views by modifying your adapter's data and calling notifyDataSetChanged method

How can I make my custom objects Parcelable?

Create Parcelable class without plugin in Android Studio

implements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.

enter image description here

How to read/write a boolean when implementing the Parcelable interface?

You could pack your boolean values into a byte using masking and shifting. That would be the most efficient way to do it and is probably what they would expect you to do.

Elegant way to read file into byte[] array in Java

This will also work:

import java.io.*;

public class IOUtil {

    public static byte[] readFile(String file) throws IOException {
        return readFile(new File(file));
    }

    public static byte[] readFile(File file) throws IOException {
        // Open file
        RandomAccessFile f = new RandomAccessFile(file, "r");
        try {
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } finally {
            f.close();
        }
    }
}

Apple Mach-O Linker Error when compiling for device

I mistakenly defined a new constant with the same name as an existing constant in a different file and it caused this error for me using xCode 4.3.1. xCode didn't complain but the compiler doesn't like it.

How to make a phone call using intent in Android?

Every thing is fine.

i just placed call permissions tag before application tag in manifest file

and now every thing is working fine.

How to send objects through bundle

Figuring out what path to take requires answering not only CommonsWare's key question of "why" but also the question of "to what?" are you passing it.

The reality is that the only thing that can go through bundles is plain data - everything else is based on interpretations of what that data means or points to. You can't literally pass an object, but what you can do is one of three things:

1) You can break the object down to its constitute data, and if what's on the other end has knowledge of the same sort of object, it can assemble a clone from the serialized data. That's how most of the common types pass through bundles.

2) You can pass an opaque handle. If you are passing it within the same context (though one might ask why bother) that will be a handle you can invoke or dereference. But if you pass it through Binder to a different context it's literal value will be an arbitrary number (in fact, these arbitrary numbers count sequentially from startup). You can't do anything but keep track of it, until you pass it back to the original context which will cause Binder to transform it back into the original handle, making it useful again.

3) You can pass a magic handle, such as a file descriptor or reference to certain os/platform objects, and if you set the right flags Binder will create a clone pointing to the same resource for the recipient, which can actually be used on the other end. But this only works for a very few types of objects.

Most likely, you are either passing your class just so the other end can keep track of it and give it back to you later, or you are passing it to a context where a clone can be created from serialized constituent data... or else you are trying to do something that just isn't going to work and you need to rethink the whole approach.

Android: java.lang.SecurityException: Permission Denial: start Intent

In your Manifest file write this before </application >

<activity android:name="com.fsck.k9.activity.MessageList">
   <intent-filter>
      <action android:name="android.intent.action.MAIN">
      </action>
   </intent-filter>
</activity>

and tell me if it solves your issue :)

Android: Difference between Parcelable and Serializable?

I'm actually going to be the one guy advocating for the Serializable. The speed difference is not so drastic any more since the devices are far better than several years ago and also there are other, more subtle differences. See my blog post on the issue for more info.

How to have Android Service communicate with Activity

There are three obvious ways to communicate with services:

  1. Using Intents
  2. Using AIDL
  3. Using the service object itself (as singleton)

In your case, I'd go with option 3. Make a static reference to the service it self and populate it in onCreate():

void onCreate(Intent i) {
  sInstance = this;
}

Make a static function MyService getInstance(), which returns the static sInstance.

Then in Activity.onCreate() you start the service, asynchronously wait until the service is actually started (you could have your service notify your app it's ready by sending an intent to the activity.) and get its instance. When you have the instance, register your service listener object to you service and you are set. NOTE: when editing Views inside the Activity you should modify them in the UI thread, the service will probably run its own Thread, so you need to call Activity.runOnUiThread().

The last thing you need to do is to remove the reference to you listener object in Activity.onPause(), otherwise an instance of your activity context will leak, not good.

NOTE: This method is only useful when your application/Activity/task is the only process that will access your service. If this is not the case you have to use option 1. or 2.

How do you post to the wall on a facebook page (not profile)

This works for me:

try {
       $statusUpdate = $facebook->api('/me/feed', 'post',
                 array('name'=>'My APP on Facebook','message'=> 'I am here working',
                 'privacy'=> array('value'=>'CUSTOM','friends'=>'SELF'),
                 'description'=>'testing my description',
                 'picture'=>'https://fbcdn-photos-a.akamaihd.net/mypicture.gif',
                 'caption'=>'apps.facebook.com/myapp','link'=>'http://apps.facebook.com/myapp'));
 } catch (FacebookApiException $e) {
      d($e);
}

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

I managed to fix the problem.

The source of the error was this line of code, that can be found in the SDLmain source code.

fprintf(stderr, "%s: %s\n", title, message);

So what I did was to edit the source code in SDLmain of that line too:

fprintf("%s: %s\n", title, message);

And then I built the SDLmain and copied and replaced the old SDLmain.lib in my SDL2 library directory with the newly built and edited.

Then when I ran my program with SDL2 no error messages came up and to code ran smoothly.

I don't know if this will bite me later, but so for everything is going great.

IF... OR IF... in a windows batch file

Even if this question is a little older:

If you want to use if cond1 or cond 2 - you should not use complicated loops or stuff like that.

Simple provide both ifs after each other combined with goto - that's an implicit or.

//thats an implicit IF cond1 OR cond2 OR cond3
if cond1 GOTO doit
if cond2 GOTO doit
if cond3 GOTO doit

//thats our else.
GOTO end

:doit
  echo "doing it"

:end

Without goto but an "inplace" action, you might execute the action 3 times, if ALL conditions are matching.

IntelliJ - Convert a Java project/module into a Maven project/module

Right-click on the module, select "Add framework support...", and check the "Maven" technology.

(This also creates a pom.xml for you to modify.)

If you mean adding source repository elements, I think you need to do that manually–not sure.

Pre-IntelliJ 13 this won't convert the project to the Maven Standard Directory Layout, 13+ it will.

What are .NET Assemblies?

In addition to the accepted answer, I want to give you an example!

For instance, we all use

System.Console.WriteLine()

But Where is the code for System.Console.WriteLine!?
which is the code that actually puts the text on the console?

If you look at the first page of the documentation for the Console class, you‘ll see near the top the following: Assembly: mscorlib (in mscorlib.dll) This indicates that the code for the Console class is located in an assem-bly named mscorlib. An assembly can consist of multiple files, but in this case it‘s only one file, which is the dynamic link library mscorlib.dll.

The mscorlib.dll file is very important in .NET, It is the main DLL for class libraries in .NET, and it contains all the basic .NET classes and structures.

if you know C or C++, generally you need a #include directive at the top that references a header file. The include file provides function prototypes to the compiler. on the contrast The C# compiler does not need header files. During compilation, the C# compiler access the mscorlib.dll file directly and obtains information from metadata in that file concerning all the classes and other types defined therein.

The C# compiler is able to establish that mscorlib.dll does indeed contain a class named Console in a namespace named System with a method named WriteLine that accepts a single argument of type string.

The C# compiler can determine that the WriteLine call is valid, and the compiler establishes a reference to the mscorlib assembly in the executable.

by default The C# compiler will access mscorlib.dll, but for other DLLs, you‘ll need to tell the compiler the assembly in which the classes are located. These are known as references.

I hope that it's clear now!

From DotNetBookZero Charles pitzold

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

The idea is that for speed and cache considerations, operands should be read from addresses aligned to their natural size. To make this happen, the compiler pads structure members so the following member or following struct will be aligned.

struct pixel {
    unsigned char red;   // 0
    unsigned char green; // 1
    unsigned int alpha;  // 4 (gotta skip to an aligned offset)
    unsigned char blue;  // 8 (then skip 9 10 11)
};

// next offset: 12

The x86 architecture has always been able to fetch misaligned addresses. However, it's slower and when the misalignment overlaps two different cache lines, then it evicts two cache lines when an aligned access would only evict one.

Some architectures actually have to trap on misaligned reads and writes, and early versions of the ARM architecture (the one that evolved into all of today's mobile CPUs) ... well, they actually just returned bad data on for those. (They ignored the low-order bits.)

Finally, note that cache lines can be arbitrarily large, and the compiler doesn't attempt to guess at those or make a space-vs-speed tradeoff. Instead, the alignment decisions are part of the ABI and represent the minimum alignment that will eventually evenly fill up a cache line.

TL;DR: alignment is important.

In Java, remove empty elements from a list of Strings

  • This code compiles and runs smoothly.
  • It uses no iterator so more readable.
  • list is your collection.
  • result is filtered form (no null no empty).

public static void listRemove() {
    List<String> list = Arrays.asList("", "Hi", "", "How", "are", "you");
    List<String> result = new ArrayList<String>();

    for (String str : list) {
        if (str != null && !str.isEmpty()) {
            result.add(str);
        }
    }

    System.out.println(result);
}

How to substitute shell variables in complex text files

Actually you need to change your read to read -r which will make it ignore backslashes.

Also, you should escape quotes and backslashes. So

while read -r line; do
  line="${line//\\/\\\\}"
  line="${line//\"/\\\"}"
  line="${line//\`/\\\`}"
  eval echo "\"$line\""
done > destination.txt < source.txt

Still a terrible way to do expansion though.

how to call a function from another function in Jquery

I think in this case you want something like this:

$(window).resize(resize=function resize(){ some code...}

Now u can call resize() within some other nested functions:

$(window).scroll(function(){ resize();}

What's the difference between process.cwd() vs __dirname?

Knowing the scope of each can make things easier to remember.

process is node's global object, and .cwd() returns where node is running.

__dirname is module's property, and represents the file path of the module. In node, one module resides in one file.

Similarly, __filename is another module's property, which holds the file name of the module.

How to test whether a service is running from the command line

You could use wmic with the /locale option

call wmic /locale:ms_409 service where (name="wsearch") get state /value | findstr State=Running
if %ErrorLevel% EQU 0 (
    echo Running
) else (
    echo Not running
)

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Jquery - How to get the style display attribute "none / block"

My answer

/**
 * Display form to reply comment
 */
function displayReplyForm(commentId) {
    var replyForm = $('#reply-form-' + commentId);
    if (replyForm.css('display') == 'block') { // Current display
        replyForm.css('display', 'none');
    } else { // Hide reply form
        replyForm.css('display', 'block');
    }
}

checked = "checked" vs checked = true

document.getElementById('myRadio').checked is a boolean value. It should be true or false

document.getElementById('myRadio').checked = "checked"; casts the string to a boolean, which is true.

document.getElementById('myRadio').checked = true; just assigns true without casting.

Use true as it is marginally more efficient and is more intention revealing to maintainers.

How to position one element relative to another with jQuery?

NOTE: This requires jQuery UI (not just jQuery).

You can now use:

$("#my_div").position({
    my:        "left top",
    at:        "left bottom",
    of:        this, // or $("#otherdiv")
    collision: "fit"
});

For fast positioning (jQuery UI/Position).

You can download jQuery UI here.

Functions are not valid as a React child. This may happen if you return a Component instead of from render

In my case i forgot to add the () after the function name inside the render function of a react component

public render() {
       let ctrl = (
           <>
                <div className="aaa">
                    {this.renderView}
                </div>
            </>
       ); 

       return ctrl;
    };


    private renderView() : JSX.Element {
        // some html
    };

Changing the render method, as it states in the error message to

        <div className="aaa">
            {this.renderView()}
        </div>

fixed the problem

How to get full path of a file?

This will work for both file and folder:

getAbsolutePath(){
    [[ -d $1 ]] && { cd "$1"; echo "$(pwd -P)"; } || 
    { cd "$(dirname "$1")" || exit 1; echo "$(pwd -P)/$(basename "$1")"; }
}

Load dimension value from res/values/dimension.xml from source code

Context.getResources().getDimension(int id);

How to export specific request to file using postman?

If you want to export it as a file just do Any Collection (...) -> Export. There you should be able to choose collection version format and it will be exported in JSN file.

Real-world examples of recursion

Since you don't seem to like computer science or mathy examples, here is a different one: wire puzzles.

Many wire puzzles involve removing a long closed loop of wire by working it in and out of wire rings. These puzzles are recursive. One of them is called "arrow dynamics". I am sue you could find it if you google for "arrow dynamics wire puzzle"

These puzzles are a lot like the towers of Hanoi.

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

How do I get column datatype in Oracle with PL-SQL with low privileges?

ALL_TAB_COLUMNS should be queryable from PL/SQL. DESC is a SQL*Plus command.

SQL> desc all_tab_columns;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)
 TABLE_NAME                                NOT NULL VARCHAR2(30)
 COLUMN_NAME                               NOT NULL VARCHAR2(30)
 DATA_TYPE                                          VARCHAR2(106)
 DATA_TYPE_MOD                                      VARCHAR2(3)
 DATA_TYPE_OWNER                                    VARCHAR2(30)
 DATA_LENGTH                               NOT NULL NUMBER
 DATA_PRECISION                                     NUMBER
 DATA_SCALE                                         NUMBER
 NULLABLE                                           VARCHAR2(1)
 COLUMN_ID                                          NUMBER
 DEFAULT_LENGTH                                     NUMBER
 DATA_DEFAULT                                       LONG
 NUM_DISTINCT                                       NUMBER
 LOW_VALUE                                          RAW(32)
 HIGH_VALUE                                         RAW(32)
 DENSITY                                            NUMBER
 NUM_NULLS                                          NUMBER
 NUM_BUCKETS                                        NUMBER
 LAST_ANALYZED                                      DATE
 SAMPLE_SIZE                                        NUMBER
 CHARACTER_SET_NAME                                 VARCHAR2(44)
 CHAR_COL_DECL_LENGTH                               NUMBER
 GLOBAL_STATS                                       VARCHAR2(3)
 USER_STATS                                         VARCHAR2(3)
 AVG_COL_LEN                                        NUMBER
 CHAR_LENGTH                                        NUMBER
 CHAR_USED                                          VARCHAR2(1)
 V80_FMT_IMAGE                                      VARCHAR2(3)
 DATA_UPGRADED                                      VARCHAR2(3)
 HISTOGRAM                                          VARCHAR2(15)

Need table of key codes for android and presenter

You can find a complete list of Key Codes and an explanation here: http://code.google.com/p/androhid/wiki/Keycodes

android ellipsize multiline textview

This is late, but I found an Apache licensed class from Android, that's used in the stock mail app: https://android.googlesource.com/platform/packages/apps/UnifiedEmail/+/184ec73/src/com/android/mail/ui/EllipsizedMultilineTextView.java

/*
 * Copyright (C) 2013 Google Inc.
 * Licensed to The Android Open Source Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.mail.ui;
import android.content.Context;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
 * A special MultiLine TextView that will apply ellipsize logic to only the last
 * line of text, such that the last line may be shorter than any previous lines.
 */
public class EllipsizedMultilineTextView extends TextView {
    public static final int ALL_AVAILABLE = -1;
    private int mMaxLines;
    public EllipsizedMultilineTextView(Context context) {
        this(context, null);
    }
    public EllipsizedMultilineTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public void setMaxLines(int maxlines) {
        super.setMaxLines(maxlines);
        mMaxLines = maxlines;
    }
    /**
     * Ellipsize just the last line of text in this view and set the text to the
     * new ellipsized value.
     * @param text Text to set and ellipsize
     * @param avail available width in pixels for the last line
     * @param paint Paint that has the proper properties set to measure the text
     *            for this view
     * @return the {@link CharSequence} that was set on the {@link TextView}
     */
    public CharSequence setText(final CharSequence text, int avail) {
        if (text == null || text.length() == 0) {
            return text;
        }
        setEllipsize(null);
        setText(text);
        if (avail == ALL_AVAILABLE) {
            return text;
        }
        Layout layout = getLayout();
        if (layout == null) {
            final int w = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
            layout = new StaticLayout(text, 0, text.length(), getPaint(), w, Alignment.ALIGN_NORMAL,
                    1.0f, 0f, false);
        }
        // find the last line of text and chop it according to available space
        final int lastLineStart = layout.getLineStart(mMaxLines - 1);
        final CharSequence remainder = TextUtils.ellipsize(text.subSequence(lastLineStart,
                text.length()), getPaint(), avail, TextUtils.TruncateAt.END);
        // assemble just the text portion, without spans
        final SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(text.toString(), 0, lastLineStart);
        if (!TextUtils.isEmpty(remainder)) {
            builder.append(remainder.toString());
        }
        // Now copy the original spans into the assembled string, modified for any ellipsizing.
        //
        // Merely assembling the Spanned pieces together would result in duplicate CharacterStyle
        // spans in the assembled version if a CharacterStyle spanned across the lastLineStart
        // offset.
        if (text instanceof Spanned) {
            final Spanned s = (Spanned) text;
            final Object[] spans = s.getSpans(0, s.length(), Object.class);
            final int destLen = builder.length();
            for (int i = 0; i < spans.length; i++) {
                final Object span = spans[i];
                final int start = s.getSpanStart(span);
                final int end = s.getSpanEnd(span);
                final int flags = s.getSpanFlags(span);
                if (start <= destLen) {
                    builder.setSpan(span, start, Math.min(end, destLen), flags);
                }
            }
        }
        setText(builder);
        return builder;
    }
}

Get the last non-empty cell in a column in Google Sheets

Here's another one:

=indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),""))))

With the final equation being this:

=DAYS360(A2,indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),"")))))

The other equations on here work, but I like this one because it makes getting the row number easy, which I find I need to do more often. Just the row number would be like this:

=max(arrayformula(if(A:A<>"",row(A:A),"")))

I originally tried to find just this to solve a spreadsheet issue, but couldn't find anything useful that just gave the row number of the last entry, so hopefully this is helpful for someone.

Also, this has the added advantage that it works for any type of data in any order, and you can have blank rows in between rows with content, and it doesn't count cells with formulas that evaluate to "". It can also handle repeated values. All in all it's very similar to the equation that uses max((G:G<>"")*row(G:G)) on here, but makes pulling out the row number a little easier if that's what you're after.

Alternatively, if you want to put a script on your sheet you can make it easy on yourself if you plan on doing this a lot. Here's that scirpt:

function lastRow(sheet,column) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  if (column == null) {
    if (sheet != null) {
       var sheet = ss.getSheetByName(sheet);
    } else {
      var sheet = ss.getActiveSheet();
    }
    return sheet.getLastRow();
  } else {
    var sheet = ss.getSheetByName(sheet);
    var lastRow = sheet.getLastRow();
    var array = sheet.getRange(column + 1 + ':' + column + lastRow).getValues();
    for (i=0;i<array.length;i++) {
      if (array[i] != '') {       
        var final = i + 1;
      }
    }
    if (final != null) {
      return final;
    } else {
      return 0;
    }
  }
}

Here you can just type in the following if you want the last row on the same of the sheet that you're currently editing:

=LASTROW()

or if you want the last row of a particular column from that sheet, or of a particular column from another sheet you can do the following:

=LASTROW("Sheet1","A")

And for the last row of a particular sheet in general:

=LASTROW("Sheet1")

Then to get the actual data you can either use indirect:

=INDIRECT("A"&LASTROW())

or you can modify the above script at the last two return lines (the last two since you would have to put both the sheet and the column to get the actual value from an actual column), and replace the variable with the following:

return sheet.getRange(column + final).getValue();

and

return sheet.getRange(column + lastRow).getValue();

One benefit of this script is that you can choose if you want to include equations that evaluate to "". If no arguments are added equations evaluating to "" will be counted, but if you specify a sheet and column they will now be counted. Also, there's a lot of flexibility if you're willing to use variations of the script.

Probably overkill, but all possible.

Command-line tool for finding out who is locking a file

Download Handle.

https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx

If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you've added Handle.exe to the PATH environment variable. And the file path is C:\path\path\file.txt", run this:

handle "C:\path\path\file.txt"

This will tell you what process(es) have the file (or folder) locked.

Path to Powershell.exe (v 2.0)

Here is one way...

(Get-Process powershell | select -First 1).Path

Here is possibly a better way, as it returns the first hit on the path, just like if you had ran Powershell from a command prompt...

(Get-Command powershell.exe).Definition

How do I run Selenium in Xvfb?

If you use Maven, you can use xvfb-maven-plugin to start xvfb before tests, run them using related DISPLAY environment variable, and stop xvfb after all.

pod install -bash: pod: command not found

so I also had the same problem. This is probably happening because your computer has an older version of ruby. So you need to first update your ruby. Mine worked for ruby 2.6.3 version.I got this solution from sStackOverflow,

You need to first open terminal and put this code

curl -L https://get.rvm.io | bash -s stable

Then put this command

rvm install ruby-2.6

This would install the ruby for you if it hasn' t been installed.After this just update the ruby to the new version

rvm use ruby-2.6.3

After this just make ruby 2.6.3 your default

rvm --default use 2.6.3

This would possibly fix your issue. You can now put the command

sudo gem install cocoapods

And the command

pod setup

I hope this was useful

Read data from a text file using Java

You should not use available(). It gives no guarantees what so ever. From the API docs of available():

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

You would probably want to use something like

try {
    BufferedReader in = new BufferedReader(new FileReader("infilename"));
    String str;
    while ((str = in.readLine()) != null)
        process(str);
    in.close();
} catch (IOException e) {
}

(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)

Parse (split) a string in C++ using string delimiter (standard C++)

strtok allows you to pass in multiple chars as delimiters. I bet if you passed in ">=" your example string would be split correctly (even though the > and = are counted as individual delimiters).

EDIT if you don't want to use c_str() to convert from string to char*, you can use substr and find_first_of to tokenize.

string token, mystring("scott>=tiger");
while(token != mystring){
  token = mystring.substr(0,mystring.find_first_of(">="));
  mystring = mystring.substr(mystring.find_first_of(">=") + 1);
  printf("%s ",token.c_str());
}

How to download image using requests

You can do something like this:

import requests
import random

url = "https://images.pexels.com/photos/1308881/pexels-photo-1308881.jpeg? auto=compress&cs=tinysrgb&dpr=1&w=500"
name=random.randrange(1,1000)
filename=str(name)+".jpg"
response = requests.get(url)
if response.status_code.ok:
   with open(filename,'w') as f:
    f.write(response.content)

What in layman's terms is a Recursive Function using PHP

Basically this. It keeps calling itself until its done

void print_folder(string root)
{
    Console.WriteLine(root);
    foreach(var folder in Directory.GetDirectories(root))
    {
        print_folder(folder);
    }
}

Also works with loops!

void pretend_loop(int c)
{
    if(c==0) return;
    print "hi";
    pretend_loop(c-);
}

You can also trying googling it. Note the "Did you mean" (click on it...). http://www.google.com/search?q=recursion&spell=1

Example of waitpid() in use?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(2);
        exit(EXIT_SUCCESS);
    }

//Comment from here to...
    //Parent waits process pid (child)
    waitpid(pid, &status, 0);
    //Option is 0 since I check it later

    if (WIFSIGNALED(status)){
        printf("Error\n");
    }
    else if (WEXITSTATUS(status)){
        printf("Exited Normally\n");
    }
//To Here and see the difference
    printf("Parent: %d\n", getpid());

    return 0;
}

How do I use a custom deleter with a std::unique_ptr member?

Unless you need to be able to change the deleter at runtime, I would strongly recommend using a custom deleter type. For example, if use a function pointer for your deleter, sizeof(unique_ptr<T, fptr>) == 2 * sizeof(T*). In other words, half of the bytes of the unique_ptr object are wasted.

Writing a custom deleter to wrap every function is a bother, though. Thankfully, we can write a type templated on the function:

Since C++17:

template <auto fn>
using deleter_from_fn = std::integral_constant<decltype(fn), fn>;

template <typename T, auto fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<fn>>;

// usage:
my_unique_ptr<Bar, destroy> p{create()};

Prior to C++17:

template <typename D, D fn>
using deleter_from_fn = std::integral_constant<D, fn>;

template <typename T, typename D, D fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<D, fn>>;

// usage:
my_unique_ptr<Bar, decltype(destroy), destroy> p{create()};

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

Click event on select option element in chrome

I don't believe the click event is valid on options. It is valid, however, on select elements. Give this a try:

$("select#yourSelect").change(function(){
    process($(this).children(":selected").html());
});

How do I perform an IF...THEN in an SQL SELECT?

If you're inserting results into a table for the first time, rather than transferring results from one table to another, this works in Oracle 11.2g:

INSERT INTO customers (last_name, first_name, city)
    SELECT 'Doe', 'John', 'Chicago' FROM dual
    WHERE NOT EXISTS 
        (SELECT '1' from customers 
            where last_name = 'Doe' 
            and first_name = 'John'
            and city = 'Chicago');

MySQL ORDER BY multiple column ASC and DESC

Ok, I THINK I understand what you want now, and let me clarify to confirm before the query. You want 1 record for each user. For each user, you want their BEST POINTS score record. Of the best points per user, you want the one with the best average time. Once you have all users "best" values, you want the final results sorted with best points first... Almost like ranking of a competition.

So now the query. If the above statement is accurate, you need to start with getting the best point/average time per person and assigning a "Rank" to that entry. This is easily done using MySQL @ variables. Then, just include a HAVING clause to only keep those records ranked 1 for each person. Finally apply the order by of best points and shortest average time.

select
      U.UserName,
      PreSortedPerUser.Point,
      PreSortedPerUser.Avg_Time,
      @UserRank := if( @lastUserID = PreSortedPerUser.User_ID, @UserRank +1, 1 ) FinalRank,
      @lastUserID := PreSortedPerUser.User_ID
   from
      ( select
              S.user_id,
              S.point,
              S.avg_time
           from
              Scores S
           order by
              S.user_id,
              S.point DESC,
              S.Avg_Time ) PreSortedPerUser
         JOIN Users U
            on PreSortedPerUser.user_ID = U.ID,
      ( select @lastUserID := 0,
               @UserRank := 0 ) sqlvars 
   having
      FinalRank = 1
   order by
      Point Desc,
      Avg_Time

Results as handled by SQLFiddle

Note, due to the inline @variables needed to get the answer, there are the two extra columns at the end of each row. These are just "left-over" and can be ignored in any actual output presentation you are trying to do... OR, you can wrap the entire thing above one more level to just get the few columns you want like

select 
      PQ.UserName,
      PQ.Point,
      PQ.Avg_Time
   from
      ( entire query above pasted here ) as PQ

How do you use MySQL's source command to import large files in windows

With xampp I think you need to use the full path at the command line, something like this, perhaps:

C:\xampp\mysql\bin\mysql -u {username} -p {databasename} < file_name.sql

How to implement a FSM - Finite State Machine in Java

The heart of a state machine is the transition table, which takes a state and a symbol (what you're calling an event) to a new state. That's just a two-index array of states. For sanity and type safety, declare the states and symbols as enumerations. I always add a "length" member in some way (language-specific) for checking array bounds. When I've hand-coded FSM's, I format the code in row and column format with whitespace fiddling. The other elements of a state machine are the initial state and the set of accepting states. The most direct implementation of the set of accepting states is an array of booleans indexed by the states. In Java, however, enumerations are classes, and you can specify an argument "accepting" in the declaration for each enumerated value and initialize it in the constructor for the enumeration.

For the machine type, you can write it as a generic class. It would take two type arguments, one for the states and one for the symbols, an array argument for the transition table, a single state for the initial. The only other detail (though it's critical) is that you have to call Enum.ordinal() to get an integer suitable for indexing the transition array, since you there's no syntax for directly declaring an array with a enumeration index (though there ought to be).

To preempt one issue, EnumMap won't work for the transition table, because the key required is a pair of enumeration values, not a single one.

enum State {
    Initial( false ),
    Final( true ),
    Error( false );
    static public final Integer length = 1 + Error.ordinal();

    final boolean accepting;

    State( boolean accepting ) {
        this.accepting = accepting;
    }
}

enum Symbol {
    A, B, C;
    static public final Integer length = 1 + C.ordinal();
}

State transition[][] = {
    //  A               B               C
    {
        State.Initial,  State.Final,    State.Error
    }, {
        State.Final,    State.Initial,  State.Error
    }
};

Rails Model find where not equal

In Rails 3, I don't know anything fancier. However, I'm not sure if you're aware, your not equal condition does not match for (user_id) NULL values. If you want that, you'll have to do something like this:

GroupUser.where("user_id != ? OR user_id IS NULL", me)

What is the difference between .py and .pyc files?

"A program doesn't run any faster when it is read from a ".pyc" or ".pyo" file than when it is read from a ".py" file; the only thing that's faster about ".pyc" or ".pyo" files is the speed with which they are loaded. "

http://docs.python.org/release/1.5.1p1/tut/node43.html

How can I write variables inside the tasks file in ansible

In Your example, apache.yml is tasklist, but not playbook

In depends on desired architecture, You can do one of:

  1. Convert apache.yml to role. Then define tasks in roles/apache/tasks/mail.yml and variables in roles/apache/defaults/mail.yml (vars in defaults can be overriden when role applied)

  2. Set vars in play.yml playbook

play.yml

---
- hosts: 127.0.0.1
  connection: local
  sudo: false

  vars:
    url: czxcxz

  tasks:
     - include: apache.yml

apache.yml

- name: Download apache
  shell: wget {{url}} 

Count the number of occurrences of a character in a string in Javascript

Here is my solution. Lots of solution already posted before me. But I love to share my view here.

const mainStr = 'str1,str2,str3,str4';

const commaAndStringCounter = (str) => {
  const commas = [...str].filter(letter => letter === ',').length;
  const numOfStr = str.split(',').length;

  return `Commas: ${commas}, String: ${numOfStr}`;
}

// Run the code
console.log(commaAndStringCounter(mainStr)); // Output: Commas: 3, String: 4

Here you find my REPL

Android Studio Emulator and "Process finished with exit code 0"

I solved this issue by offing all of advantage features of my graphics card in its settings(Nvidaa type). It started to throw such hanging error less a lot. But finally I found a simplier way: In avd manager you need to put less resolution for the avd. Say, 400x800. Then I reenabled graphics card features again and now it runs all ok. (I suspect my graphics card or cpu are weaker than needed. )

Spring Boot: How can I set the logging level with application.properties?

You can do that using your application.properties.

logging.level.=ERROR -> Sets the root logging level to error
...
logging.level.=DEBUG -> Sets the root logging level to DEBUG

logging.file=${java.io.tmpdir}/myapp.log -> Sets the absolute log file path to TMPDIR/myapp.log

A sane default set of application.properties regarding logging using profiles would be: application.properties:

spring.application.name=<your app name here>
logging.level.=ERROR
logging.file=${java.io.tmpdir}/${spring.application.name}.log

application-dev.properties:

logging.level.=DEBUG
logging.file=

When you develop inside your favourite IDE you just add a -Dspring.profiles.active=dev as VM argument to the run/debug configuration of your app.

This will give you error only logging in production and debug logging during development WITHOUT writing the output to a log file. This will improve the performance during development ( and save SSD drives some hours of operation ;) ).

Ansible - Use default if a variable is not defined

If you have a single play that you want to loop over the items, define that list in group_vars/all or somewhere else that makes sense:

all_items:
  - first
  - second
  - third
  - fourth

Then your task can look like this:

  - name: List items or default list
    debug:
      var: item
    with_items: "{{ varlist | default(all_items) }}"

Pass in varlist as a JSON array:

ansible-playbook <playbook_name> --extra-vars='{"varlist": [first,third]}'

Prior to that, you might also want a task that checks that each item in varlist is also in all_items:

  - name: Ensure passed variables are in all_items
    fail:
      msg: "{{ item }} not  in all_items list"
    when: item not in all_items
    with_items: "{{ varlist | default(all_items) }}"

What does print(... sep='', '\t' ) mean?

sep='' ignore whiteSpace. see the code to understand.Without sep=''

from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
    print(*i)

output:

HACK 2
A C
A H
A K
C A
C H
C K
H A
H C
H K
K A
K C
K H

using sep='' The code and output.

from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
    print(*i,sep='')

output:

HACK 2
AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH

Catch KeyError in Python

You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.

Alternatively, a good way to debug this kind of thing is to say:

except Exception, e:
    print dir(e)

to see what properties e has - you'll probably find it has a message property or similar.

Is there a way to delete all the data from a topic or delete the topic before every run?

All data about topics and its partitions are stored in tmp/kafka-logs/. Moreover they are stored in a format topic-partionNumber, so if you want to delete a topic newTopic, you can:

  • stop kafka
  • delete the files rm -rf /tmp/kafka-logs/newTopic-*

Make Axios send cookies in its requests automatically

TL;DR:

{ withCredentials: true } or axios.defaults.withCredentials = true


From the axios documentation

withCredentials: false, // default

withCredentials indicates whether or not cross-site Access-Control requests should be made using credentials

If you pass { withCredentials: true } with your request it should work.

A better way would be setting withCredentials as true in axios.defaults

axios.defaults.withCredentials = true

jQuery $(document).ready and UpdatePanels?

I had a similar problem and found the way that worked best was to rely on Event Bubbling and event delegation to handle it. The nice thing about event delegation is that once setup, you don't have to rebind events after an AJAX update.

What I do in my code is setup a delegate on the parent element of the update panel. This parent element is not replaced on an update and therefore the event binding is unaffected.

There are a number of good articles and plugins to handle event delegation in jQuery and the feature will likely be baked into the 1.3 release. The article/plugin I use for reference is:

http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery

Once you understand what it happening, I think you'll find this a much more elegant solution that is more reliable than remembering to re-bind events after every update. This also has the added benefit of giving you one event to unbind when the page is unloaded.

Replace all whitespace with a line break/paragraph mark to make a word list

  1. option 1

    echo $(cat testfile)
    
  2. Option 2

    tr ' ' '\n' < testfile
    

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

You must have to define no-args or default constructor if you are creating your own constructor.

You can read why default or no argument constructor is required.

why-default-or-no-argument-constructor-java-class.html

how to configuring a xampp web server for different root directory

You can also put in a new virtual Host entry in the

c:\xampp\apache\conf\httpd-vhosts.conf

like:

<VirtualHost *:80>
  ServerAdmin [email protected]
  DocumentRoot "C:/xampp/htdocs/myproject/web"
  ServerName localhost
  ErrorLog "logs/dummy-host2.example.com-error.log"
  CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Custom Drawable for ProgressBar/ProgressDialog

I was having some trouble using an Indeterminate Progress Dialog with the solution here, after some work and trial and error I got it to work.

First, create the animation you want to use for the Progress Dialog. In my case I used 5 images.

../res/anim/progress_dialog_icon_drawable_animation.xml:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_progress_dialog_drawable_1" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_2" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_3" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_4" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_5" android:duration="150" />
</animation-list>

Where you want to show a ProgressDialog:

dialog = new ProgressDialog(Context.this);
dialog.setIndeterminate(true);
dialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.progress_dialog_icon_drawable_animation));
dialog.setMessage("Some Text");
dialog.show();

This solution is really simple and worked for me, you could extend ProgressDialog and make it override the drawable internally, however, this was really too complicated for what I needed so I did not do it.

How to drop all tables from a database with one SQL query?

If you want to use only one SQL query to delete all tables you can use this:

EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

This is a hidden Stored Procedure in sql server, and will be executed for each table in the database you're connected.

Note: You may need to execute the query a few times to delete all tables due to dependencies.

Note2: To avoid the first note, before running the query, first check if there foreign keys relations to any table. If there are then just disable foreign key constraint by running the query bellow:

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

C# Convert a Base64 -> byte[]

You have to use Convert.FromBase64String to turn a Base64 encoded string into a byte[].

git with IntelliJ IDEA: Could not read from remote repository

I started getting Could not read from remote repository error recently when working with my repository. My specs:

  • IntelliJ IDEA 2017.3.4 (Ultimate Edition)
  • Settings -> Version Control -> Git -> SSH executable -> Built-In
  • Fedora Linux

enter image description here

Of course those problems occurred only when trying to push/pull/fetch etc. from IDE - executing same commands from command line worked like a charm.

Solution that worked for me

I didn't want to switch from Built-In SSH executable to Native, mostly because my native SSH client asks me for the password anytime I try to sync with remote repository.

I solved this problem by switching from SSH remote URL to HTTPS URL. According to this GitHub help page - it is recommended to use HTTPS URL instead of SSH one.

Changing remote URL from SSH to HTTPS

In IntelliJ IDEA go to VCS -> Git -> Remotes..., select row containing "origin" and click on edit button. If you host your repository on GitHub, replace your SSH URL from:

[email protected]:USERNAME/REPOSITORY.git

to:

https://github.com/USERNAME/REPOSITORY.git

You can also get your HTTPS URL from your GitHub repository home page - click on "Clone or download" button and click on "Use HTTPS" link to display your repository's HTTPS URL:

enter image description here

UPDATE 2018-03-13

JetBrains just released IntelliJ IDEA 2017.3.5 that includes fix for SSH access to GitHub - https://blog.jetbrains.com/idea/2018/03/intellij-idea-2017-3-5-fix-for-ssh-access-to-github/

Disabled UIButton not faded or grey

Swift 4+

extension UIButton {
    override open var isEnabled: Bool {
        didSet {
            DispatchQueue.main.async {
                if self.isEnabled {
                    self.alpha = 1.0
                }
                else {
                    self.alpha = 0.6
                }
            }
        }
    }
}

How to use

myButton.isEnabled = false

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

Python check if list items are integers?

You can use exceptional handling as str.digit will only work for integers and can fail for something like this too:

>>> str.isdigit(' 1')
False

Using a generator function:

def solve(lis):                                        
    for x in lis:
        try:
            yield float(x)
        except ValueError:    
            pass

>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> list(solve(mylist))                                    
[1.0, 2.0, 3.0, 4.0, 1.5, 2.6]   #returns converted values

or may be you wanted this:

def solve(lis):
    for x in lis:
        try:
            float(x)
            return True
        except:
            return False
...         
>>> mylist = ['1','orange','2','3','4','apple', '1.5', '2.6']
>>> [x for x in mylist if solve(x)]
['1', '2', '3', '4', '1.5', '2.6']

or using ast.literal_eval, this will work for all types of numbers:

>>> from ast import literal_eval
>>> def solve(lis):
    for x in lis:
        try:
            literal_eval(x)
            return True
        except ValueError:   
             return False
...         
>>> mylist=['1','orange','2','3','4','apple', '1.5', '2.6', '1+0j']
>>> [x for x in mylist if solve(x)]                               
['1', '2', '3', '4', '1.5', '2.6', '1+0j']

Android BroadcastReceiver within Activity

You need to define the receiver as a class in the manifest and it will receive the intent:

<application
  ....
  <receiver android:name=".ToastReceiver">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

And you don't need to create the class manually inside ToastDisplay.

In the code you provided, you must be inside ToastDisplay activity to actually receive the Intent.

How to break out of a loop in Bash?

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

Enabling refreshing for specific html elements only

try to empty your innerHtml everytime. just like this:

_x000D_
_x000D_
Element.innerHtml="";
_x000D_
_x000D_
_x000D_

How to fix a locale setting warning from Perl

Use:

export LANGUAGE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_CTYPE=en_US.UTF-8

It works for Debian. I don't know why - but locale-gen had not results.

Important! It's a temporary solution. It has to be run for each session.

builder for HashMap

You can use:

HashMap<String,Integer> m = Maps.newHashMap(
    ImmutableMap.of("a",1,"b",2)
);

It's not as classy and readable, but does the work.

jQuery using append with effects

When you append to the div, hide it and show it with the argument "slow".

$("#img_container").append(first_div).hide().show('slow');

Algorithm to calculate the number of divisors of a given number

This is the most basic way of computing the number divissors:

class PrintDivisors
{
    public static void main(String args[])
    {

    System.out.println("Enter the number");

    // Create Scanner object for taking input
    Scanner s=new Scanner(System.in);

    // Read an int
    int n=s.nextInt();

        // Loop from 1 to 'n'
        for(int i=1;i<=n;i++)
        {

            // If remainder is 0 when 'n' is divided by 'i',
            if(n%i==0)
            {
            System.out.print(i+", ");
            }
        }

    // Print [not necessary]    
    System.out.print("are divisors of "+n);

    }
}

Uploading/Displaying Images in MVC 4

Have a look at the following

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, 
                            new { enctype = "multipart/form-data" }))
{  
    <label for="file">Upload Image:</label> 
    <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" /> 
}

your controller should have action method which would accept HttpPostedFileBase;

 public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string pic = System.IO.Path.GetFileName(file.FileName);
            string path = System.IO.Path.Combine(
                                   Server.MapPath("~/images/profile"), pic); 
            // file is uploaded
            file.SaveAs(path);

            // save the image path path to the database or you can send image 
            // directly to database
            // in-case if you want to store byte[] ie. for DB
            using (MemoryStream ms = new MemoryStream()) 
            {
                 file.InputStream.CopyTo(ms);
                 byte[] array = ms.GetBuffer();
            }

        }
        // after successfully uploading redirect the user
        return RedirectToAction("actionname", "controller name");
    }

Update 1

In case you want to upload files using jQuery with asynchornously, then try this article.

the code to handle the server side (for multiple upload) is;

 try
    {
        HttpFileCollection hfc = HttpContext.Current.Request.Files;
        string path = "/content/files/contact/";

        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                string fileName = "";
                if (Request.Browser.Browser == "IE")
                {
                    fileName = Path.GetFileName(hpf.FileName);
                }
                else
                {
                    fileName = hpf.FileName;
                }
                string fullPathWithFileName = path + fileName;
                hpf.SaveAs(Server.MapPath(fullPathWithFileName));
            }
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.

UPDATE 2

Alternatively, you can try Async File Uploads in MVC 4.

How to change a css class style through Javascript?

I'd highly recommend jQuery. It then becomes as simple as:

$('#mydiv').addClass('newclass');

You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();

The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.

$('div').addClass('newclass');
$('.oldclass').addClass('newclass');

The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.

How can I fill a div with an image while keeping it proportional?

It's a bit late but I just had the same problem and finally solved it with the help of another stackoverflow post (https://stackoverflow.com/a/29103071).

img {
   object-fit: cover;
   width: 50px;
   height: 100px;
}

Hope this still helps somebody.

Ps: Also works together with max-height, max-width, min-width and min-height css properties. It's espacially handy with using lenght units like 100% or 100vh/100vw to fill the container or the whole browser window.

CSS How to set div height 100% minus nPx

If you need to support IE6, use JavaScript so manage the size of the wrapper div (set the position of the element in pixels after reading the window size). If you don't want to use JavaScript, then this can't be done. There are workarounds but expect a week or two to make it work in every case and in every browser.

For other modern browsers, use this css:

position: absolute;
top: 60px;
bottom: 0px;

Convert string to nullable type (int, double, etc...)

The generic answer provided by "Joel Coehoorn" is good.

But, this is another way without using those GetConverter... or try/catch blocks... (i'm not sure but this may have better performance in some cases):

public static class StrToNumberExtensions
{
    public static short ToShort(this string s, short defaultValue = 0) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int ToInt(this string s, int defaultValue = 0) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long ToLong(this string s, long defaultValue = 0) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal ToDecimal(this string s, decimal defaultValue = 0) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float ToFloat(this string s, float defaultValue = 0) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double ToDouble(this string s, double defaultValue = 0) => double.TryParse(s, out var v) ? v : defaultValue;

    public static short? ToshortNullable(this string s, short? defaultValue = null) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int? ToIntNullable(this string s, int? defaultValue = null) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long? ToLongNullable(this string s, long? defaultValue = null) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal? ToDecimalNullable(this string s, decimal? defaultValue = null) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float? ToFloatNullable(this string s, float? defaultValue = null) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double? ToDoubleNullable(this string s, double? defaultValue = null) => double.TryParse(s, out var v) ? v : defaultValue;
}

Usage is as following:

var x1 = "123".ToInt(); //123
var x2 = "abc".ToInt(); //0
var x3 = "abc".ToIntNullable(); // (int?)null 
int x4 = ((string)null).ToInt(-1); // -1
int x5 = "abc".ToInt(-1); // -1

var y = "19.50".ToDecimal(); //19.50

var z1 = "invalid number string".ToDoubleNullable(); // (double?)null
var z2 = "invalid number string".ToDoubleNullable(0); // (double?)0

Creating an empty file in C#

File.WriteAllText("path", String.Empty);

or

File.CreateText("path").Close();

(13: Permission denied) while connecting to upstream:[nginx]

I have solved my problem by running my Nginx as the user I'm currently logged in with, mulagala.

By default the user as nginx is defined at the very top section of the nginx.conf file as seen below;

user nginx; # Default Nginx user

Change nginx to the name of your current user - here, mulagala.

user mulagala; # Custom Nginx user (as username of the current logged in user)

However, this may not address the actual problem and may actually have casual side effect(s).

For an effective solution, please refer to Joseph Barbere's solution.

WCF error - There was no endpoint listening at

I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!

How do I create a sequence in MySQL?

By creating the increment table you should be aware not to delete inserted rows. reason for this is to avoid storing large dumb data in db with ID-s in it. Otherwise in case of mysql restart it would get max existing row and continue increment from that point as mention in documentation http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html

SVG rounded corner

Just to simplify implementing answer of @hmak.me, here's a commented piece of React code to generate rounded rectangles.

const Rect = ({width, height, round, strokeWidth}) => {
    // overhang over given width and height that we get due to stroke width
    const s = strokeWidth / 2;

    // how many pixels do we need to cut from vertical and horizontal parts
    // due to rounded corners and stroke width
    const over = 2 * round + strokeWidth;

    // lengths of straight lines
    const w = width - over;
    const h = height - over;

    // beware that extra spaces will not be minified
    // they are added for clarity
    const d = `
        M${round + s},${s}
        h${w}
        a${round},${round} 0 0 1 ${round},${round}
        v${h}
        a${round},${round} 0 0 1 -${round},${round}
        h-${w}
        a${round},${round} 0 0 1 -${round},-${round}
        v-${h}
        a${round},${round} 0 0 1 ${round},-${round}
        z
    `;
    return (
        <svg width={width} height={height}>
            <path d={d} fill="none" stroke="black" strokeWidth={strokeWidth} />
        </svg>
    );
};

ReactDOM.render(
    <Rect width={64} height={32} strokeWidth={2} round={4} />,
    document.querySelector('#app'),
);

Jsfiddle link.

How to get device make and model on iOS?

If you have a plist of devices (eg maintained by @Tib above in https://stackoverflow.com/a/17655825/849616) to handle it if Swift 3 you'd use:

extension UIDevice {
    /// Fetches the information about the name of the device.
    ///
    /// - Returns: Should return meaningful device name, if not found will return device system code.
    public static func modelName() -> String {
        let physicalName = deviceSystemCode()
        if let deviceTypes = deviceTypes(), let modelName = deviceTypes[physicalName] as? String {
            return modelName
        }
        return physicalName
    }
}

private extension UIDevice {
    /// Fetches from system the code of the device
    static func deviceSystemCode() -> String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        return identifier
    }

    /// Fetches the plist entries from plist maintained in https://stackoverflow.com/a/17655825/849616
    ///
    /// - Returns: A dictionary with pairs of deviceSystemCode <-> meaningfulDeviceName.
    static func deviceTypes() -> NSDictionary? {
        if let fileUrl = Bundle.main.url(forResource: "your plist name", withExtension: "plist"),
            let configurationDictionary = NSDictionary(contentsOf: fileUrl) {
            return configurationDictionary
        }
        return nil
    }
}

Later you can call it using UIDevice.modelName().

Additional credits go to @Tib (for plist), @Aniruddh Joshi (for deviceSystemCode() function).

How to open an existing project in Eclipse?

This is How I do it.

File -> Open Project from File System -> Existing Project in WorkSpace

Apache shows PHP code instead of executing it

I had the same problem. When I run a php file, the web browser showed me the php code instead of execute it. I had tried many times: uninstall/reinstall the wampserver64, working around the PHP/Apache settings/modules, etc. After 2 days: I realised that when I tried to run the php file within the notepad++ by pressing the default combination "ctrl + alt + shift + R" for chrome. It was trying to execute my php file like: "file///C:/wamp64/www/bla/bla.." in my chrome's address bar. That was my problem. I made the changes according to page Configuring Notepad++ to run php on localhost?. My problem was solved. But after 2 days..

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

I got the same error with vlc component when i changed the framework from 4.5 to 4. but it worked for me when I changed the platform from Any CPU to x86.

How to find nth occurrence of character in a string?

//scala

// throw's -1 if the value isn't present for nth time, even if it is present till n-1 th time. // throw's index if the value is present for nth time

def indexOfWithNumber(tempString:String,valueString:String,numberOfOccurance:Int):Int={
var stabilizeIndex=0 
var tempSubString=tempString 
var tempIndex=tempString.indexOf(valueString) 
breakable
{
for ( i <- 1 to numberOfOccurance)
if ((tempSubString.indexOf(valueString) != -1) && (tempIndex != -1))
{
tempIndex=tempSubString.indexOf(valueString)
tempSubString=tempSubString.substring(tempIndex+1,tempSubString.size) // ADJUSTING FOR 0
stabilizeIndex=stabilizeIndex+tempIndex+1 // ADJUSTING FOR 0
}
else
{ 
stabilizeIndex= -1
tempIndex= 0
break
}
}
stabilizeIndex match { case value if value <= -1 => -1 case _ => stabilizeIndex-1 } // reverting for adjusting 0 previously
}


indexOfWithNumber("bbcfgtbgft","b",3) // 6
indexOfWithNumber("bbcfgtbgft","b",2) //1
indexOfWithNumber("bbcfgtbgft","b",4) //-1

indexOfWithNumber("bbcfgtbcgft","bc",1)  //1
indexOfWithNumber("bbcfgtbcgft","bc",4) //-1
indexOfWithNumber("bbcfgtbcgft","bc",2) //6

How to find memory leak in a C++ code/project?

Search your code for occurrences of new, and make sure that they all occur within a constructor with a matching delete in a destructor. Make sure that this is the only possibly throwing operation in that constructor. A simple way to do this is to wrap all pointers in std::auto_ptr, or boost::scoped_ptr (depending on whether or not you need move semantics). For all future code just ensure that every resource is owned by an object that cleans up the resource in its destructor. If you need move semantics then you can upgrade to a compiler that supports r-value references (VS2010 does I believe) and create move constructors. If you don't want to do that then you can use a variety of tricky techniques involving conscientious usage of swap, or try the Boost.Move library.

Access images inside public folder in laravel

Just use public_path() it will find public folder and address it itself.

<img src=public_path().'/images/imagename.jpg' >

Submitting HTML form using Jquery AJAX

Quick Description of AJAX

AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.

Really quickly there are 4 general web actions GET, POST, PUT, and DELETE; these directly correspond with SELECT/Retreiving DATA, INSERTING DATA, UPDATING/UPSERTING DATA, and DELETING DATA. A default HTML/ASP.Net webform/PHP/Python or any other form action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax.

My code specifically for you (described in code comments):

_x000D_
_x000D_
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post with element id name and name2*/
  var posting = $.post(url, {
    name: $('#name').val(),
    name2: $('#name2').val()
  });

  /* Alerts the results */
  posting.done(function(data) {
    $('#result').text('success');
  });
  posting.fail(function() {
    $('#result').text('failed');
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formoid" action="studentFormInsert.php" title="" method="post">
  <div>
    <label class="title">First Name</label>
    <input type="text" id="name" name="name">
  </div>
  <div>
    <label class="title">Last Name</label>
    <input type="text" id="name2" name="name2">
  </div>
  <div>
    <input type="submit" id="submitButton" name="submitButton" value="Submit">
  </div>
</form>

<div id="result"></div>
_x000D_
_x000D_
_x000D_


Documentation

From jQuery website $.post documentation.

Example: Send form data using ajax requests

$.post("test.php", $("#testform").serialize());

Example: Post a form using ajax and put results in a div

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form action="/" id="searchForm">
            <input type="text" name="s" placeholder="Search..." />
            <input type="submit" value="Search" />
        </form>
        <!-- the result of the search will be rendered inside this div -->
        <div id="result"></div>
        <script>
            /* attach a submit handler to the form */
            $("#searchForm").submit(function(event) {

                /* stop form from submitting normally */
                event.preventDefault();

                /* get some values from elements on the page: */
                var $form = $(this),
                    term = $form.find('input[name="s"]').val(),
                    url = $form.attr('action');

                /* Send the data using post */
                var posting = $.post(url, {
                    s: term
                });

                /* Put the results in a div */
                posting.done(function(data) {
                    var content = $(data).find('#content');
                    $("#result").empty().append(content);
                });
            });
        </script>
    </body>
</html>

Important Note

Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)

How to resize image (Bitmap) to a given size?

In MonoDroid here's how (c#)

/// <summary>
/// Graphics support for resizing images
/// </summary>
public static class Graphics
{
    public static Bitmap ScaleDownBitmap(Bitmap originalImage, float maxImageSize, bool filter)
    {
        float ratio = Math.Min((float)maxImageSize / originalImage.Width, (float)maxImageSize / originalImage.Height);
        int width = (int)Math.Round(ratio * (float)originalImage.Width);
        int height =(int) Math.Round(ratio * (float)originalImage.Height);

        Bitmap newBitmap = Bitmap.CreateScaledBitmap(originalImage, width, height, filter);
        return newBitmap;
    }

    public static Bitmap ScaleBitmap(Bitmap originalImage, int wantedWidth, int wantedHeight)
    {
        Bitmap output = Bitmap.CreateBitmap(wantedWidth, wantedHeight, Bitmap.Config.Argb8888);
        Canvas canvas = new Canvas(output);
        Matrix m = new Matrix();
        m.SetScale((float)wantedWidth / originalImage.Width, (float)wantedHeight / originalImage.Height);
        canvas.DrawBitmap(originalImage, m, new Paint());
        return output;
    }

}

How do I get the YouTube video ID from a URL?

In C#, it looks like this:

public static string GetYouTubeId(string url) {
    var regex = @"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?|watch)\/|.*[?&amp;]v=)|youtu\.be\/)([^""&amp;?\/ ]{11})";

    var match = Regex.Match(url, regex);

    if (match.Success)
    {
        return match.Groups[1].Value;
    }

    return url;
  }

Feel free to modify.

How is the AND/OR operator represented as in Regular Expressions?

Or you can use this:

^(?:part[12]|(part)1,\12)$

Move a view up only when the keyboard covers an input field

Your problem is well explained in this document by Apple. Example code on this page (at Listing 4-1) does exactly what you need, it will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew. The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:

Declare a variable

var activeField: UITextField?

then add these methods

 func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.scrollEnabled = true
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeFieldPresent = activeField
    {
        if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
        {
            self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
        }
    }


}


func keyboardWillBeHidden(notification: NSNotification)
{
    //Once keyboard disappears, restore original positions
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.scrollEnabled = false

}

func textFieldDidBeginEditing(textField: UITextField!)
{
    activeField = textField
}

func textFieldDidEndEditing(textField: UITextField!)
{
    activeField = nil
}

Be sure to declare your ViewController as UITextFieldDelegate and set correct delegates in your initialization methods: ex:

self.you_text_field.delegate = self

And remember to call registerForKeyboardNotifications on viewInit and deregisterFromKeyboardNotifications on exit.

Edit/Update: Swift 4.2 Syntax

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}

Using setattr() in python

You are setting self.name to the string "get_thing", not the function get_thing.

If you want self.name to be a function, then you should set it to one:

setattr(self, 'name', self.get_thing)

However, that's completely unnecessary for your other code, because you could just call it directly:

value_returned = self.get_thing()

Notepad++ incrementally replace

(Posting in case someone might have a use of it).

I was looking for a solution for a problem a bit more sophisticated than OP - replacing EVERY occurrence of something with the number by same thing with incremented number

E.g. Replacing something like this:

<row id="1" />
<row id="2" />
<row id="1" />
<row id="3" />
<row id="1" />

By this:

<row id="2" />
<row id="3" />
<row id="2" />
<row id="4" />
<row id="2" />

Couldnt find the solution online so I wrote my own script in groovy (a bit ugly but does the job):

 /**
 * <p> Finds words that matches template and increases them by 1.
 * '_' in word template represents number.
 *
 * <p> E.g. if template equals 'Row="_"', then:
 * ALL Row=0 will be replaced by Row="1"
 * All Row=1 will be replaced by Row="2"
 * <p> Warning - your find template might not work properly if _ is the last character of it
 * etc.
 * <p> Requirments:
 * - Original text does not contain tepmlate string
 * - Only numbers in non-disrupted sequence are incremented and replaced
 * (i.e. from example below, if Row=4 exists in original text, but Row=3 not, than Row=4 will NOT be 
 * replaced by Row=5)
 */
def replace_inc(String text, int startingIndex, String findTemplate) {
    assert findTemplate.contains('_') : 'search template needs to contain "_" placeholder'
    assert !(findTemplate.replaceFirst('_','').contains('_')) : 'only one "_" placeholder is allowed'
    assert !text.contains('_____') : 'input text should not contain "______" (5 underscores)'
    while (true) {
        findString = findTemplate.replace("_",(startingIndex).toString())
        if (!text.contains(findString)) break;
        replaceString = findTemplate.replace("_", "_____"+(++startingIndex).toString())
        text = text.replaceAll(findString, replaceString)
    }
    return text.replaceAll("_____","") // get rid of '_____' character
}

// input
findTemplate = 'Row="_"'
path = /C:\TEMP\working_copy.txt/
startingIndex = 0

// do stuff
f = new File(path)
outText = replace_inc(f.text,startingIndex,findTemplate)
println "Results \n: " + outText
f.withWriter { out -> out.println outText }
println "Results written to $f"

How to add "on delete cascade" constraints?

Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:

ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
  FOREIGN KEY ("parentId")
  REFERENCES "Parent"(id)
  ON DELETE CASCADE;

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

Call a stored procedure with parameter in c#

As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/

SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
    sqlAccess.Procedure()
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtFirstName.Text)
         .AddSqlParameter("@FirstName", SqlDbType.VarChar, txtLastName.Text)
         .ExecuteNonQuery("StoredProcedureName");

List of All Folders and Sub-folders

As well as find listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh for example...

ls -lad **/*(/)

...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...

find . -type d -exec ls -ld {} \;

(not quite as easy as the other answers suggest)

The benefit of find is that it's more independent of the shell - more portable, even for system() calls from within a C/C++ program etc..

Add data to JSONObject

The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.

What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!

I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.

So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:

import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;

//  create and initialize an object 
public static JSONObject buildObject( final SimpleEntry... entries ) { 
    JSONObject object = new JSONObject();
    for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
    return object;
}

//  nest a list of objects inside another                          
public static void putObjects( final JSONObject parentObject, final String key,
                               final JSONObject... objects ) { 
    List objectList = new ArrayList<JSONObject>();
    for( JSONObject o : objects ) objectList.add( o );
    parentObject.put( key, objectList );
}   

Implementation example:

JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
    buildObject( 
        new SimpleEntry( "child1Key1", "someValue" )
      , new SimpleEntry( "child1Key2", "someValue" ) 
    )
  , buildObject( 
        new SimpleEntry( "child2Key1", "someValue" )
      , new SimpleEntry( "child2Key2", "someValue" ) 
    )
);      

Adobe Acrobat Pro make all pages the same dimension

  • Open the PDF in MacOS´ Preview App
  • Chose File menu –> Export as PDF
  • In the export dialog klick the Details button an select your page size
  • Click save

All pages of the resulting document will be scaled to that size. The resulting file size is nearly identical to the original PDF, so I conclude, that image resolutions/compressions are not changed.

Hints:

  1. I am not sure whether the "Export as PDF" menu item is available by default or only if Adobe Acrobat is installed.

  2. My first trial was to use Preview App and print (!) into a new PDF, but this leads to additional margins around the page content.

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

A lot of people are going to say this is a bad answer because it is not best practice but you can also convert it to a List before your where.

result = result.ToList().Where(p => date >= p.DOB);

Slauma's answer is better, but this would work as well. This cost more because ToList() will execute the Query against the database and move the results into memory.

Git blame -- prior commits?

Building on DavidN's answer and I want to follow renamed file:

LINE=8 FILE=Info.plist; for commit in $(git log --format='%h%%' --name-only --follow -- $FILE | xargs echo | perl -pe 's/\%\s/,/g'); do hash=$(echo $commit | cut -f1 -d ','); fileMayRenamed=$(echo $commit | cut -f2 -d ','); git blame -n -L$LINE,+1 $hash -- $fileMayRenamed; done | sed '$!N; /^\(.*\)\n\1$/!P; D'

ref: nicely display file rename history in git log

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

In Flask you just need to write:

curs = conn.cursor()
curs.execute("ROLLBACK")
conn.commit()

P.S. Documentation goes here https://www.postgresql.org/docs/9.4/static/sql-rollback.html

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

Run -> Edit configurations -> Select your build configuration -> JRE - change Default to one of actual JDK paths

static files with express.js

In the newest version of express the "createServer" is deprecated. This example works for me:

var express = require('express');
var app = express();
var path = require('path');

//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); //  "public" off of current is root

app.listen(80);
console.log('Listening on port 80');

javac : command not found

Linux Mint 19.3

I installed Java Oracle manually, like this:

$ sudo ln -s /usr/lib/jvm/java-1.8.0_211/bin/javac /usr/bin/javac

how to remove "," from a string in javascript

If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.

Here the script that can remove up to 12 commas:

function uncomma(x) {
  var string1 = x;
  for (y = 0; y < 12; y++) {
    string1 = string1.replace(/\,/g, '');
  }
  return string1;
}

Modify that for loop if you need bigger numbers.

Bootstrap 3: how to make head of dropdown link clickable in navbar

This topic is super old, but I needed a solution that worked on desktop AND mobile and none of these seemed to work for me. Unfortunately, this is the solution I came up with that involves checking the window width and comparing it to the mobile menu breakpoint:

$( 'a.dropdown-toggle' ).on( 'click', function( e ) {
    var $a = $( this ),
        $parent = $a.parent( 'li' ),
        mobile_bp = 767, // Default breakpoint, may need to change this.
        window_width = $( window ).width(),
        is_mobile = window_width <= mobile_bp;

    if ( is_mobile && ! $parent.hasClass( 'open' ) ) {
        e.preventDefault();
        return false;
    }

    location.href = $a.attr( 'href' );
    return true;
});

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Detecting sheet of paper is kinda old school. If you want to tackle skew detection then it is better if you straightaway aim for text line detection. With this you will get the extremas left, right, top and bottom. Discard any graphics in the image if you dont want and then do some statistics on the text line segments to find the most occurring angle range or rather angle. This is how you will narrow down to a good skew angle. Now after this you put these parameters the skew angle and the extremas to deskew and chop the image to what is required.

As for the current image requirement, it is better if you try CV_RETR_EXTERNAL instead of CV_RETR_LIST.

Another method of detecting edges is to train a random forests classifier on the paper edges and then use the classifier to get the edge Map. This is by far a robust method but requires training and time.

Random forests will work with low contrast difference scenarios for example white paper on roughly white background.

How do I exit the Vim editor?

If you want to quit without saving in Vim and have Vim return a non-zero exit code, you can use :cq.

I use this all the time because I can't be bothered to pinky shift for !. I often pipe things to Vim which don't need to be saved in a file. We also have an odd SVN wrapper at work which must be exited with a non-zero value in order to abort a checkin.

How do I remove repeated elements from ArrayList?

        List<String> result = new ArrayList<String>();
        Set<String> set = new LinkedHashSet<String>();
        String s = "ravi is a good!boy. But ravi is very nasty fellow.";
        StringTokenizer st = new StringTokenizer(s, " ,. ,!");
        while (st.hasMoreTokens()) {
            result.add(st.nextToken());
        }
         System.out.println(result);
         set.addAll(result);
        result.clear();
        result.addAll(set);
        System.out.println(result);

output:
[ravi, is, a, good, boy, But, ravi, is, very, nasty, fellow]
[ravi, is, a, good, boy, But, very, nasty, fellow]

How to COUNT rows within EntityFramework without loading contents?

This is my code:

IQueryable<AuctionRecord> records = db.AuctionRecord;
var count = records.Count();

Make sure the variable is defined as IQueryable then when you use Count() method, EF will execute something like

select count(*) from ...

Otherwise, if the records is defined as IEnumerable, the sql generated will query the entire table and count rows returned.

Checking the equality of two slices

This is just example using reflect.DeepEqual() that is given in @VictorDeryagin's answer.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := []int {4,5,6}
    b := []int {4,5,6}
    c := []int {4,5,6,7}

    fmt.Println(reflect.DeepEqual(a, b))
    fmt.Println(reflect.DeepEqual(a, c))

}

Result:

true
false

Try it in Go Playground

Most efficient way to increment a Map value in Java

Are you sure that this is a bottleneck? Have you done any performance analysis?

Try using the NetBeans profiler (its free and built into NB 6.1) to look at hotspots.

Finally, a JVM upgrade (say from 1.5->1.6) is often a cheap performance booster. Even an upgrade in build number can provide good performance boosts. If you are running on Windows and this is a server class application, use -server on the command line to use the Server Hotspot JVM. On Linux and Solaris machines this is autodetected.

Illegal Escape Character "\"

The character '\' is a special character and needs to be escaped when used as part of a String, e.g., "\". Here is an example of a string comparison using the '\' character:

if (invName.substring(j,k).equals("\\")) {...}

You can also perform direct character comparisons using logic similar to the following:

if (invName.charAt(j) == '\\') {...}

How to concatenate two strings in SQL Server 2005

DECLARE @COMBINED_STRINGS AS VARCHAR(50),
        @STRING1 AS VARCHAR(20),
        @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;

SELECT @COMBINED_STRINGS;

SELECT '2' + '3';

I typed this in a sql file named TEST.sql and I run it. I got the following out put.

+-------------------+
| @COMBINED_STRINGS |
+-------------------+
|                 0 |
+-------------------+
1 row in set (0.00 sec)

+-----------+
| '2' + '3' |
+-----------+
|         5 |
+-----------+
1 row in set (0.00 sec)

After looking into this issue a bit more I found the best and sure sort way for string concatenation in SQL is by using CONCAT method. So I made the following changes in the same file.

#DECLARE @COMBINED_STRINGS AS VARCHAR(50),
 #       @STRING1 AS VARCHAR(20),
 #       @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
#SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SET @COMBINED_STRINGS = (SELECT CONCAT(@STRING1, @STRING2));

SELECT @COMBINED_STRINGS;

#SELECT '2' + '3';
SELECT CONCAT('2','3');

and after executing the file this was the output.

+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| rupesh'smalviya   |
+-------------------+
1 row in set (0.00 sec)

+-----------------+
| CONCAT('2','3') |
+-----------------+
| 23              |
+-----------------+
1 row in set (0.00 sec)

SQL version I am using is: 14.14

How do I load external fonts into an HTML document?

Take a look at this A List Apart article. The pertinent CSS is:

@font-face {
  font-family: "Kimberley";
  src: url(http://www.princexml.com/fonts/larabie/kimberle.ttf) format("truetype");
}
h1 { font-family: "Kimberley", sans-serif }

The above will work in Chrome/Safari/FireFox. As Paul D. Waite pointed out in the comments you can get it to work with IE if you convert the font to the EOT format.

The good news is that this seems to degrade gracefully in older browsers, so as long as you're aware and comfortable with the fact that not all users will see the same font, it's safe to use.

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

Below solution is a clean work around.It does not compromises security because we are using same strict firewall.

The Steps for fixing is as below:

STEP 1 : Create a Class overriding StrictHttpFirewall as below.

package com.biz.brains.project.security.firewall;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpMethod;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;

public class CustomStrictHttpFirewall implements HttpFirewall {
    private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.unmodifiableSet(Collections.emptySet());

    private static final String ENCODED_PERCENT = "%25";

    private static final String PERCENT = "%";

    private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections.unmodifiableList(Arrays.asList("%2e", "%2E"));

    private static final List<String> FORBIDDEN_SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));

    private static final List<String> FORBIDDEN_FORWARDSLASH = Collections.unmodifiableList(Arrays.asList("%2f", "%2F"));

    private static final List<String> FORBIDDEN_BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));

    private Set<String> encodedUrlBlacklist = new HashSet<String>();

    private Set<String> decodedUrlBlacklist = new HashSet<String>();

    private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();

    public CustomStrictHttpFirewall() {
        urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);

        this.encodedUrlBlacklist.add(ENCODED_PERCENT);
        this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        this.decodedUrlBlacklist.add(PERCENT);
    }

    public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
        this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
    }

    public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
        if (allowedHttpMethods == null) {
            throw new IllegalArgumentException("allowedHttpMethods cannot be null");
        }
        if (allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            this.allowedHttpMethods = ALLOW_ANY_HTTP_METHOD;
        } else {
            this.allowedHttpMethods = new HashSet<>(allowedHttpMethods);
        }
    }

    public void setAllowSemicolon(boolean allowSemicolon) {
        if (allowSemicolon) {
            urlBlacklistsRemoveAll(FORBIDDEN_SEMICOLON);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        }
    }

    public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
        if (allowUrlEncodedSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        }
    }

    public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
        if (allowUrlEncodedPeriod) {
            this.encodedUrlBlacklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
        } else {
            this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        }
    }

    public void setAllowBackSlash(boolean allowBackSlash) {
        if (allowBackSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_BACKSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
        }
    }

    public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
        if (allowUrlEncodedPercent) {
            this.encodedUrlBlacklist.remove(ENCODED_PERCENT);
            this.decodedUrlBlacklist.remove(PERCENT);
        } else {
            this.encodedUrlBlacklist.add(ENCODED_PERCENT);
            this.decodedUrlBlacklist.add(PERCENT);
        }
    }

    private void urlBlacklistsAddAll(Collection<String> values) {
        this.encodedUrlBlacklist.addAll(values);
        this.decodedUrlBlacklist.addAll(values);
    }

    private void urlBlacklistsRemoveAll(Collection<String> values) {
        this.encodedUrlBlacklist.removeAll(values);
        this.decodedUrlBlacklist.removeAll(values);
    }

    @Override
    public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
        rejectForbiddenHttpMethod(request);
        rejectedBlacklistedUrls(request);

        if (!isNormalized(request)) {
            request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL was not normalized."));
        }

        String requestUri = request.getRequestURI();
        if (!containsOnlyPrintableAsciiCharacters(requestUri)) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The requestURI was rejected because it can only contain printable ASCII characters."));
        }
        return new FirewalledRequest(request) {
            @Override
            public void reset() {
            }
        };
    }

    private void rejectForbiddenHttpMethod(HttpServletRequest request) {
        if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            return;
        }
        if (!this.allowedHttpMethods.contains(request.getMethod())) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the HTTP method \"" +
                    request.getMethod() +
                    "\" was not included within the whitelist " +
                    this.allowedHttpMethods));
        }
    }

    private void rejectedBlacklistedUrls(HttpServletRequest request) {
        for (String forbidden : this.encodedUrlBlacklist) {
            if (encodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
        for (String forbidden : this.decodedUrlBlacklist) {
            if (decodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
    }

    @Override
    public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
        return new FirewalledResponse(response);
    }

    private static Set<String> createDefaultAllowedHttpMethods() {
        Set<String> result = new HashSet<>();
        result.add(HttpMethod.DELETE.name());
        result.add(HttpMethod.GET.name());
        result.add(HttpMethod.HEAD.name());
        result.add(HttpMethod.OPTIONS.name());
        result.add(HttpMethod.PATCH.name());
        result.add(HttpMethod.POST.name());
        result.add(HttpMethod.PUT.name());
        return result;
    }

    private static boolean isNormalized(HttpServletRequest request) {
        if (!isNormalized(request.getRequestURI())) {
            return false;
        }
        if (!isNormalized(request.getContextPath())) {
            return false;
        }
        if (!isNormalized(request.getServletPath())) {
            return false;
        }
        if (!isNormalized(request.getPathInfo())) {
            return false;
        }
        return true;
    }

    private static boolean encodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getContextPath(), value)) {
            return true;
        }
        return valueContains(request.getRequestURI(), value);
    }

    private static boolean decodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getServletPath(), value)) {
            return true;
        }
        if (valueContains(request.getPathInfo(), value)) {
            return true;
        }
        return false;
    }

    private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
        int length = uri.length();
        for (int i = 0; i < length; i++) {
            char c = uri.charAt(i);
            if (c < '\u0020' || c > '\u007e') {
                return false;
            }
        }

        return true;
    }

    private static boolean valueContains(String value, String contains) {
        return value != null && value.contains(contains);
    }

    private static boolean isNormalized(String path) {
        if (path == null) {
            return true;
        }

        if (path.indexOf("//") > -1) {
            return false;
        }

        for (int j = path.length(); j > 0;) {
            int i = path.lastIndexOf('/', j - 1);
            int gap = j - i;

            if (gap == 2 && path.charAt(i + 1) == '.') {
                // ".", "/./" or "/."
                return false;
            } else if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
                return false;
            }

            j = i;
        }

        return true;
    }

}

STEP 2 : Create a FirewalledResponse class

package com.biz.brains.project.security.firewall;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

class FirewalledResponse extends HttpServletResponseWrapper {
    private static final Pattern CR_OR_LF = Pattern.compile("\\r|\\n");
    private static final String LOCATION_HEADER = "Location";
    private static final String SET_COOKIE_HEADER = "Set-Cookie";

    public FirewalledResponse(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void sendRedirect(String location) throws IOException {
        // TODO: implement pluggable validation, instead of simple blacklisting.
        // SEC-1790. Prevent redirects containing CRLF
        validateCrlf(LOCATION_HEADER, location);
        super.sendRedirect(location);
    }

    @Override
    public void setHeader(String name, String value) {
        validateCrlf(name, value);
        super.setHeader(name, value);
    }

    @Override
    public void addHeader(String name, String value) {
        validateCrlf(name, value);
        super.addHeader(name, value);
    }

    @Override
    public void addCookie(Cookie cookie) {
        if (cookie != null) {
            validateCrlf(SET_COOKIE_HEADER, cookie.getName());
            validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
            validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
            validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
            validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
        }
        super.addCookie(cookie);
    }

    void validateCrlf(String name, String value) {
        if (hasCrlf(name) || hasCrlf(value)) {
            throw new IllegalArgumentException(
                    "Invalid characters (CR/LF) in header " + name);
        }
    }

    private boolean hasCrlf(String value) {
        return value != null && CR_OR_LF.matcher(value).find();
    }
}

STEP 3: Create a custom Filter to suppress the RejectedException

package com.biz.brains.project.security.filter;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestRejectedExceptionFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            try {
                RequestRejectedException requestRejectedException=(RequestRejectedException) servletRequest.getAttribute("isNormalized");
                if(Objects.nonNull(requestRejectedException)) {
                    throw requestRejectedException;
                }else {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } catch (RequestRejectedException requestRejectedException) {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                log
                    .error(
                            "request_rejected: remote={}, user_agent={}, request_url={}",
                            httpServletRequest.getRemoteHost(),  
                            httpServletRequest.getHeader(HttpHeaders.USER_AGENT),
                            httpServletRequest.getRequestURL(), 
                            requestRejectedException
                    );

                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
}

STEP 4: Add the custom filter to spring filter chain in security configuration

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.addFilterBefore(new RequestRejectedExceptionFilter(),
             ChannelProcessingFilter.class);
}

Now using above fix, we can handle RequestRejectedException with Error 404 page.

Unresolved external symbol on static class members

Since this is the first SO thread that seemed to come up for me when searching for "unresolved externals with static const members" in general, I'll leave another hint to solve one problem with unresolved externals here:

For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.
Still, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.

How to sort an array based on the length of each element?

This code should do the trick:

var array = ["ab", "abcdefgh", "abcd"];

array.sort(function(a, b){return b.length - a.length});

console.log(JSON.stringify(array, null, '\t'));

JQuery create new select option

What about

var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text('myText');
$('#county').append(option);

How to detect a route change in Angular?

For Angular 7 someone should write like:

this.router.events.subscribe((event: Event) => {})


A detailed example can be as follows:

import { Component } from '@angular/core'; 
import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';

@Component({
    selector: 'app-root',
    template: `<router-outlet></router-outlet>`
})
export class AppComponent {

    constructor(private router: Router) {

        this.router.events.subscribe((event: Event) => {
            if (event instanceof NavigationStart) {
                // Show loading indicator
            }

            if (event instanceof NavigationEnd) {
                // Hide loading indicator
            }

            if (event instanceof NavigationError) {
                // Hide loading indicator

                // Present error to user
                console.log(event.error);
            }
        });

   }
}

Error in contrasts when defining a linear model in R

If your independent variable (RHS variable) is a factor or a character taking only one value then that type of error occurs.

Example: iris data in R

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species, data=iris))

# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Species, data = iris)

# Coefficients:
#       (Intercept)        Sepal.Width  Speciesversicolor   Speciesvirginica  
#            2.2514             0.8036             1.4587             1.9468  

Now, if your data consists of only one species:

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species,
              data=iris[iris$Species == "setosa", ]))
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
#   contrasts can be applied only to factors with 2 or more levels

If the variable is numeric (Sepal.Width) but taking only a single value say 3, then the model runs but you will get NA as coefficient of that variable as follows:

(model2 <-lm(Sepal.Length ~ Sepal.Width + Species,
             data=iris[iris$Sepal.Width == 3, ]))

# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Species, 
#    data = iris[iris$Sepal.Width == 3, ])

# Coefficients:
#       (Intercept)        Sepal.Width  Speciesversicolor   Speciesvirginica  
#             4.700                 NA              1.250              2.017

Solution: There is not enough variation in dependent variable with only one value. So, you need to drop that variable, irrespective of whether that is numeric or character or factor variable.

Updated as per comments: Since you know that the error will only occur with factor/character, you can focus only on those and see whether the length of levels of those factor variables is 1 (DROP) or greater than 1 (NODROP).

To see, whether the variable is a factor or not, use the following code:

(l <- sapply(iris, function(x) is.factor(x)))
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#        FALSE        FALSE        FALSE        FALSE         TRUE 

Then you can get the data frame of factor variables only

m <- iris[, l]

Now, find the number of levels of factor variables, if this is one you need to drop that

ifelse(n <- sapply(m, function(x) length(levels(x))) == 1, "DROP", "NODROP")

Note: If the levels of factor variable is only one then that is the variable, you have to drop.

Package structure for a Java project?

I would suggest creating your package structure by feature, and not by the implementation layer. A good write up on this is Java practices: Package by feature, not layer

replace \n and \r\n with <br /> in java

Since my account is new I can't up-vote Nino van Hooff's answer. If your strings are coming from a Windows based source such as an aspx based server, this solution does work:

rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "<br />");

Seems to be a weird character set issue as the double back-slashes are being interpreted as single slash escape characters. Hence the need for the quadruple slashes above.

Again, under most circumstances "(\\r\\n|\\n)" should work, but if your strings are coming from a Windows based source try the above.

Just an FYI tried everything to correct the issue I was having replacing those line endings. Thought at first was failed conversion from Windows-1252 to UTF-8. But that didn't working either. This solution is what finally did the trick. :)

Set Focus on EditText

new OnEditorActionListener(){
   @Override
   public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
      editText.requestFocus();
      //used ******* return true ******
      return **true**;
   }
} 

Express.js - app.listen vs server.listen

Just for punctuality purpose and extend a bit Tim answer.
From official documentation:

The app returned by express() is in fact a JavaScript Function, DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handle requests.

This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Going from MM/DD/YYYY to DD-MMM-YYYY in java

java.time

You should use java.time classes with Java 8 and later. To use java.time, add:

import java.time.* ;

Below is an example, how you can format date.

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate); 
System.out.println(formatter.format(localDate));

Using app.config in .Net Core

It is possible to use your usual System.Configuration even in .NET Core 2.0 on Linux. Try this test example:

  1. Created a .NET Standard 2.0 Library (say MyLib.dll)
  2. Added the NuGet package System.Configuration.ConfigurationManager v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library v2.0.0 (I hope that changes)
  3. All your C# classes derived from ConfigurationSection or ConfigurationElement go into MyLib.dll. For example MyClass.cs derives from ConfigurationSection and MyAccount.cs derives from ConfigurationElement. Implementation details are out of scope here but Google is your friend.
  4. Create a .NET Core 2.0 app (e.g. a console app, MyApp.dll). .NET Core apps end with .dll rather than .exe in Framework.
  5. Create an app.config in MyApp with your custom configuration sections. This should obviously match your class designs in #3 above. For example:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
  </configSections>
  <myCustomConfig>
    <myAccount id="007" />
  </myCustomConfig>
</configuration>

That's it - you'll find that the app.config is parsed properly within MyApp and your existing code within MyLib works just fine. Don't forget to run dotnet restore if you switch platforms from Windows (dev) to Linux (test).

Additional workaround for test projects

If you're finding that your App.config is not working in your test projects, you might need this snippet in your test project's .csproj (e.g. just before the ending </Project>). It basically copies App.config into your output folder as testhost.dll.config so dotnet test picks it up.

  <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
  <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
  </Target>
  <!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->

Linq Select Group By

    from p in PriceLog
    group p by p.LogDateTime.ToString("MMM") into g
    select new 
    { 
        LogDate = g.Key.ToString("MMM yyyy"),
        GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
        SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    }

Checking if a variable is not nil and not zero in ruby

I believe the following is good enough for ruby code. I don't think I could write a unit test that shows any difference between this and the original.

if discount != 0
end

Mailto links do nothing in Chrome but work in Firefox?

The usual <a href="mailto:[email protected]"></a> should work, but remember you must have a default email program set on your computer. For ex, I'm using Ubuntu 14.04 and the default email is thunderbird, which works fine.

Read from a gzip file in python

python: read lines from compressed text files

Using gzip.GzipFile:

import gzip

with gzip.open('input.gz','r') as fin:        
    for line in fin:        
        print('got line', line)

How to use a calculated column to calculate another column in the same view

In SQL Server

You can do this using With CTE

WITH common_table_expression (Transact-SQL)

CREATE TABLE tab(ColumnA DECIMAL(10,2), ColumnB DECIMAL(10,2), ColumnC DECIMAL(10,2))

INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2),(3, 15, 6),(7, 14, 3)

WITH tab_CTE (ColumnA, ColumnB, ColumnC,calccolumn1)  
AS  
(  
Select
    ColumnA,
    ColumnB,
    ColumnC,
    ColumnA + ColumnB As calccolumn1
  from tab
)  

SELECT
  ColumnA,
  ColumnB,
  calccolumn1,
  calccolumn1 / ColumnC AS calccolumn2
FROM  tab_CTE

DBFiddle Demo

JavaScript get window X/Y position for scroll

Using pure javascript you can use Window.scrollX and Window.scrollY

window.addEventListener("scroll", function(event) {
    var top = this.scrollY,
        left =this.scrollX;
}, false);

Notes

The pageXOffset property is an alias for the scrollX property, and The pageYOffset property is an alias for the scrollY property:

window.pageXOffset == window.scrollX; // always true
window.pageYOffset == window.scrollY; // always true

Here is a quick demo

_x000D_
_x000D_
window.addEventListener("scroll", function(event) {_x000D_
  _x000D_
    var top = this.scrollY,_x000D_
        left = this.scrollX;_x000D_
  _x000D_
    var horizontalScroll = document.querySelector(".horizontalScroll"),_x000D_
        verticalScroll = document.querySelector(".verticalScroll");_x000D_
    _x000D_
    horizontalScroll.innerHTML = "Scroll X: " + left + "px";_x000D_
      verticalScroll.innerHTML = "Scroll Y: " + top + "px";_x000D_
  _x000D_
}, false);
_x000D_
*{box-sizing: border-box}_x000D_
:root{height: 200vh;width: 200vw}_x000D_
.wrapper{_x000D_
    position: fixed;_x000D_
    top:20px;_x000D_
    left:0px;_x000D_
    width:320px;_x000D_
    background: black;_x000D_
    color: green;_x000D_
    height: 64px;_x000D_
}_x000D_
.wrapper div{_x000D_
    display: inline;_x000D_
    width: 50%;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    line-height: 64px_x000D_
}_x000D_
.horizontalScroll{color: orange}
_x000D_
<div class=wrapper>_x000D_
    <div class=horizontalScroll>Scroll (x,y) to </div>_x000D_
    <div class=verticalScroll>see me in action</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Propagate all arguments in a bash shell script

My SUN Unix has a lot of limitations, even "$@" was not interpreted as desired. My workaround is ${@}. For example,

#!/bin/ksh
find ./ -type f | xargs grep "${@}"

By the way, I had to have this particular script because my Unix also does not support grep -r

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

How to check if type of a variable is string?

Alternative way for Python 2, without using basestring:

isinstance(s, (str, unicode))

But still won't work in Python 3 since unicode isn't defined (in Python 3).

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

Detecting user leaving page with react-router

For react-router v3.x

I had the same issue where I needed a confirmation message for any unsaved change on the page. In my case, I was using React Router v3, so I could not use <Prompt />, which was introduced from React Router v4.

I handled 'back button click' and 'accidental link click' with the combination of setRouteLeaveHook and history.pushState(), and handled 'reload button' with onbeforeunload event handler.

setRouteLeaveHook (doc) & history.pushState (doc)

  • Using only setRouteLeaveHook was not enough. For some reason, the URL was changed although the page remained the same when 'back button' was clicked.

      // setRouteLeaveHook returns the unregister method
      this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
        this.props.route,
        this.routerWillLeave
      );
    
      ...
    
      routerWillLeave = nextLocation => {
        // Using native 'confirm' method to show confirmation message
        const result = confirm('Unsaved work will be lost');
        if (result) {
          // navigation confirmed
          return true;
        } else {
          // navigation canceled, pushing the previous path
          window.history.pushState(null, null, this.props.route.path);
          return false;
        }
      };
    

onbeforeunload (doc)

  • It is used to handle 'accidental reload' button

    window.onbeforeunload = this.handleOnBeforeUnload;
    
    ...
    
    handleOnBeforeUnload = e => {
      const message = 'Are you sure?';
      e.returnValue = message;
      return message;
    }
    

Below is the full component that I have written

  • note that withRouter is used to have this.props.router.
  • note that this.props.route is passed down from the calling component
  • note that currentState is passed as prop to have initial state and to check any change

    import React from 'react';
    import PropTypes from 'prop-types';
    import _ from 'lodash';
    import { withRouter } from 'react-router';
    import Component from '../Component';
    import styles from './PreventRouteChange.css';
    
    class PreventRouteChange extends Component {
      constructor(props) {
        super(props);
        this.state = {
          // initialize the initial state to check any change
          initialState: _.cloneDeep(props.currentState),
          hookMounted: false
        };
      }
    
      componentDidUpdate() {
    
       // I used the library called 'lodash'
       // but you can use your own way to check any unsaved changed
        const unsaved = !_.isEqual(
          this.state.initialState,
          this.props.currentState
        );
    
        if (!unsaved && this.state.hookMounted) {
          // unregister hooks
          this.setState({ hookMounted: false });
          this.unregisterRouteHook();
          window.onbeforeunload = null;
        } else if (unsaved && !this.state.hookMounted) {
          // register hooks
          this.setState({ hookMounted: true });
          this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
            this.props.route,
            this.routerWillLeave
          );
          window.onbeforeunload = this.handleOnBeforeUnload;
        }
      }
    
      componentWillUnmount() {
        // unregister onbeforeunload event handler
        window.onbeforeunload = null;
      }
    
      handleOnBeforeUnload = e => {
        const message = 'Are you sure?';
        e.returnValue = message;
        return message;
      };
    
      routerWillLeave = nextLocation => {
        const result = confirm('Unsaved work will be lost');
        if (result) {
          return true;
        } else {
          window.history.pushState(null, null, this.props.route.path);
          if (this.formStartEle) {
            this.moveTo.move(this.formStartEle);
          }
          return false;
        }
      };
    
      render() {
        return (
          <div>
            {this.props.children}
          </div>
        );
      }
    }
    
    PreventRouteChange.propTypes = propTypes;
    
    export default withRouter(PreventRouteChange);
    

Please let me know if there is any question :)

How to quit android application programmatically

Similar to @MobileMateo, but in Kotlin

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    this.finishAffinity()
} else{
    this.finish()
    System.exit(0)
}

How to copy a string of std::string type in C++?

strcpy example:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]="Sample string" ;
  char str2[40] ;
  strcpy (str2,str1) ;
  printf ("str1: %s\n",str1) ;
  return 0 ;
}

Output: str1: Sample string

Your case:

A simple = operator should do the job.

string str1="Sample string" ;
string str2 = str1 ;

Checking letter case (Upper/Lower) within a string in Java

To determine if a String contains an upper case and a lower case char, you can use the following:

boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());

This allows you to check:

if(!hasUppercase)System.out.println("Must have an uppercase Character");
if(!hasLowercase)System.out.println("Must have a lowercase Character");

Essentially, this works by checking if the String is equal to its entirely lowercase, or uppercase equivalent. If this is not true, then there must be at least one character that is uppercase or lowercase.

As for your other conditions, these can be satisfied in a similar way:

boolean isAtLeast8   = password.length() >= 8;//Checks for at least 8 characters
boolean hasSpecial   = !password.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
boolean noConditions = !(password.contains("AND") || password.contains("NOT"));//Check that it doesn't contain AND or NOT

With suitable error messages as above.

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

What is the difference between Digest and Basic Authentication?

Digest Authentication communicates credentials in an encrypted form by applying a hash function to: the username, the password, a server supplied nonce value, the HTTP method and the requested URI.

Whereas Basic Authentication uses non-encrypted base64 encoding.

Therefore, Basic Authentication should generally only be used where transport layer security is provided such as https.

See RFC-2617 for all the gory details.

Which JDK version (Language Level) is required for Android Studio?

Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

Split Div Into 2 Columns Using CSS

For whatever reason I've never liked the clearing approaches, I rely on floats and percentage widths for things like this.

Here's something that works in simple cases:

#content { 
  overflow:auto; 
  width: 600px; 
  background: gray; 
} 

#left, #right { 
  width: 40%; 
  margin:5px; 
  padding: 1em; 
  background: white; 
} 

#left  { float:left;  }
#right { float:right; } 

If you put some content in you'll see that it works:

<div id="content">
  <div id="left">
     <div id="object1">some stuff</div>
     <div id="object2">some more stuff</div>
  </div>

  <div id="right">
     <div id="object3">unas cosas</div>
     <div id="object4">mas cosas para ti</div>
  </div>
</div>

You can see it here: http://cssdesk.com/d64uy

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

Open Android Studio then go to gradle.properties file and change the last line to

org.gradle.jvmargs=-Xmx1024m.

And then press try again

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

how to add the missing RANDR extension

I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.

It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR warning and problem at starting Firefox using Xfvb.

After adding +extension RANDR it worked again.

$ vim /etc/init/xvfb.conf

#!upstart
description "Xvfb Server as a daemon"

start on filesystem and started networking
stop on shutdown

respawn

env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid

exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1

How to check if a folder exists

To check if a directory exists with the new IO:

if (Files.isDirectory(Paths.get("directory"))) {
  ...
}

isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.

See: documentation.

How to insert Records in Database using C# language?

You should form the command with the contents of the textboxes:

sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + 
"," + textbox3.Text+ ")";

This, of course, provided that you manage to open the connection correctly.

It would be helpful to know what is happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.

You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code).

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use String.Format:

DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"

Iterating over each line of ls -l output

Set IFS to newline, like this:

IFS='
'
for x in `ls -l $1`; do echo $x; done

Put a sub-shell around it if you don't want to set IFS permanently:

(IFS='
'
for x in `ls -l $1`; do echo $x; done)

Or use while | read instead:

ls -l $1 | while read x; do echo $x; done

One more option, which runs the while/read at the same shell level:

while read x; do echo $x; done << EOF
$(ls -l $1)
EOF

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

I faced a similar issue while copying a sheet to another workbook. I prefer to avoid using 'activesheet' though as it has caused me issues in the past. Hence I wrote a function to perform this inline with my needs. I add it here for those who arrive via google as I did:

The main issue here is that copying a visible sheet to the last index position results in Excel repositioning the sheet to the end of the visible sheets. Hence copying the sheet to the position after the last visible sheet sorts this issue. Even if you are copying hidden sheets.

Function Copy_WS_to_NewWB(WB As Workbook, WS As Worksheet) As Worksheet
    'Creates a copy of the specified worksheet in the specified workbook
    '   Accomodates the fact that there may be hidden sheets in the workbook
    
    Dim WSInd As Integer: WSInd = 1
    Dim CWS As Worksheet
    
    'Determine the index of the last visible worksheet
    For Each CWS In WB.Worksheets
        If CWS.Visible Then If CWS.Index > WSInd Then WSInd = CWS.Index
    Next CWS
    
    WS.Copy after:=WB.Worksheets(WSInd)
    Set Copy_WS_to_NewWB = WB.Worksheets(WSInd + 1)

End Function

To use this function for the original question (ie in the same workbook) could be done with something like...

Set test = Copy_WS_to_NewWB(Workbooks(1), Workbooks(1).Worksheets(1))
test.name = "test sheet name"

EDIT 04/11/2020 from –user3598756 Adding a slight refactoring of the above code

Function CopySheetToWorkBook(targetWb As Workbook, shToBeCopied As Worksheet, copiedSh As Worksheet) As Boolean
    'Creates a copy of the specified worksheet in the specified workbook
    '   Accomodates the fact that there may be hidden sheets in the workbook

    Dim lastVisibleShIndex As Long
    Dim iSh As Long

    On Error GoTo SafeExit
    
    With targetWb
        'Determine the index of the last visible worksheet
        For iSh = .Sheets.Count To 1 Step -1
            If .Sheets(iSh).Visible Then
                lastVisibleShIndex = iSh
                Exit For
            End If
        Next
    
        shToBeCopied.Copy after:=.Sheets(lastVisibleShIndex)
        Set copiedSh = .Sheets(lastVisibleShIndex + 1)
    End With
    
    CopySheetToWorkBook = True
    Exit Function
    
SafeExit:
    
End Function

other than using different (more descriptive?) variable names, the refactoring manily deals with:

  1. turning the Function type into a `Boolean while including returned (copied) worksheet within function parameters list this, to let the calling Sub hande possible errors, like

     Dim WB as Workbook: Set WB = ThisWorkbook ' as an example
     Dim sh as Worksheet: Set sh = ActiveSheet ' as an example
     Dim copiedSh as Worksheet
     If CopySheetToWorkBook(WB, sh, copiedSh) Then
         ' go on with your copiedSh sheet
     Else
         Msgbox "Error while trying to copy '" & sh.Name & "'" & vbcrlf & err.Description
     End If
    
  2. having the For - Next loop stepping from last sheet index backwards and exiting at first visible sheet occurence, since we're after the "last" visible one

Looping through all rows in a table column, Excel-VBA

I came across the same problem but no forum could help me, after some minutes I came out with an idea:

match(ColumnHeader,Table1[#Headers],0)

This will return you the number.

How add class='active' to html menu with php

The solution i'm using is as follows and allows you to set the active class per php page.

Give each of your menu items a unique class, i use .nav-x (nav-about, here).

<li class="nav-item nav-about"> <a class="nav-link" href="about.php">About</a> </li>

At the top of each page (about.php here):

<!-- Navbar Active Class -->
<?php $activeClass = '.nav-about > a'; ?>

Elsewhere (header.php / index.php):

<style>
<?php echo $activeClass; ?> {
    color: #fff !important;
}
</style>

Simply change the .nav-about > a per page, .nav-forum > a, for example.

If you want different styling (colors etc) for each nav item, just attach the inline styling to that page instead of the index / header page.

SQL Format as of Round off removing decimals

use ROUND () (See examples ) function in sql server

select round(11.6,0)

result:

12.0

ex2:

select round(11.4,0)

result:

11.0

if you don't want the decimal part, you could do

select cast(round(11.6,0) as int)

What are NR and FNR and what does "NR==FNR" imply?

Look for keys (first word of line) in file2 that are also in file1.
Step 1: fill array a with the first words of file 1:

awk '{a[$1];}' file1

Step 2: Fill array a and ignore file 2 in the same command. For this check the total number of records until now with the number of the current input file.

awk 'NR==FNR{a[$1]}' file1 file2

Step 3: Ignore actions that might come after } when parsing file 1

awk 'NR==FNR{a[$1];next}' file1 file2 

Step 4: print key of file2 when found in the array a

awk 'NR==FNR{a[$1];next} $1 in a{print $1}' file1 file2

Auto submit form on page load

Add the following to Body tag,

<body onload="document.forms['member_signup'].submit()">

and give name attribute to your Form.

<form method="POST" action="" name="member_signup">

How to pass extra variables in URL with WordPress

This was the only way I could get this to work

add_action('init','add_query_args');
function add_query_args()
{ 
    add_query_arg( 'var1', 'val1' );
}

http://codex.wordpress.org/Function_Reference/add_query_arg

How to set the default value of an attribute on a Laravel model

The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    // auto-sets values on creation
    static::creating(function ($query) {
        $query->is_voicemail = $query->is_voicemail ?? true;
    });
}

Firebase (FCM) how to get token

The team behind Firebase Android SDK change API a little bit. I've implemented "Token to Server" logic like this:

In my instance of FirebaseMessagingService:

public class FirebaseCloudMessagingService extends FirebaseMessagingService {

    ...

    @Override
    public void onNewToken(String token) {
        // sending token to server here
    }

    ...

}

Keep in mind that token is per device, and it can be updated by Firebase regardless of your login logic. So, if you have Login and Logout functionality, you have to consider extra cases:

  1. When a new user logs in, you need to bind token to the new user (send it to the server). Because token might be updated during the session of old user and server doesn't know token of the new user.
  2. When the user logs out, you need to unbind token. Because user should not receive notifications/messages anymore.

Using new API, you can get token like this:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String token = instanceIdResult.getToken();
            // send it to server
        }
    });

Good luck!

What is the max size of localStorage values?

I'm doing the following:

getLocalStorageSizeLimit = function () {

    var maxLength = Math.pow(2,24);
    var preLength = 0;
    var hugeString = "0";
    var testString;
    var keyName = "testingLengthKey";

    //2^24 = 16777216 should be enough to all browsers
    testString = (new Array(Math.pow(2, 24))).join("X");

    while (maxLength !== preLength) {
        try  {
            localStorage.setItem(keyName, testString);

            preLength = testString.length;
            maxLength = Math.ceil(preLength + ((hugeString.length - preLength) / 2));

            testString = hugeString.substr(0, maxLength);
        } catch (e) {
            hugeString = testString;

            maxLength = Math.floor(testString.length - (testString.length - preLength) / 2);
            testString = hugeString.substr(0, maxLength);
        }
    }

    localStorage.removeItem(keyName);

    maxLength = JSON.stringify(this.storageObject).length + maxLength + keyName.length - 2;

    return maxLength;
};

Interop type cannot be embedded

Got the solution

Go to references right click the desired dll you will get option "Embed Interop Types" to "False" or "True".

How to get value of Radio Buttons?

You need to check one if you have two

if(rbMale.Checked)
{

}
else
{

}

You need to check all the checkboxes if more then two

if(rb1.Checked)
{

}
else if(rb2.Checked)
{

}
else if(rb3.Checked)
{

}

Nginx not running with no error message

First, always sudo nginx -t to verify your config files are good.

I ran into the same problem. The reason I had the issue was twofold. First, I had accidentally copied a log file into my site-enabled folder. I deleted the log file and made sure that all the files in sites-enabled were proper nginx site configs. I also noticed two of my virtual hosts were listening for the same domain. So I made sure that each of my virtual hosts had unique domain names.

sudo service nginx restart

Then it worked.

Connecting to remote MySQL server using PHP

  • firewall of the server must be set-up to enable incomming connections on port 3306
  • you must have a user in MySQL who is allowed to connect from % (any host) (see manual for details)

The current problem is the first one, but right after you resolve it you will likely get the second one.

How to trigger an event in input text after I stop typing/writing?

cleaned solution :

$.fn.donetyping = function(callback, delay){
  delay || (delay = 1000);
  var timeoutReference;
  var doneTyping = function(elt){
    if (!timeoutReference) return;
    timeoutReference = null;
    callback(elt);
  };

  this.each(function(){
    var self = $(this);
    self.on('keyup',function(){
      if(timeoutReference) clearTimeout(timeoutReference);
      timeoutReference = setTimeout(function(){
        doneTyping(self);
      }, delay);
    }).on('blur',function(){
      doneTyping(self);
    });
  });

  return this;
};

Get the new record primary key ID from MySQL insert query?

If in python using pymysql, from the cursor you can use cursor.lastrowid

How can I make a Python script standalone executable to run without ANY dependency?

For Python 3.2 scripts, the only choice is cx_Freeze. Build it from sources; otherwise it won't work.

For Python 2.x I suggest PyInstaller as it can package a Python program in a single executable, unlike cx_Freeze which outputs also libraries.

Simultaneously merge multiple data.frames in a list

Reduce makes this fairly easy:

merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)

Here's a fully example using some mock data:

set.seed(1)
list.of.data.frames = list(data.frame(x=1:10, a=1:10), data.frame(x=5:14, b=11:20), data.frame(x=sample(20, 10), y=runif(10)))
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
tail(merged.data.frame)
#    x  a  b         y
#12 12 NA 18        NA
#13 13 NA 19        NA
#14 14 NA 20 0.4976992
#15 15 NA NA 0.7176185
#16 16 NA NA 0.3841037
#17 19 NA NA 0.3800352

And here's an example using these data to replicate my.list:

merged.data.frame = Reduce(function(...) merge(..., by=match.by, all=T), my.list)
merged.data.frame[, 1:12]

#  matchname party st district chamber senate1993 name.x v2.x v3.x v4.x senate1994 name.y
#1   ALGIERE   200 RI      026       S         NA   <NA>   NA   NA   NA         NA   <NA>
#2     ALVES   100 RI      019       S         NA   <NA>   NA   NA   NA         NA   <NA>
#3    BADEAU   100 RI      032       S         NA   <NA>   NA   NA   NA         NA   <NA>

Note: It looks like this is arguably a bug in merge. The problem is there is no check that adding the suffixes (to handle overlapping non-matching names) actually makes them unique. At a certain point it uses [.data.frame which does make.unique the names, causing the rbind to fail.

# first merge will end up with 'name.x' & 'name.y'
merge(my.list[[1]], my.list[[2]], by=match.by, all=T)
# [1] matchname    party        st           district     chamber      senate1993   name.x      
# [8] votes.year.x senate1994   name.y       votes.year.y
#<0 rows> (or 0-length row.names)
# as there is no clash, we retain 'name.x' & 'name.y' and get 'name' again
merge(merge(my.list[[1]], my.list[[2]], by=match.by, all=T), my.list[[3]], by=match.by, all=T)
# [1] matchname    party        st           district     chamber      senate1993   name.x      
# [8] votes.year.x senate1994   name.y       votes.year.y senate1995   name         votes.year  
#<0 rows> (or 0-length row.names)
# the next merge will fail as 'name' will get renamed to a pre-existing field.

Easiest way to fix is to not leave the field renaming for duplicates fields (of which there are many here) up to merge. Eg:

my.list2 = Map(function(x, i) setNames(x, ifelse(names(x) %in% match.by,
      names(x), sprintf('%s.%d', names(x), i))), my.list, seq_along(my.list))

The merge/Reduce will then work fine.

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

How to install plugins to Sublime Text 2 editor?

You should have a Data/Packages folder in your Sublime Text 2 install directory. All you need to do is download the plugin and put the plugin folder in the Packages folder.

Or, an easier way would be to install the Package Control Plugin by wbond.

Just go here: https://sublime.wbond.net/installation

and follow the install instructions.

Once you are done you can use the Ctrl + Shift + P shortcut in Sublime, type in install and press enter, then search for emmet.

EDIT: You can now also press Ctrl + Shift + P right away and use the command 'Install Package Control' instead of following the install instructions. (Tested on Build 3126)

How to set cache: false in jQuery.get call

To me, the correct way of doing it would be the ones listed. Either ajax or ajaxSetup. If you really want to use get and not use ajaxSetup then you could create your own parameter and give it the value of the the current date/time.

I would however question your motives in not using one of the other methods.

Running MSBuild fails to read SDKToolsPath

I had this same issue and had installed Windows SDK 7.0 and Windows SDK 7.1 which neither fixed the issue. The cause of the problem for me was that the offending class library was built with Target Framework of .NET Framework 2.0.

I changed it to .NET Framework 4.0 and worked locally and when checked in the Build server built it successfully.

What are the default access modifiers in C#?

Short answer: minimum possible access (cf Jon Skeet's answer).

Long answer:

Non-nested types, enumeration and delegate accessibilities (may only have internal or public accessibility)

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | public, internal

interface            | internal  | public, internal

class                | internal  | public, internal

struct               | internal  | public, internal

delegate             | internal  | public, internal

Nested type and member accessiblities

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | All¹

interface            | public    | All¹

class                | private   | All¹

struct               | private   | public, internal, private²

delegate             | private   | All¹

constructor          | private   | All¹

enum member          | public    | none (always implicitly public)

interface member     | public    | none (always implicitly public)
     
method               | private   | All¹

field                | private   | All¹

user-defined operator| none      | public (must be declared public)

¹ All === public, protected, internal, private, protected internal

² structs cannot inherit from structs or classes (although they can, interfaces), hence protected is not a valid modifier

The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type. However, the accessibility domain of a nested type cannot exceed that of the containing type.

Note: CIL also has the provision for protected and internal (as opposed to the existing protected "or" internal), but to my knowledge this is not currently available for use in C#.


See:

http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx
http://msdn.microsoft.com/en-us/library/ms173121.aspx
http://msdn.microsoft.com/en-us/library/cx03xt0t.aspx
(Man I love Microsoft URLs...)

How do I read a string entered by the user in C?

You can use scanf function to read string

scanf("%[^\n]",name);

i don't know about other better options to receive string,

How do I use the Simple HTTP client in Android?

public static void connect(String url)
{

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
        }


    } catch (Exception e) {}
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

Add padding on view programmatically

To answer your second question:

view.setPadding(0,padding,0,0);

like SpK and Jave suggested, will set the padding in pixels. You can set it in dp by calculating the dp value as follows:

int paddingDp = 25;
float density = context.getResources().getDisplayMetrics().density
int paddingPixel = (int)(paddingDp * density);
view.setPadding(0,paddingPixel,0,0);

Hope that helps!

Exporting the values in List to excel

I know, I am late to this party, however I think it could be helpful for others.

Already posted answers are for csv and other one is by Interop dll where you need to install excel over the server, every approach has its own pros and cons. Here is an option which will give you

  1. Perfect excel output [not csv]
  2. With perfect excel and your data type match
  3. Without excel installation
  4. Pass list and get Excel output :)

you can achieve this by using NPOI DLL, available for both .net as well as for .net core

Steps :

  1. Import NPOI DLL
  2. Add Section 1 and 2 code provided below
  3. Good to go

Section 1

This code performs below task :

  1. Creating New Excel object - _workbook = new XSSFWorkbook();
  2. Creating New Excel Sheet object - _sheet =_workbook.CreateSheet(_sheetName);
  3. Invokes WriteData() - explained later Finally, creating and
  4. returning MemoryStream object

=============================================================================

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace GenericExcelExport.ExcelExport
{
    public interface IAbstractDataExport
    {
        HttpResponseMessage Export(List exportData, string fileName, string sheetName);
    }

    public abstract class AbstractDataExport : IAbstractDataExport
    {
        protected string _sheetName;
        protected string _fileName;
        protected List _headers;
        protected List _type;
        protected IWorkbook _workbook;
        protected ISheet _sheet;
        private const string DefaultSheetName = "Sheet1";

        public HttpResponseMessage Export
              (List exportData, string fileName, string sheetName = DefaultSheetName)
        {
            _fileName = fileName;
            _sheetName = sheetName;

            _workbook = new XSSFWorkbook(); //Creating New Excel object
            _sheet = _workbook.CreateSheet(_sheetName); //Creating New Excel Sheet object

            var headerStyle = _workbook.CreateCellStyle(); //Formatting
            var headerFont = _workbook.CreateFont();
            headerFont.IsBold = true;
            headerStyle.SetFont(headerFont);

            WriteData(exportData); //your list object to NPOI excel conversion happens here

            //Header
            var header = _sheet.CreateRow(0);
            for (var i = 0; i < _headers.Count; i++)
            {
                var cell = header.CreateCell(i);
                cell.SetCellValue(_headers[i]);
                cell.CellStyle = headerStyle;
            }

            for (var i = 0; i < _headers.Count; i++)
            {
                _sheet.AutoSizeColumn(i);
            }

            using (var memoryStream = new MemoryStream()) //creating memoryStream
            {
                _workbook.Write(memoryStream);
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(memoryStream.ToArray())
                };

                response.Content.Headers.ContentType = new MediaTypeHeaderValue
                       ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.Content.Headers.ContentDisposition = 
                       new ContentDispositionHeaderValue("attachment")
                {
                    FileName = $"{_fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
                };

                return response;
            }
        }

        //Generic Definition to handle all types of List
        public abstract void WriteData(List exportData);
    }
}

=============================================================================

Section 2

In section 2, we will be performing below steps :

  1. Converts List to DataTable Reflection to read property name, your
  2. Column header will be coming from here
  3. Loop through DataTable to Create excel Rows

=============================================================================

using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text.RegularExpressions;

namespace GenericExcelExport.ExcelExport
{
    public class AbstractDataExportBridge : AbstractDataExport
    {
        public AbstractDataExportBridge()
        {
            _headers = new List<string>();
            _type = new List<string>();
        }

        public override void WriteData<T>(List<T> exportData)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();

            foreach (PropertyDescriptor prop in properties)
            {
                var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                _type.Add(type.Name);
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? 
                                  prop.PropertyType);
                string name = Regex.Replace(prop.Name, "([A-Z])", " $1").Trim(); //space separated 
                                                                           //name by caps for header
                _headers.Add(name);
            }

            foreach (T item in exportData)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }

            IRow sheetRow = null;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                sheetRow = _sheet.CreateRow(i + 1);
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    ICell Row1 = sheetRow.CreateCell(j);

                    string type = _type[j].ToLower();
                    var currentCellValue = table.Rows[i][j];

                    if (currentCellValue != null && 
                        !string.IsNullOrEmpty(Convert.ToString(currentCellValue)))
                    {
                        if (type == "string")
                        {
                            Row1.SetCellValue(Convert.ToString(currentCellValue));
                        }
                        else if (type == "int32")
                        {
                            Row1.SetCellValue(Convert.ToInt32(currentCellValue));
                        }
                        else if (type == "double")
                        {
                            Row1.SetCellValue(Convert.ToDouble(currentCellValue));
                        }
                    }
                    else
                    {
                        Row1.SetCellValue(string.Empty);
                    }
                }
            }
        }
    }
}

=============================================================================

Now you just need to call WriteData() function by passing your list, and it will provide you your excel.

I have tested it in WEB API and WEB API Core, works like a charm.

What is Type-safe?

Type safety is not just a compile time constraint, but a run time constraint. I feel even after all this time, we can add further clarity to this.

There are 2 main issues related to type safety. Memory** and data type (with its corresponding operations).

Memory**

A char typically requires 1 byte per character, or 8 bits (depends on language, Java and C# store unicode chars which require 16 bits). An int requires 4 bytes, or 32 bits (usually).

Visually:

char: |-|-|-|-|-|-|-|-|

int : |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|

A type safe language does not allow an int to be inserted into a char at run-time (this should throw some kind of class cast or out of memory exception). However, in a type unsafe language, you would overwrite existing data in 3 more adjacent bytes of memory.

int >> char:

|-|-|-|-|-|-|-|-| |?|?|?|?|?|?|?|?| |?|?|?|?|?|?|?|?| |?|?|?|?|?|?|?|?|

In the above case, the 3 bytes to the right are overwritten, so any pointers to that memory (say 3 consecutive chars) which expect to get a predictable char value will now have garbage. This causes undefined behavior in your program (or worse, possibly in other programs depending on how the OS allocates memory - very unlikely these days).

** While this first issue is not technically about data type, type safe languages address it inherently and it visually describes the issue to those unaware of how memory allocation "looks".

Data Type

The more subtle and direct type issue is where two data types use the same memory allocation. Take a int vs an unsigned int. Both are 32 bits. (Just as easily could be a char[4] and an int, but the more common issue is uint vs. int).

|-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|

|-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|

A type unsafe language allows the programmer to reference a properly allocated span of 32 bits, but when the value of a unsigned int is read into the space of an int (or vice versa), we again have undefined behavior. Imagine the problems this could cause in a banking program:

"Dude! I overdrafted $30 and now I have $65,506 left!!"

...'course, banking programs use much larger data types. ;) LOL!

As others have already pointed out, the next issue is computational operations on types. That has already been sufficiently covered.

Speed vs Safety

Most programmers today never need to worry about such things unless they are using something like C or C++. Both of these languages allow programmers to easily violate type safety at run time (direct memory referencing) despite the compilers' best efforts to minimize the risk. HOWEVER, this is not all bad.

One reason these languages are so computationally fast is they are not burdened by verifying type compatibility during run time operations like, for example, Java. They assume the developer is a good rational being who won't add a string and an int together and for that, the developer is rewarded with speed/efficiency.

Correct way to initialize empty slice

They are equivalent. See this code:

mySlice1 := make([]int, 0)
mySlice2 := []int{}
fmt.Println("mySlice1", cap(mySlice1))
fmt.Println("mySlice2", cap(mySlice2))

Output:

mySlice1 0
mySlice2 0

Both slices have 0 capacity which implies both slices have 0 length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.

See similar questions:

What is the point of having nil slice and empty slice in golang?

nil slices vs non-nil slices vs empty slices in Go language

Copy file(s) from one project to another using post build event...VS2010

xcopy "$(ProjectDir)Views\Home\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\Home"

and if you want to copy entire folders:

xcopy /E /Y "$(ProjectDir)Views" "$(SolutionDir)MEFMVCPOC\Views"

Update: here's the working version

xcopy "$(ProjectDir)Views\ModuleAHome\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\ModuleAHome\" /Y /I

Here are some commonly used switches with xcopy:

  • /I - treat as a directory if copying multiple files.
  • /Q - Do not display the files being copied.
  • /S - Copy subdirectories unless empty.
  • /E - Copy empty subdirectories.
  • /Y - Do not prompt for overwrite of existing files.
  • /R - Overwrite read-only files.

Importing project into Netbeans

From Netbeans 8.1 - there is an "Import from ZIP" option.

Go to Main Menu -> File -> Import Project -> from ZIP.

Browse your .ZIP file's location via Browse button.

If you have Java project depending on external Libraries, Netbeans will highlight & ask for "Resolving problems" in project, click on resolve, provide location in your file system containing required library files .e.g JARs etc & you will be good to go.

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.

There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.

Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:

  • std::condition_variable::wait(std::unique_lock&) just calls pthread_cond_wait() on the underlying pthread condition variable with respect to the mutex held by unique_lock (and so could equally do the same for lock_guard, but doesn't because the standard doesn't provide for that)
  • std::condition_variable_any can work with any lockable object, including one which is not a mutex lock at all (it could therefore even work with an inter-process semaphore)

How to do one-liner if else statement?

Like user2680100 said, in Golang you can have the structure:

if <statement>; <evaluation> {
    [statements ...]
} else {
    [statements ...]
}

This is useful to shortcut some expressions that need error checking, or another kind of boolean checking, like:


var number int64
if v := os.Getenv("NUMBER"); v != "" {
   if number, err = strconv.ParseInt(v, 10, 64); err != nil {
       os.Exit(42)
   }
} else {
    os.Exit(1)
}

With this you can achieve something like (in C):

Sprite *buffer = get_sprite("foo.png");
Sprite *foo_sprite = (buffer != 0) ? buffer : donut_sprite

But is evident that this sugar in Golang have to be used with moderation, for me, personally, I like to use this sugar with max of one level of nesting, like:


var number int64
if v := os.Getenv("NUMBER"); v != "" {
    number, err = strconv.ParseInt(v, 10, 64)
    if err != nil {
        os.Exit(42)
    }
} else {
    os.Exit(1)
}

You can also implement ternary expressions with functions like func Ternary(b bool, a interface{}, b interface{}) { ... } but i don't like this approach, looks like a creation of a exception case in syntax, and creation of this "features", in my personal opinion, reduce the focus on that matters, that is algorithm and readability, but, the most important thing that makes me don't go for this way is that fact that this can bring a kind of overhead, and bring more cycles to in your program execution.

How to tell if tensorflow is using gpu acceleration from inside python shell?

This is the line I am using to list devices available to tf.session directly from bash:

python -c "import os; os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'; import tensorflow as tf; sess = tf.Session(); [print(x) for x in sess.list_devices()]; print(tf.__version__);"

It will print available devices and tensorflow version, for example:

_DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456, 10588614393916958794)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 12320120782636586575)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 13378821206986992411)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:GPU:0, GPU, 32039954023, 12481654498215526877)
1.14.0

Jenkins Git Plugin: How to build specific tag?

If you are using Jenkins pipelines and want to checkout a specific tag (eg: a TAG parameter of your build), here is what you can do:

stage('Checkout') {
  steps {
    checkout scm: [$class: 'GitSCM', userRemoteConfigs: [[url: 'YOUR_GIT_REPO_URL.git', credentialsId: 'YOUR_GIT_CREDENTIALS_ID' ]], branches: [[name: 'refs/tags/${TAG}']]], poll: false
  }
}

IntelliJ: Working on multiple projects

Prequisite

Having all the related projects in the same root directory.

Steps

1) First you create a new Empty project

New empty project


2) Then you select the root directory of all you projects.

This will create a empty project, with a .idea directory that will simply remember the module organisation we are about to do in the next step

Select root directory


3) Then, in the next window, you import the different projects as modules

Import projects as modules


4) In the next window, to import each project, simply double click on the build.gradle, or pom.xml

The project will be imported as a new module. Select build file


5) Done, you now have all your projects as modules, opened on the same IntelliJ project

Result

Visual Studio: How to break on handled exceptions?

With a solution open, go to the Debug - Exceptions (Ctrl+D,E) menu option. From there you can choose to break on Thrown or User-unhandled exceptions.

EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles?

Convert MFC CString to integer

CString s="143";
int x=atoi(s);

or

CString s=_T("143");
int x=_toti(s);

atoi will work, if you want to convert CString to int.

PHP create key => value pairs within a foreach

Something like this?

foreach ($Offer as $key => $value) { 
  $offerArray[$key] = $value[4];
}

Meaning of @classmethod and @staticmethod for beginner?

I'm a beginner on this site, I have read all above answers, and got the information what I want. However, I don't have the right to upvote. So I want to get my start on StackOverflow with the answer as I understand it.

  • @staticmethod doesn't need self or cls as the first parameter of the method
  • @staticmethod and @classmethod wrapped function could be called by instance or class variable
  • @staticmethod decorated function impact some kind 'immutable property' that subclass inheritance can't overwrite its base class function which is wrapped by a @staticmethod decorator.
  • @classmethod need cls (Class name, you could change the variable name if you want, but it's not advised) as the first parameter of function
  • @classmethod always used by subclass manner, subclass inheritance may change the effect of base class function, i.e. @classmethod wrapped base class function could be overwritten by different subclasses.

'Must Override a Superclass Method' Errors after importing a project into Eclipse

If nothing of the above helps, make sure you have a proper "Execution environment" selected, and not an "Alternate JRE".

To be found under:

Project -> Build Path -> Libraries

Select the JRE System Library and click Edit....

If "Alternate JRE ..." is selected, change it to a fitting "Execution Environment" like JavaSE-1.8 (jre1.8.0_60). No idea why, but this will solve it.