Programs & Examples On #Android image

This tag is for questions related to images on Android

How do I get the resource id of an image if I know its name?

You can use this function to get a Resource ID:

public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
    try {
        return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        throw new RuntimeException("Error getting Resource ID.", e)
    } 
}


So if you want to get a Drawable Resource ID, you can call the method like this:

getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName());

(or from a fragment):

getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName());


For a String Resource ID you can call it like this:

getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName());

etc...


Careful: It throws a RuntimeException if it fails to find the Resource ID. Be sure to recover properly in production.

Read this

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

"Bitmap too large to be uploaded into a texture"

I tried all the solutions above, one-after-the-other, for quite many hours, and none seemed to work! Finally, I decided to look around for an official example concerning capturing images with Android's camera, and displaying them. The official example (here), finally gave me the only method that worked. Below I present the solution I found in that example app:

public void setThumbnailImageAndSave(final ImageView imgView, File imgFile) {

            /* There isn't enough memory to open up more than a couple camera photos */
    /* So pre-scale the target bitmap into which the file is decoded */

    /* Get the size of the ImageView */
    int targetW = imgView.getWidth();
    int targetH = imgView.getHeight();

    /* Get the size of the image */
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    /* Figure out which way needs to be reduced less */
    int scaleFactor = 1;
    if ((targetW > 0) || (targetH > 0)) {
        scaleFactor = Math.min(photoW/targetW, photoH/targetH);
    }

    /* Set bitmap options to scale the image decode target */
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    /* Decode the JPEG file into a Bitmap */
    Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions);

    /* Associate the Bitmap to the ImageView */
    imgView.setImageBitmap(bitmap);
    imgView.setVisibility(View.VISIBLE);
}

How to make an ImageView with rounded corners?

Answer for the question that is redirected here: "How to create a circular ImageView in Android?"

public static Bitmap getRoundBitmap(Bitmap bitmap) {

    int min = Math.min(bitmap.getWidth(), bitmap.getHeight());

    Bitmap bitmapRounded = Bitmap.createBitmap(min, min, bitmap.getConfig());

    Canvas canvas = new Canvas(bitmapRounded);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    canvas.drawRoundRect((new RectF(0.0f, 0.0f, min, min)), min/2, min/2, paint);

    return bitmapRounded;
}

Open an image using URI in Android's default gallery image viewer

Based on Vikas answer but with a slight modification: The Uri is received by parameter:

private void showPhoto(Uri photoUri){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(photoUri, "image/*");
    startActivity(intent);
}

Android Text over image

You can use a TextView and change its background to the image you want to use

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);

or

http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html

How to display a list of images in a ListView in Android?

I'd start with something like this (and if there is something wrong with my code, I'd of course appreciate any comment):

public class ItemsList extends ListActivity {

private ItemsAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.items_list);

    this.adapter = new ItemsAdapter(this, R.layout.items_list_item, ItemManager.getLoadedItems());
    setListAdapter(this.adapter);
}

private class ItemsAdapter extends ArrayAdapter<Item> {

    private Item[] items;

    public ItemsAdapter(Context context, int textViewResourceId, Item[] items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.items_list_item, null);
        }

        Item it = items[position];
        if (it != null) {
            ImageView iv = (ImageView) v.findViewById(R.id.list_item_image);
            if (iv != null) {
                iv.setImageDrawable(it.getImage());
            }
        }

        return v;
    }
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    this.adapter.getItem(position).click(this.getApplicationContext());
}
}

E.g. extending ArrayAdapter with own type of Items (holding information about your pictures) and overriden getView() method, that prepares view for items within list. There is also method add() on ArrayAdapter to add items to the end of the list.

R.layout.items_list is simple layout with ListView

R.layout.items_list_item is layout representing one item in list

Saving and Reading Bitmaps/Images from Internal memory in Android

For Kotlin users, I created a ImageStorageManager class which will handle save, get and delete actions for images easily:

class ImageStorageManager {
    companion object {
        fun saveToInternalStorage(context: Context, bitmapImage: Bitmap, imageFileName: String): String {
            context.openFileOutput(imageFileName, Context.MODE_PRIVATE).use { fos ->
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 25, fos)
            }
            return context.filesDir.absolutePath
        }

        fun getImageFromInternalStorage(context: Context, imageFileName: String): Bitmap? {
            val directory = context.filesDir
            val file = File(directory, imageFileName)
            return BitmapFactory.decodeStream(FileInputStream(file))
        }

        fun deleteImageFromInternalStorage(context: Context, imageFileName: String): Boolean {
            val dir = context.filesDir
            val file = File(dir, imageFileName)
            return file.delete()
        }
    }
}

Read more here

How to get Bitmap from an Uri?

  InputStream imageStream = null;
    try {
        imageStream = getContext().getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);

How to clear an ImageView in Android?

If none of these solutions are clearing an image you've already set (especially setImageResource(0) or setImageResources(android.R.color.transparent), check to make sure the current image isn't set as background using setBackgroundDrawable(...) or something similar.

Your code will just set the image resource in the foreground to something transparent in front of that background image you've set and will still show.

How to pick an image from gallery (SD Card) for my app?

Here is a tested code for image and video.It will work for all APIs less than 19 and greater than 19 as well.

Image:

if (Build.VERSION.SDK_INT <= 19) {
                        Intent i = new Intent();
                        i.setType("image/*");
                        i.setAction(Intent.ACTION_GET_CONTENT);
                        i.addCategory(Intent.CATEGORY_OPENABLE);
                        startActivityForResult(i, 10);
                    } else if (Build.VERSION.SDK_INT > 19) {
                        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 10);
                    }

Video:

if (Build.VERSION.SDK_INT <= 19) {
                        Intent i = new Intent();
                        i.setType("video/*");
                        i.setAction(Intent.ACTION_GET_CONTENT);
                        i.addCategory(Intent.CATEGORY_OPENABLE);
                        startActivityForResult(i, 20);
                    } else if (Build.VERSION.SDK_INT > 19) {
                        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 20);
                    }    

.

     @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {               
            if (requestCode == 10) {
                Uri selectedImageUri = data.getData();
                String selectedImagePath = getRealPathFromURI(selectedImageUri);
            } else if (requestCode == 20) {
                Uri selectedVideoUri = data.getData();
                String selectedVideoPath = getRealPathFromURI(selectedVideoUri);
            }
        }
     }

     public String getRealPathFromURI(Uri uri) {
            if (uri == null) {
                return null;
            }
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }
            return uri.getPath();
        }

How to get the current working directory in Java?

Using Windows user.dir returns the directory as expected, but NOT when you start your application with elevated rights (run as admin), in that case you get C:\WINDOWS\system32

How to give a time delay of less than one second in excel vba?

Everyone tries Application.Wait, but that's not really reliable. If you ask it to wait for less than a second, you'll get anything between 0 and 1, but closer to 10 seconds. Here's a demonstration using a wait of 0.5 seconds:

Sub TestWait()
  Dim i As Long
  For i = 1 To 5
    Dim t As Double
    t = Timer
    Application.Wait Now + TimeValue("0:00:00") / 2
    Debug.Print Timer - t
  Next
End Sub

Here's the output, an average of 0.0015625 seconds:

0
0
0
0.0078125
0

Admittedly, Timer may not be the ideal way to measure these events, but you get the idea.

The Timer approach is better:

Sub TestTimer()
  Dim i As Long
  For i = 1 To 5
    Dim t As Double
    t = Timer
    Do Until Timer - t >= 0.5
      DoEvents
    Loop
    Debug.Print Timer - t
  Next
End Sub

And the results average is very close to 0.5 seconds:

0.5
0.5
0.5
0.5
0.5

Java - how do I write a file to a specified directory

The best practice is using File.separator in the paths.

How to Disable landscape mode in Android?

If you are using Xamarin C# some of these solutions will not work. Here is the solution I found to work.

[Activity(MainLauncher = true, Icon = "@drawable/icon", ScreenOrientation = ScreenOrientation.Portrait)]

Above the class works well, similar to the other solutions, also not globally applicable and needs to be placed in each activity header.

How do I collapse a table row in Bootstrap?


problem is that the collapse item (div) is nested in the table elements. The div is hidden, the tr and td of the table are still visible and some css-styles are applied to them (border and padding).
Why are you using tables? Is there a reason for? When you dont´t have to use them, dont´use them :-)

php random x digit number

you can generate any x-digit random number with mt_rand() function. mt_rand() much faster with rand() function syntax : mt_rand() or mt_rand($min , $max).

read more

example : <?php echo mt_rand(); ?>

In Visual Studio C++, what are the memory allocation representations?

Regarding 0xCC and 0xCD in particular, these are relics from the Intel 8088/8086 processor instruction set back in the 1980s. 0xCC is a special case of the software interrupt opcode INT 0xCD. The special single-byte version 0xCC allows a program to generate interrupt 3.

Although software interrupt numbers are, in principle, arbitrary, INT 3 was traditionally used for the debugger break or breakpoint function, a convention which remains to this day. Whenever a debugger is launched, it installs an interrupt handler for INT 3 such that when that opcode is executed the debugger will be triggered. Typically it will pause the currently running programming and show an interactive prompt.

Normally, the x86 INT opcode is two bytes: 0xCD followed by the desired interrupt number from 0-255. Now although you could issue 0xCD 0x03 for INT 3, Intel decided to add a special version--0xCC with no additional byte--because an opcode must be only one byte in order to function as a reliable 'fill byte' for unused memory.

The point here is to allow for graceful recovery if the processor mistakenly jumps into memory that does not contain any intended instructions. Multi-byte instructions aren't suited this purpose since an erroneous jump could land at any possible byte offset where it would have to continue with a properly formed instruction stream.

Obviously, one-byte opcodes work trivially for this, but there can also be quirky exceptions: for example, considering the fill sequence 0xCDCDCDCD (also mentioned on this page), we can see that it's fairly reliable since no matter where the instruction pointer lands (except perhaps the last filled byte), the CPU can resume executing a valid two-byte x86 instruction CD CD, in this case for generating software interrupt 205 (0xCD).

Weirder still, whereas CD CC CD CC is 100% interpretable--giving either INT 3 or INT 204--the sequence CC CD CC CD is less reliable, only 75% as shown, but generally 99.99% when repeated as an int-sized memory filler.

page from contemporaneous 8088/8086 instruction set manual showing INT instruction
Macro Assembler Reference, 1987

GitLab remote: HTTP Basic: Access denied and fatal Authentication

For Mac user:

  1. Go to keychain and delete gitlab accounts
  2. Go to your project path in terminal and simply type git pull
  3. Then you will be asked for username and password for gitlab
  4. Enter your username which you will find out in gitlab account in profile section.
  5. Then after that enter you updated password here.
  6. Here we go, again try to push your code, it may help you guys.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

Like @Travis and @Mari, I wanted to autoselect when the user clicked in, which means preventing the default behaviour of a mouseup event, but not prevent the user from clicking around. The solution I came up with, which works in IE11, Chrome 45, Opera 32 and Firefox 29 (these are the browsers I currently have installed), is based on the sequence of events involved in a mouse click.

When you click on a text input that does not have focus, you get these events (among others):

  • mousedown: In response to your click. Default handling raises focus if necessary and sets selection start.
  • focus: As part of the default handling of mousedown.
  • mouseup: The completion of your click, whose default handling will set the selection end.

When you click on a text input that already has focus, the focus event is skipped. As @Travis and @Mari both astutely noticed, the default handling of mouseup needs to be prevented only if the focus event occurs. However, as there is no "focus didn't happen" event, we need to infer this, which we can do within the mousedown handler.

@Mari's solution requires that jQuery be imported, which I want to avoid. @Travis's solution does this by inspecting document.activeElement. I don't know why exactly his solution doesn't work across browsers, but there is another way to track whether the text input has focus: simply follow its focus and blur events.

Here is the code that works for me:

    var blockMouseUp = false;
    var customerInputFocused = false;

    txtCustomer.onfocus =
      function ()
      {
        try
        {
          txtCustomer.selectionStart = 0;
          txtCustomer.selectionEnd = txtCustomer.value.length;
        }
        catch (error)
        {
          txtCustomer.select();
        }

        customerInputFocused = true;
      };

    txtCustomer.onblur =
      function ()
      {
        customerInputFocused = false;
      };

    txtCustomer.onmousedown =
      function ()
      {
        blockMouseUp = !customerInputFocused;
      };

    txtCustomer.onmouseup =
      function ()
      {
        if (blockMouseUp)
          return false;
      };

I hope this is of help to someone. :-)

How to output in CLI during execution of PHP Unit tests?

You should really think about your intentions: If you need the information now when debugging to fix the test, you will need it next week again when the tests break.

This means that you will need the information always when the test fails - and adding a var_dump to find the cause is just too much work. Rather put the data into your assertions.

If your code is too complex for that, split it up until you reach a level where one assertion (with a custom message) tells you enough to know where it broke, why and how to fix the code.

Add newly created specific folder to .gitignore in Git

From "git help ignore" we learn:

If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

Therefore what you need is

public_html/stats/

event Action<> vs event EventHandler<>

The main difference will be that if you use Action<> your event will not follow the design pattern of virtually any other event in the system, which I would consider a drawback.

One upside with the dominating design pattern (apart from the power of sameness) is that you can extend the EventArgs object with new properties without altering the signature of the event. This would still be possible if you used Action<SomeClassWithProperties>, but I don't really see the point with not using the regular approach in that case.

How to search file text for a pattern and replace it with a given value

Actually, Ruby does have an in-place editing feature. Like Perl, you can say

ruby -pi.bak -e "gsub(/oldtext/, 'newtext')" *.txt

This will apply the code in double-quotes to all files in the current directory whose names end with ".txt". Backup copies of edited files will be created with a ".bak" extension ("foobar.txt.bak" I think).

NOTE: this does not appear to work for multiline searches. For those, you have to do it the other less pretty way, with a wrapper script around the regex.

OpenCV - DLL missing, but it's not?

As to @Marc's answer, I don't think VC uses the path from the OS. Did you add the path to VC's library paths. I usually add the DLLs to the project and copy if newer on the build and that works very well for me.

How do I initialize a TypeScript Object with a JSON-Object?

Maybe not actual, but simple solution:

interface Bar{
x:number;
y?:string; 
}

var baz:Bar = JSON.parse(jsonString);
alert(baz.y);

work for difficult dependencies too!!!

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

Find the number of columns in a table

It's working (mysql) :

SELECT TABLE_NAME , count(COLUMN_NAME)
FROM information_schema.columns
GROUP BY TABLE_NAME 

Initializing array of structures

There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.

Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data is declared as

typedef struct my_data {
  int a;
  const char *name;
  double x;
} my_data;

then your

my_data data[]={
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};

is simply a more compact form of

my_data data[4]={
    { 0, "Peter", 0 },
    { 0, "James", 0 },
    { 0, "John", 0 },
    { 0, "Mike", 0 }
};

I hope you know what the latter does.

All possible array initialization syntaxes

For the class below:

public class Page
{

    private string data;

    public Page()
    {
    }

    public Page(string data)
    {
        this.Data = data;
    }

    public string Data
    {
        get
        {
            return this.data;
        }
        set
        {
            this.data = value;
        }
    }
}

you can initialize the array of above object as below.

Pages = new Page[] { new Page("a string") };

Hope this helps.

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

I had to do this in VB and prefer to split it out to a method that I placed in a Module. You can add the Fill column as another ByRef parameter if desired.

''' <summary>
''' Makes all columns in a DataGridView autosize based on displayed cells,
''' while leaving the column widths user-adjustable.
''' </summary>
''' <param name="dgv">A DataGridView to adjust</param>
Friend Sub MakeAdjustableAutoSizedGridCols(ByRef dgv As DataGridView)
    Dim width As Integer

    For Each col As DataGridViewColumn In dgv.Columns
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        width = col.Width
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None
        col.Width = width
    Next
    dgv.AllowUserToResizeColumns = True
End Sub

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

Mapping list in Yaml to list of objects in Spring Boot

for me the fix was to add the injected class as inner class in the one annotated with @ConfigurationProperites, because I think you need @Component to inject properties.

Execute script after specific delay using JavaScript

The simplest solution to call your function with delay is:

function executeWithDelay(anotherFunction) {
    setTimeout(anotherFunction, delayInMilliseconds);
}

Prevent overwriting a file using cmd if exist

I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...

CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"

two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult. also...

start \\filer\repo\lab\"software"\"myapp"\setup.exe

the start code here, can be set up like that, but the correct syntax is

start "\\filter\repo\lab\software\myapp\" setup.exe

This will run: setup.exe, located in: \filter\repo\lab...etc.\

Best Practices: working with long, multiline strings in PHP?

Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.

If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:

$text = "Hello, {$vars->name},\r\n\r\n"
    . "The second line starts two lines below.\r\n"
    . ".. Third line... etc";

This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.

How do I find the parent directory in C#?

string parent = System.IO.Directory.GetParent(str_directory).FullName;

See BOL

What is a good way to handle exceptions when trying to read a file in python?

Here is a read/write example. The with statements insure the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm

import sys

fIn = 'symbolsIn.csv'
fOut = 'symbolsOut.csv'

try:
   with open(fIn, 'r') as f:
      file_content = f.read()
      print "read file " + fIn
   if not file_content:
      print "no data in file " + fIn
      file_content = "name,phone,address\n"
   with open(fOut, 'w') as dest:
      dest.write(file_content)
      print "wrote file " + fOut
except IOError as e:
   print "I/O error({0}): {1}".format(e.errno, e.strerror)
except: #handle other exceptions such as attribute errors
   print "Unexpected error:", sys.exc_info()[0]
print "done"

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Normally when an optimization algorithm does not converge, it is usually because the problem is not well-conditioned, perhaps due to a poor scaling of the decision variables. There are a few things you can try.

  1. Normalize your training data so that the problem hopefully becomes more well conditioned, which in turn can speed up convergence. One possibility is to scale your data to 0 mean, unit standard deviation using Scikit-Learn's StandardScaler for an example. Note that you have to apply the StandardScaler fitted on the training data to the test data.
  2. Related to 1), make sure the other arguments such as regularization weight, C, is set appropriately.
  3. Set max_iter to a larger value. The default is 1000.
  4. Set dual = True if number of features > number of examples and vice versa. This solves the SVM optimization problem using the dual formulation. Thanks @Nino van Hooff for pointing this out, and @JamesKo for spotting my mistake.
  5. Use a different solver, for e.g., the L-BFGS solver if you are using Logistic Regression. See @5ervant's answer.

Note: One should not ignore this warning.

This warning came about because

  1. Solving the linear SVM is just solving a quadratic optimization problem. The solver is typically an iterative algorithm that keeps a running estimate of the solution (i.e., the weight and bias for the SVM). It stops running when the solution corresponds to an objective value that is optimal for this convex optimization problem, or when it hits the maximum number of iterations set.

  2. If the algorithm does not converge, then the current estimate of the SVM's parameters are not guaranteed to be any good, hence the predictions can also be complete garbage.

Edit

In addition, consider the comment by @Nino van Hooff and @5ervant to use the dual formulation of the SVM. This is especially important if the number of features you have, D, is more than the number of training examples N. This is what the dual formulation of the SVM is particular designed for and helps with the conditioning of the optimization problem. Credit to @5ervant for noticing and pointing this out.

Furthermore, @5ervant also pointed out the possibility of changing the solver, in particular the use of the L-BFGS solver. Credit to him (i.e., upvote his answer, not mine).

I would like to provide a quick rough explanation for those who are interested (I am :)) why this matters in this case. Second-order methods, and in particular approximate second-order method like the L-BFGS solver, will help with ill-conditioned problems because it is approximating the Hessian at each iteration and using it to scale the gradient direction. This allows it to get better convergence rate but possibly at a higher compute cost per iteration. That is, it takes fewer iterations to finish but each iteration will be slower than a typical first-order method like gradient-descent or its variants.

For e.g., a typical first-order method might update the solution at each iteration like

x(k + 1) = x(k) - alpha(k) * gradient(f(x(k)))

where alpha(k), the step size at iteration k, depends on the particular choice of algorithm or learning rate schedule.

A second order method, for e.g., Newton, will have an update equation

x(k + 1) = x(k) - alpha(k) * Hessian(x(k))^(-1) * gradient(f(x(k)))

That is, it uses the information of the local curvature encoded in the Hessian to scale the gradient accordingly. If the problem is ill-conditioned, the gradient will be pointing in less than ideal directions and the inverse Hessian scaling will help correct this.

In particular, L-BFGS mentioned in @5ervant's answer is a way to approximate the inverse of the Hessian as computing it can be an expensive operation.

However, second-order methods might converge much faster (i.e., requires fewer iterations) than first-order methods like the usual gradient-descent based solvers, which as you guys know by now sometimes fail to even converge. This can compensate for the time spent at each iteration.

In summary, if you have a well-conditioned problem, or if you can make it well-conditioned through other means such as using regularization and/or feature scaling and/or making sure you have more examples than features, you probably don't have to use a second-order method. But these days with many models optimizing non-convex problems (e.g., those in DL models), second order methods such as L-BFGS methods plays a different role there and there are evidence to suggest they can sometimes find better solutions compared to first-order methods. But that is another story.

fatal: Not a valid object name: 'master'

First off, when you create a "bare repository", you're not going to be doing any work with it (it doesn't contain a working copy, so the git branch command is not useful).

Now, the reason you wouldn't have a master branch even after doing a git init is that there are no commits: when you create your first commit, you will then have a master branch.

Java correct way convert/cast object to Double

I tried this and it worked:

Object obj = 10;
String str = obj.toString(); 
double d = Double.valueOf(str).doubleValue();

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

Android YouTube app Play Video Intent

Replying to old question, just to inform you guys that package have changed, heres the update

Intent videoClient = new Intent(Intent.ACTION_VIEW);
videoClient.setData("VALID YOUTUBE LINK WITH HTTP");
videoClient.setClassName("com.google.android.youtube", "com.google.android.youtube.WatchActivity");
startActivity(videoClient);

This works very well, but when you call normal Intent with ACTION_VIEW with valid youtube URL user gets the Activity selector anyways.

How do I set a cookie on HttpClient's HttpRequestMessage

I had a similar problem and for my AspNetCore 3.1 application the other answers to this question were not working. I found that configuring a named HttpClient in my Startup.cs and using header propagation of the Cookie header worked perfectly. It also avoids all the concerns about proper disposition of your handler and client. Note if propagation of the request cookies is not what you need (sorry Op) you can set your own cookies when configuring the client factory.

Configure Services with IServiceCollection

services.AddHttpClient("MyNamedClient").AddHeaderPropagation();
services.AddHeaderPropagation(options =>
{
    options.Headers.Add("Cookie");
});

Configure with IApplicationBuilder

builder.UseHeaderPropagation();
  • Inject the IHttpClientFactory into your controller or middleware.
  • Create your client using var client = clientFactory.CreateClient("MyNamedClient");

string.split - by multiple character delimiter

string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);

How to import Google Web Font in CSS file?

Download the font ttf/other format files, then simply add this CSS code example:

_x000D_
_x000D_
@font-face { font-family: roboto-regular; _x000D_
    src: url('../font/Roboto-Regular.ttf'); } _x000D_
h2{_x000D_
 font-family: roboto-regular;_x000D_
}
_x000D_
_x000D_
_x000D_

Null & empty string comparison in Bash

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes

Ineligible Devices section appeared in Xcode 6.x.x

I simply restarted my Mac and my iPhone 6 and the problem was solved. I never had to change my deployment target.

Stop setInterval call in JavaScript

This is how I used clearInterval() method to stop the timer after 10 seconds.

_x000D_
_x000D_
function startCountDown() {_x000D_
  var countdownNumberEl = document.getElementById('countdown-number');_x000D_
  var countdown = 10;_x000D_
  const interval = setInterval(() => {_x000D_
    countdown = --countdown <= 0 ? 10 : countdown;_x000D_
    countdownNumberEl.textContent = countdown;_x000D_
    if (countdown == 1) {_x000D_
      clearInterval(interval);_x000D_
    }_x000D_
  }, 1000)_x000D_
}
_x000D_
<head>_x000D_
  <body>_x000D_
    <button id="countdown-number" onclick="startCountDown();">Show Time </button>_x000D_
  </body>_x000D_
</head>
_x000D_
_x000D_
_x000D_

SQL Server: UPDATE a table by using ORDER BY

update based on Ordering by the order of values in a SQL IN() clause

Solution:

DECLARE @counter int
SET @counter = 0

;WITH q  AS
        (
select * from Products WHERE ID in (SELECT TOP (10) ID FROM Products WHERE  ID IN( 3,2,1) 
ORDER BY ID DESC)
        )
update q set Display= @counter, @counter = @counter + 1

This updates based on descending 3,2,1

Hope helps someone.

How can I replace the deprecated set_magic_quotes_runtime in php?

ini_set('magic_quotes_runtime', 0)

I guess.

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

How to include External CSS and JS file in Laravel 5

Place your assets in public directory and use the following

URL::to()

example

<link rel="stylesheet" type="text/css" href="{{ URL::to('css/style.css') }}">
<script type="text/javascript" src="{{ URL::to('js/jquery.min.js') }}"></script>

Maven: How do I activate a profile from command line?

Both commands are correct :

mvn clean install -Pdev1
mvn clean install -P dev1

The problem is most likely not profile activation, but the profile not accomplishing what you expect it to.

It is normal that the command :

mvn help:active-profiles

does not display the profile, because is does not contain -Pdev1. You could add it to make the profile appear, but it would be pointless because you would be testing maven itself.

What you should do is check the profile behavior by doing the following :

  1. set activeByDefault to true in the profile configuration,
  2. run mvn help:active-profiles (to make sure it is effectively activated even without -Pdev1),
  3. run mvn install.

It should give the same results as before, and therefore confirm that the problem is the profile not doing what you expect.

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

first copy the cumber inside the file then remove it: rm /your_project_path/tmp/pids/server.pid then create it again. touch /YOUR_PROJECT_PATH/tmp/pids/server.pid It worked for me.

Check if year is leap year in javascript

A faster solution is provided by Kevin P. Rice here:https://stackoverflow.com/a/11595914/5535820 So here's the code:

function leapYear(year)
{
    return (year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0);
}

Java simple code: java.net.SocketException: Unexpected end of file from server

In my case url contained wrong chars like spaces . Overall log your url and in some cases use browser.

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

If you want to avoid the error message and you are not using Bootstrap tool tips, you can define window.Tether before loading Bootstrap.

<script>
  window.Tether = {};
</script>
<script src="js/bootstrap.min.js"></script>

How to call a function after delay in Kotlin?

val timer = Timer()
timer.schedule(timerTask { nextScreen() }, 3000)

How to select min and max values of a column in a datatable?

Performance wise, this should be comparable. Use Select statement and Sort to get a list and then pick the first or last (depending on your sort order).

var col = dt.Select("AccountLevel", "AccountLevel ASC");

var min = col.First();
var max = col.Last();

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

.NET / C# - Convert char[] to string

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);

How to style a disabled checkbox?

Use CSS's :disabled selector (for CSS3):

checkbox-style { }
checkbox-style:disabled { }

Or you need to use javascript to alter the style based on when you enable/disable it (Assuming it is being enabled/disabled based on your question).

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

how can I Update top 100 records in sql server

Without an ORDER BY the whole idea of TOP doesn't make much sense. You need to have a consistent definition of which direction is "up" and which is "down" for the concept of top to be meaningful.

Nonetheless SQL Server allows it but doesn't guarantee a deterministic result.

The UPDATE TOP syntax in the accepted answer does not support an ORDER BY clause but it is possible to get deterministic semantics here by using a CTE or derived table to define the desired sort order as below.

;WITH CTE AS 
( 
SELECT TOP 100 * 
FROM T1 
ORDER BY F2 
) 
UPDATE CTE SET F1='foo'

XML Schema How to Restrict Attribute by Enumeration

The numerical value seems to be missing from your price definition. Try the following:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />
  </xs:restriction>
</xs:simpleType>



<xs:element name="price">
        <xs:complexType>
            <xs:extension base="xs:decimal">
              <xs:attribute name="currency" type="curr"/>
            </xs:extension>
        </xs:complexType>
</xs:element>

Visual c++ can't open include file 'iostream'

Replace

#include <iostream.h>

with

using namespace std;

#include <iostream>

PostgreSQL how to see which queries have run

While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:

tail -f /var/log/postgresql/*

Ubuntu 18.04, django 2+, python3+

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

just add your .jar file in applet tag as an attribute as shown below:

<applet
    code="file.class"
    archive="file.jar"
    height=550 
    width=1100>         
</applet>

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Short answer:

There is no difference in semantic.

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Further reading:

RequestMapping can be used at class level:

This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.

while GetMapping only applies to method:

Annotation for mapping HTTP GET requests onto specific handler methods.


https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

Generating random numbers in C

You need to seed your PRNG so it starts with a different value each time.

A simple but low quality seed is to use the current time:

srand(time(0));

This will get you started but is considered low quality (i.e. for example, don't use that if you are trying to generate RSA keys).

Background. Pseudo-random number generators do not create true random number sequences but just simulate them. Given a starting point number, a PRNG will always return the same sequence of numbers. By default, they start with the same internal state so will return the same sequence.

To not get the same sequence, you change the internal state. The act of changing the internal state is called "seeding".

How do I make a redirect in PHP?

function Redirect($url, $permanent = false)
{
    if (headers_sent() === false)
    {
        header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
    }

    exit();
}

Redirect('http://www.google.com/', false);

Don't forget to die()/exit()!

Is there any way to prevent input type="number" getting negative values?

Just adding another way of doing this (using Angular) if you don't wanna dirt the HTML with even more code:

You only have to subscribe to the field valueChanges and set the Value as an absolute value (taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)

HTML CODE

<form [formGroup]="myForm">
    <input type="number" formControlName="myInput"/>
</form>

TypeScript CODE (Inside your Component)

formGroup: FormGroup;

ngOnInit() { 
    this.myInput.valueChanges 
    .subscribe(() => {
        this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
    });
}

get myInput(): AbstractControl {
    return this.myForm.controls['myInput'];
}

Difference between setTimeout with and without quotes and parentheses

With the parentheses:

setTimeout("alertMsg()", 3000); // It work, here it treat as a function

Without the quotes and the parentheses:

setTimeout(alertMsg, 3000); // It also work, here it treat as a function

And the third is only using quotes:

setTimeout("alertMsg", 3000); // It not work, here it treat as a string

_x000D_
_x000D_
function alertMsg1() {_x000D_
        alert("message 1");_x000D_
    }_x000D_
    function alertMsg2() {_x000D_
        alert("message 2");_x000D_
    }_x000D_
    function alertMsg3() {_x000D_
        alert("message 3");_x000D_
    }_x000D_
    function alertMsg4() {_x000D_
        alert("message 4");_x000D_
    }_x000D_
_x000D_
    // this work after 2 second_x000D_
    setTimeout(alertMsg1, 2000);_x000D_
_x000D_
    // This work immediately_x000D_
    setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
    // this fail_x000D_
    setTimeout('alertMsg3', 6000);_x000D_
_x000D_
    // this work after 8second_x000D_
    setTimeout('alertMsg4()', 8000);
_x000D_
_x000D_
_x000D_

In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.

Sorting HashMap by values

You don't, basically. A HashMap is fundamentally unordered. Any patterns you might see in the ordering should not be relied on.

There are sorted maps such as TreeMap, but they traditionally sort by key rather than value. It's relatively unusual to sort by value - especially as multiple keys can have the same value.

Can you give more context for what you're trying to do? If you're really only storing numbers (as strings) for the keys, perhaps a SortedSet such as TreeSet would work for you?

Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?

Git: How to return from 'detached HEAD' state

If you remember which branch was checked out before (e.g. master) you could simply

git checkout master

to get out of detached HEAD state.

Generally speaking: git checkout <branchname> will get you out of that.

If you don't remember the last branch name, try

git checkout -

This also tries to check out your last checked out branch.

Git error when trying to push -- pre-receive hook declined

In my case I got this error because a branch with the same name already existed. Deleting this branch off of the git server will fix this.

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

Please set your form action attribute as below it will solve your problem.

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        event.preventDefault();
        //grab all form data  
        var formData = $(this).serialize();

        $.ajax({
            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });
});

Replacing blank values (white space) with NaN in pandas

For a very fast and simple solution where you check equality against a single value, you can use the mask method.

df.mask(df == ' ')

How to delete an array element based on key?

You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()).
If so, just use unset():

unset($arr[1]);

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I was able to solve "ORA-00604: error" by Droping with purge.

DROP TABLE tablename PURGE

jQuery Refresh/Reload Page if Ajax Success after time

I prefer this way Using ajaxStop + setInterval,, this will refresh the page after any XHR[ajax] request in the same page

    $(document).ajaxStop(function() {
        setInterval(function() {
            location.reload();
        }, 3000);
    });

Get the new record primary key ID from MySQL insert query?

i used return $this->db->insert_id(); for Codeigniter

Python: Get HTTP headers from urllib2.urlopen call?

def _GetHtmlPage(self, addr):
  headers = { 'User-Agent' : self.userAgent,
            '  Cookie' : self.cookies}

  req = urllib2.Request(addr)
  response = urllib2.urlopen(req)

  print "ResponseInfo="
  print response.info()

  resultsHtml = unicode(response.read(), self.encoding)
  return resultsHtml  

Reading in from System.in - Java

You would read from System.in just like you would for keyboard input using, for example, InputStreamReader or Scanner.

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

How to add image that is on my computer to a site in css or html?

If you just want to see the image on your local browser, this can be done if you have a server running locally. You just need to reference the local server via http (not file://), like:

http://localhost/my_picture.jpg

if picture.jpg is in your local server's webroot folder. You can do this for any site if you open your browser's developer tools and change the img element's src attribute to the local server's URL for the image. If you have access to the HTML of your site, then change it there. But obviously if someone not on your local computer/server accesses the site, they will get a broken image unless they happen to be running a local server as well and have an image with the same filename, which would be weird.

Error inflating when extending a class

I had the same problem extending a TextEdit. For me the mistake was I did non add "public" to the constructor. In my case it works even if I define only one constructor, the one with arguments Context and AttributeSet. The wired thing is that the bug reveals itself only when I build an APK (singed or not) and I transfer it to the devices. When the application is run via AndroidStudio -> RunApp on a USB connected device the app works.

How to post a file from a form with Axios

Sample application using Vue. Requires a backend server running on localhost to process the request:

var app = new Vue({
  el: "#app",
  data: {
    file: ''
  },
  methods: {
    submitFile() {
      let formData = new FormData();
      formData.append('file', this.file);
      console.log('>> formData >> ', formData);

      // You should have a server side REST API 
      axios.post('http://localhost:8080/restapi/fileupload',
          formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        ).then(function () {
          console.log('SUCCESS!!');
        })
        .catch(function () {
          console.log('FAILURE!!');
        });
    },
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
      console.log('>>>> 1st element in files array >>>> ', this.file);
    }
  }
});

https://codepen.io/pmarimuthu/pen/MqqaOE

Icons missing in jQuery UI

Having the right CSS and JS libraries helps, this solved it for me

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

How to remove a branch locally?

By your tags, I'm assuming your using Github. Why not create some branch protection rules for your master branch? That way even if you do try to push to master, it will reject it.

1) Go to the 'Settings' tab of your repo on Github.

2) Click on 'Branches' on the left side-menu.

3) Click 'Add rule'

4) Enter 'master' for a branch pattern.

5) Check off 'Require pull request reviews before merging'

I would also recommend doing the same for your dev branch.

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

The difference is the amount of memory allocated to each integer, and how large a number they each can store.

Replace substring with another substring C++

If you are sure that the required substring is present in the string, then this will replace the first occurence of "abc" to "hij"

test.replace( test.find("abc"), 3, "hij");

It will crash if you dont have "abc" in test, so use it with care.

SQL Server Express CREATE DATABASE permission denied in database 'master'

  1. Download the script from this Microsoft Site
  2. Run it as Administrator
  3. Follow the instructions and your set.

UPDATE 9/3/2014

The Microsoft URL above is no longer valid, someone thou took the time to save it to GitHubGist and the link is as follows https://gist.github.com/wadewegner/1677788

Launch Android application without main Activity and start Service on launching application

The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found.

Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing. Then click ok and run the App.

(Since there is no launcher activity, No app will be show in the Apps menu.).

Error "The connection to adb is down, and a severe error has occurred."

Another error cause would be the fact you might have set up adb.exe to run with administrator privileges.

Sending intent to BroadcastReceiver from adb

Another thing to keep in mind: Android 8 limits the receivers that can be registered via manifest (e.g., statically)

https://developer.android.com/guide/components/broadcast-exceptions

How to fix homebrew permissions?

cd /usr/local && sudo chown -R $(whoami) bin etc include lib sbin share var opt Cellar Frameworks

Export to csv in jQuery

By using just jQuery, you cannot avoid a server call.

However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.

To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.

matplotlib get ylim values

Just use axes.get_ylim(), it is very similar to set_ylim. From the docs:

get_ylim()

Get the y-axis range [bottom, top]

C# password TextBox in a ASP.net website

To do it the ASP.NET way:

<asp:TextBox ID="txtBox1" TextMode="Password" runat="server" />

-bash: export: `=': not a valid identifier

First of all go to the /home directorty then open invisible shell script with some text editor, ~/.bash_profile (macOS) or ~/.bashrc (linux) go to the bottom, you would see something like this,

export LD_LIBRARY_PATH = /usr/local/lib

change this like that( remove blank point around the = ),

export LD_LIBRARY_PATH=/usr/local/lib

it should be useful.

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

for Xcode 8:

What I do is run sudo du -khd 1 in the Terminal to see my file system's storage amounts for each folder in simple text, then drill up/down into where the huge GB are hiding using the cd command.

Ultimately you'll find the Users//Library/Developer/CoreSimulator/Devices folder where you can have little concern about deleting all those "devices" using iOS versions you no longer need. It's also safe to just delete them all, but keep in mind you'll lose data that's written to the device like sqlite files you may want to use as a backup version.

I once saved over 50GB doing this since I did so much testing on older iOS versions.

Disable automatic sorting on the first column when using jQuery DataTables

this.dtOptions = {
    order: [],
    columnDefs: [ {
        'targets': [0], /* column index [0,1,2,3]*/
        'orderable': false, /* true or false */
    }],
    ........ rest all stuff .....
}

The above worked fine for me.

(I am using Angular version 7, angular-datatables version 6.0.0 and bootstrap version 4)

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

boto3 client NoRegionError: You must specify a region error only sometimes

you can also set environment variables in the script itself, rather than passing region_name parameter

os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'

case sensitivity may matter.

Where should I put the log4j.properties file?

I've spent a great deal of time to figure out why the log4j.properties file is not seen.
Then I noticed it was visible for the project only when it was in both MyProject/target/classes/ and MyProject/src/main/resources folders.
Hope it'll be useful to somebody.
PS: The project was maven-based.

Android lollipop change navigation bar color

For people using Kotlin you can put this in your MainActivity.kt:

window.navigationBarColor = ContextCompat.getColor(this@MainActivity, R.color.yourColor)

With window being:

val window: Window = [email protected]

Or you can put this in your themes.xml or styles.xml (requires API level 21):

<item name='android:navigationBarColor'>@color/yourColor</item>

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

I had the same issue. I checked the version of System.Data.SqlServerCe in C:\Windows\assembly. It was 3.5.1.0. So I installed version 4.0.0 from below link (x86) and works fine.

http://www.microsoft.com/download/en/details.aspx?id=17876

How to select the first element in the dropdown using jquery?

    var arr_select_val=[];

    $("select").each(function() { 
        var name=this.name;
            arr_select_val[name]=$('select option:first-child').val();
    });


// Process the array object
     $('.orders_status_summary_div').print(arr_select_val);

Why use 'git rm' to remove a file instead of 'rm'?

Remove files from the index, or from the working tree and the index. git rm will not remove a file from just your working directory.

Here's how you might delete a file using rm -f and then remove it from your index with git rm

$ rm -f index.html
$ git status -s
 D index.html
$ git rm index.html
rm 'index.html'
$ git status -s
D  index.html

However you can do this all in one go with just git rm

$ git status -s
$ git rm index.html
rm 'index.html'
$ ls
lib vendor
$ git status -s
D  index.html

Removing elements from an array in C

Interestingly array is randomly accessible by the index. And removing randomly an element may impact the indexes of other elements as well.

    int remove_element(int*from, int total, int index) {
            if((total - index - 1) > 0) {
                      memmove(from+i, from+i+1, sizeof(int)*(total-index-1));
            }
            return total-1; // return the new array size
    }

Note that memcpy will not work in this case because of the overlapping memory.

One of the efficient way (better than memory move) to remove one random element is swapping with the last element.

    int remove_element(int*from, int total, int index) {
            if(index != (total-1))
                    from[index] = from[total-1];
            return total; // **DO NOT DECREASE** the total here
    }

But the order is changed after the removal.

Again if the removal is done in loop operation then the reordering may impact processing. Memory move is one expensive alternative to keep the order while removing an array element. Another of the way to keep the order while in a loop is to defer the removal. It can be done by validity array of the same size.

    int remove_element(int*from, int total, int*is_valid, int index) {
            is_valid[index] = 0;
            return total-1; // return the number of elements
    }

It will create a sparse array. Finally, the sparse array can be made compact(that contains no two valid elements that contain invalid element between them) by doing some reordering.

    int sparse_to_compact(int*arr, int total, int*is_valid) {
            int i = 0;
            int last = total - 1;
            // trim the last invalid elements
            for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements from last

            // now we keep swapping the invalid with last valid element
            for(i=0; i < last; i++) {
                    if(is_valid[i])
                            continue;
                    arr[i] = arr[last]; // swap invalid with the last valid
                    last--;
                    for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements
            }
            return last+1; // return the compact length of the array
    }

anchor jumping by using javascript

Not enough rep for a comment.

The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).

Something to bare in mind if you don't have control of the document markup (e.g. webextension).

The location based method in the selected answer can also be simplified with location.replace:

function jump(hash) { location.replace("#" + hash) }

How to define Singleton in TypeScript

The best way I have found is:

class SingletonClass {

    private static _instance:SingletonClass = new SingletonClass();

    private _score:number = 0;

    constructor() {
        if(SingletonClass._instance){
            throw new Error("Error: Instantiation failed: Use SingletonClass.getInstance() instead of new.");
        }
        SingletonClass._instance = this;
    }

    public static getInstance():SingletonClass
    {
        return SingletonClass._instance;
    }

    public setScore(value:number):void
    {
        this._score = value;
    }

    public getScore():number
    {
        return this._score;
    }

    public addPoints(value:number):void
    {
        this._score += value;
    }

    public removePoints(value:number):void
    {
        this._score -= value;
    }

}

Here is how you use it:

var scoreManager = SingletonClass.getInstance();
scoreManager.setScore(10);
scoreManager.addPoints(1);
scoreManager.removePoints(2);
console.log( scoreManager.getScore() );

https://codebelt.github.io/blog/typescript/typescript-singleton-pattern/

Present and dismiss modal view controller

presentModalViewController:

MainViewController *mainViewController=[[MainViewController alloc]init];
[self.navigationController presentModalViewController:mainViewController animated:YES];

dismissModalViewController:

[self dismissModalViewControllerAnimated:YES];

Ignore <br> with CSS?

With css, you can "hide" the br tags and they won't have an effect:

br {
    display: none;
}

If you only want to hide some within a specific heading type, just make your css more specific.

h3 br {
    display: none;
}

How to change Bootstrap's global default font size?

There are several ways but since you are using just the CSS version and not the SASS or LESS versions, your best bet to use Bootstraps own customization tool:

http://getbootstrap.com/customize/

Customize whatever you want on this page and then you can download a custom build with your own font sizes and anything else you want to change.

Altering the CSS file directly (or simply adding new CSS styles that override the Bootstrap CSS) is not recommended because other Bootstrap styles' values are derived from the base font size. For example:

https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_variables.scss#L52

You can see that the base font size is used to calculate the sizes of the h1, h2, h3 etc. If you just changed the font size in the CSS (or added your own overriding font-size) all the other values that used the font size in calculations would no longer be proportionally accurate according to Bootstrap's design.

As I said, your best bet is to just use their own Customize tool. That is exactly what it's for.

If you are using SASS or LESS, you would change the font size in the variables file before compiling.

When do I use super()?

You call super() to specifically run a constructor of your superclass. Given that a class can have multiple constructors, you can either call a specific constructor using super() or super(param,param) oder you can let Java handle that and call the standard constructor. Remember that classes that follow a class hierarchy follow the "is-a" relationship.

Jmeter - Run .jmx file through command line and get the summary report in a excel

You can use this command,

jmeter -n -t /path to the script.jmx -l /path to save results with file name file.jtl

But if you really want to run a load test in a remote machine, you should be able to make it run eventhough you close the window. So we can use nohup to ignore the HUP (hangup) signal. So you can use this command as below.

nohup sh jmeter.sh -n -t /path to the script.jmx -l /path to save results with file name file.jtl &

Getting all selected checkboxes in an array

here is my code for the same problem someone can also try this. jquery

<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];        
$.each($("input[name='check1']:checked"), function(){                    
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>

How do I get the row count of a Pandas DataFrame?

Suppose df is your dataframe then:

count_row = df.shape[0]  # Gives number of rows
count_col = df.shape[1]  # Gives number of columns

Or, more succinctly,

r, c = df.shape

log4j vs logback

Should you? Yes.

Why? Log4J has essentially been deprecated by Logback.

Is it urgent? Maybe not.

Is it painless? Probably, but it may depend on your logging statements.

Note that if you really want to take full advantage of LogBack (or SLF4J), then you really need to write proper logging statements. This will yield advantages like faster code because of the lazy evaluation, and less lines of code because you can avoid guards.

Finally, I highly recommend SLF4J. (Why recreate the wheel with your own facade?)

Take n rows from a spark dataframe and pass to toPandas()

Try it:

def showDf(df, count=None, percent=None, maxColumns=0):
    if (df == None): return
    import pandas
    from IPython.display import display
    pandas.set_option('display.encoding', 'UTF-8')
    # Pandas dataframe
    dfp = None
    # maxColumns param
    if (maxColumns >= 0):
        if (maxColumns == 0): maxColumns = len(df.columns)
        pandas.set_option('display.max_columns', maxColumns)
    # count param
    if (count == None and percent == None): count = 10 # Default count
    if (count != None):
        count = int(count)
        if (count == 0): count = df.count()
        pandas.set_option('display.max_rows', count)
        dfp = pandas.DataFrame(df.head(count), columns=df.columns)
        display(dfp)
    # percent param
    elif (percent != None):
        percent = float(percent)
        if (percent >=0.0 and percent <= 1.0):
            import datetime
            now = datetime.datetime.now()
            seed = long(now.strftime("%H%M%S"))
            dfs = df.sample(False, percent, seed)
            count = df.count()
            pandas.set_option('display.max_rows', count)
            dfp = dfs.toPandas()    
            display(dfp)

Examples of usages are:

# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)

# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15) 

Is there a PowerShell "string does not contain" cmdlet or syntax?

If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:

Get-Content $FileName | foreach-object { `
   if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }

or better (IMO)

Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}

Pandas dataframe get first row of each group

>>> df.groupby('id').first()
     value
id        
1    first
2    first
3    first
4   second
5    first
6    first
7   fourth

If you need id as column:

>>> df.groupby('id').first().reset_index()
   id   value
0   1   first
1   2   first
2   3   first
3   4  second
4   5   first
5   6   first
6   7  fourth

To get n first records, you can use head():

>>> df.groupby('id').head(2).reset_index(drop=True)
    id   value
0    1   first
1    1  second
2    2   first
3    2  second
4    3   first
5    3   third
6    4  second
7    4   fifth
8    5   first
9    6   first
10   6  second
11   7  fourth
12   7   fifth

super() raises "TypeError: must be type, not classobj" for new-style class

FWIW and though I'm no Python guru I got by with this

>>> class TextParser(HTMLParser):
...    def handle_starttag(self, tag, attrs):
...        if tag == "b":
...            self.all_data.append("bold")
...        else:
...            self.all_data.append("other")
...     
...         
>>> p = TextParser()
>>> p.all_data = []
>>> p.feed(text)
>>> print p.all_data
(...)

Just got me the parse results back as needed.

Is embedding background image data into CSS as Base64 good or bad practice?

One of the things I would suggest is to have two separate stylesheets: One with your regular style definitions and another one that contains your images in base64 encoding.

You have to include the base stylesheet before the image stylesheet of course.

This way you will assure that you're regular stylesheet is downloaded and applied as soon as possible to the document, yet at the same time you profit from reduced http-requests and other benefits data-uris give you.

Speed up rsync with Simultaneous/Concurrent File Transfers?

You can use xargs which supports running many processes at a time. For your case it will be:

ls -1 /main/files | xargs -I {} -P 5 -n 1 rsync -avh /main/files/{} /main/filesTest/

Failed to Connect to MySQL at localhost:3306 with user root

Steps:

1 - Right click on your task bar -->Start Task Manager

2 - Click on Services button (at bottom).

3 - Search for MYSQL57

4 - Right Click on MYSQL57 --> Start

Now again start your mysql-cmd-prompt or MYSQL WorkBench

What is Mocking?

There are plenty of answers on SO and good posts on the web about mocking. One place that you might want to start looking is the post by Martin Fowler Mocks Aren't Stubs where he discusses a lot of the ideas of mocking.

In one paragraph - Mocking is one particlar technique to allow testing of a unit of code with out being reliant upon dependencies. In general, what differentiates mocking from other methods is that mock objects used to replace code dependencies will allow expectations to be set - a mock object will know how it is meant to be called by your code and how to respond.


Your original question mentioned TypeMock, so I've left my answer to that below:

TypeMock is the name of a commercial mocking framework.

It offers all the features of the free mocking frameworks like RhinoMocks and Moq, plus some more powerful options.

Whether or not you need TypeMock is highly debatable - you can do most mocking you would ever want with free mocking libraries, and many argue that the abilities offered by TypeMock will often lead you away from well encapsulated design.

As another answer stated 'TypeMocking' is not actually a defined concept, but could be taken to mean the type of mocking that TypeMock offers, using the CLR profiler to intercept .Net calls at runtime, giving much greater ability to fake objects (not requirements such as needing interfaces or virtual methods).

Abort a git cherry-pick?

I found the answer is git reset --merge - it clears the conflicted cherry-pick attempt.

How do I Validate the File Type of a File Upload?

As another respondent notes, the file type can be spoofed (e.g., .exe renamed .pdf), which checking for the MIME type will not prevent (i.e., the .exe will show a MIME of "application/pdf" if renamed as .pdf). I believe a check of the true file type can only be done server side; an easy way to check it using System.IO.BinaryReader is described here:

http://forums.asp.net/post/2680667.aspx

and VB version here:

http://forums.asp.net/post/2681036.aspx

Note that you'll need to know the binary 'codes' for the file type(s) you're checking for, but you can get them by implementing this solution and debugging the code.

Is it not possible to stringify an Error using JSON.stringify?

None of the answers above seemed to properly serialize properties which are on the prototype of Error (because getOwnPropertyNames() does not include inherited properties). I was also not able to redefine the properties like one of the answers suggested.

This is the solution I came up with - it uses lodash but you could replace lodash with generic versions of those functions.

 function recursivePropertyFinder(obj){
    if( obj === Object.prototype){
        return {};
    }else{
        return _.reduce(Object.getOwnPropertyNames(obj), 
            function copy(result, value, key) {
                if( !_.isFunction(obj[value])){
                    if( _.isObject(obj[value])){
                        result[value] = recursivePropertyFinder(obj[value]);
                    }else{
                        result[value] = obj[value];
                    }
                }
                return result;
            }, recursivePropertyFinder(Object.getPrototypeOf(obj)));
    }
}


Error.prototype.toJSON = function(){
    return recursivePropertyFinder(this);
}

Here's the test I did in Chrome:

var myError = Error('hello');
myError.causedBy = Error('error2');
myError.causedBy.causedBy = Error('error3');
myError.causedBy.causedBy.displayed = true;
JSON.stringify(myError);

{"name":"Error","message":"hello","stack":"Error: hello\n    at <anonymous>:66:15","causedBy":{"name":"Error","message":"error2","stack":"Error: error2\n    at <anonymous>:67:20","causedBy":{"name":"Error","message":"error3","stack":"Error: error3\n    at <anonymous>:68:29","displayed":true}}}  

SQL Server - stop or break execution of a SQL script

The raiserror method

raiserror('Oh no a fatal error', 20, -1) with log

This will terminate the connection, thereby stopping the rest of the script from running.

Note that both severity level 20 or higher and the WITH LOG option are necessary for it to work this way.

This even works with GO statements, eg.

print 'hi'
go
raiserror('Oh no a fatal error', 20, -1) with log
go
print 'ho'

Will give you the output:

hi
Msg 2745, Level 16, State 2, Line 1
Process ID 51 has raised user error 50000, severity 20. SQL Server is terminating this process.
Msg 50000, Level 20, State 1, Line 1
Oh no a fatal error
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command.  The results, if any, should be discarded.

Notice that 'ho' is not printed.

CAVEATS:

  • This only works if you are logged in as admin ('sysadmin' role), and also leaves you with no database connection.
  • If you are NOT logged in as admin, the RAISEERROR() call itself will fail and the script will continue executing.
  • When invoked with sqlcmd.exe, exit code 2745 will be reported.

Reference: http://www.mydatabasesupport.com/forums/ms-sqlserver/174037-sql-server-2000-abort-whole-script.html#post761334

The noexec method

Another method that works with GO statements is set noexec on. This causes the rest of the script to be skipped over. It does not terminate the connection, but you need to turn noexec off again before any commands will execute.

Example:

print 'hi'
go

print 'Fatal error, script will not continue!'
set noexec on

print 'ho'
go

-- last line of the script
set noexec off -- Turn execution back on; only needed in SSMS, so as to be able 
               -- to run this script again in the same session.

Docker error : no space left on device

If it's just a test installation of Docker (ie not production) and you don't care about doing a nuclear clean, you can:

clean all containers: docker ps -a | sed '1 d' | awk '{print $1}' | xargs -L1 docker rm

clean all images: docker images -a | sed '1 d' | awk '{print $3}' | xargs -L1 docker rmi -f

Again, I use this in my ec2 instances when developing Docker, not in any serious QA or Production path. The great thing is that if you have your Dockerfile(s), it's easy to rebuild and or docker pull.

Setting PHPMyAdmin Language

sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php and set:

$cfg['Lang'] = 'en-utf-8';

C++ - struct vs. class

The other difference is that

template<class T> ...

is allowed, but

template<struct T> ...

is not.

How to build a Debian/Ubuntu package from source?

First, the title question: Assuming the debian directory is already there, be in the source directory (the directory containing the debian directory) and invoke dpkg-buildpackage. I like to run it with these options:

dpkg-buildpackage -us -uc -nc

which mean don't sign the result and don't clean.

How can I check if I have listed all the dependencies correctly?

Getting the dependencies is a black art. The "official" way is to check build depends is if the package builds with only the base system, the "build-essential" packages, and the build dependencies you have specified. Don't know a general answer for regular Dependencies, just wade in :)

How I can I prevent the update system installing the older version in the repo on an update? How I can prevent the system installing a newer version (when its out), overwriting my custom package?

My knowledge might be out of date on this one, but to address both: Use dpkg --set-selections. Assuming nullidentd was the package you wanted to stay put, run as root

echo 'nullidentd hold' | dpkg --set-selections

Alternately, since you are building from source, you can use an epoch to set the version number artificially high and never be bothered again. To use an epoch, add a new entry to the debian/changelog file, and put a 99: in front of the version number. Given my nullidentd example, the first line of your updated changelog would read:

nullidentd (99:1.0-4) unstable; urgency=low

Bernard's link is good, especially if you have to create the debian directory yourself - also helpful are the developers reference and the general resource page. Adam's link also looks good but I'm not familiar with it.

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

For me, the problem that caused this error arose when I was saving a new row to the database, but a field was null. In the database table design, that field is NOT NULL. So when I tried to save a new row with a null value for not-null field, Visual Studio threw this error. Thus, I made sure that the field was assigned a value, and the problem was fixed.

How do I configure Maven for offline development?

You can run maven in offline mode mvn -o install. Of course any artifacts not available in your local repository will fail. Maven is not predicated on distributed repositories, but they certainly make things more seamless. Its for this reason that many shops use internal mirrors that are incrementally synced with the central repos.

In addition, the mvn dependency:go-offline can be used to ensure you have all of your dependencies installed locally before you begin to work offline.

How to escape apostrophe (') in MySql?

I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe

eg. 'This is John's place'

Here MYSQL assumes two sentence 'This is John' 's place'

You can put 'This is John''s place'. I think it should work that way.

How to call a method function from another class?

You need to instantiate the other classes inside the main class;

Date d = new Date(params);
TemperatureRange t = new TemperatureRange(params);

You can then call their methods with:

object.methodname(params);
d.method();

You currently have constructors in your other classes. You should not return anything in these.

public Date(params){
    set variables for date object
}

Next you need a method to reference.

public returnType methodName(params){
  return something;
}

Check if registry key exists using VBScript

In case anyone else runs into this, I took WhoIsRich's example and modified it a bit. When calling ReadReg I needed to do the following: ReadReg("App", "HKEY_CURRENT_USER\App\Version") which would then be able to read the version number from the registry, if it existed. I also am using HKCU since it does not require admin privileges to write to.

Function ReadReg(RegKey, RegPath)
      Const HKEY_CURRENT_USER = &H80000001
      Dim objRegistry, oReg
      Set objRegistry = CreateObject("Wscript.shell")
      Set oReg = GetObject("winmgmts:!root\default:StdRegProv")

      if oReg.EnumKey(HKEY_CURRENT_USER, RegKey) = 0 Then
        ReadReg = objRegistry.RegRead(RegPath)
      else
        ReadReg = ""
      end if
End Function

How to loop over files in directory and change path and add suffix to filename

Looks like you're trying to execute a windows file (.exe) Surely you ought to be using powershell. Anyway on a Linux bash shell a simple one-liner will suffice.

[/home/$] for filename in /Data/*.txt; do for i in {0..3}; do ./MyProgam.exe  Data/filenameLogs/$filename_log$i.txt; done done

Or in a bash

#!/bin/bash

for filename in /Data/*.txt; 
   do
     for i in {0..3}; 
       do ./MyProgam.exe Data/filename.txt Logs/$filename_log$i.txt; 
     done 
 done

Can media queries resize based on a div element instead of the screen?

After nearly a decade of work — with proposals, proofs-of-concept, discussions and other contributions by the broader web developer community — the CSS Working Group has finally laid some of the groundwork needed for container queries to be written into a future edition of the CSS Containment spec! For more details on how such a feature might work and be used, check out Miriam Suzanne's extensive explainer.

Hopefully it won't be much longer before we see a robust cross-browser implementation of such a system. It's been a grueling wait, but I'm glad that it's no longer something we simply have to accept as an insurmountable limitation of CSS due to cyclic dependencies or infinite loops or what have you (these are still a potential issue in some aspects of the proposed design, but I have faith that the CSSWG will find a way).


Media queries aren't designed to work based on elements in a page. They are designed to work based on devices or media types (hence why they are called media queries). width, height, and other dimension-based media features all refer to the dimensions of either the viewport or the device's screen in screen-based media. They cannot be used to refer to a certain element on a page.

If you need to apply styles depending on the size of a certain div element on your page, you'll have to use JavaScript to observe changes in the size of that div element instead of media queries.

Alternatively, with more modern layout techniques introduced since the original publication of this answer such as flexbox and standards such as custom properties, you may not need media or element queries after all. Djave provides an example.

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

$record = '123';

$this->db->distinct();

$this->db->select('accessid');

$this->db->where('record', $record); 

$query = $this->db->get('accesslog');

then

$query->num_rows();

should go a long way towards it.

What is the difference between join and merge in Pandas?

I believe that join() is just a convenience method. Try df1.merge(df2) instead, which allows you to specify left_on and right_on:

In [30]: left.merge(right, left_on="key1", right_on="key2")
Out[30]: 
  key1  lval key2  rval
0  foo     1  foo     4
1  bar     2  bar     5

Rank function in MySQL

Here is a generic solution that assigns dense rank over partition to rows. It uses user variables:

CREATE TABLE person (
    id INT NOT NULL PRIMARY KEY,
    firstname VARCHAR(10),
    gender VARCHAR(1),
    age INT
);

INSERT INTO person (id, firstname, gender, age) VALUES
(1,  'Adams',  'M', 33),
(2,  'Matt',   'M', 31),
(3,  'Grace',  'F', 25),
(4,  'Harry',  'M', 20),
(5,  'Scott',  'M', 30),
(6,  'Sarah',  'F', 30),
(7,  'Tony',   'M', 30),
(8,  'Lucy',   'F', 27),
(9,  'Zoe',    'F', 30),
(10, 'Megan',  'F', 26),
(11, 'Emily',  'F', 20),
(12, 'Peter',  'M', 20),
(13, 'John',   'M', 21),
(14, 'Kate',   'F', 35),
(15, 'James',  'M', 32),
(16, 'Cole',   'M', 25),
(17, 'Dennis', 'M', 27),
(18, 'Smith',  'M', 35),
(19, 'Zack',   'M', 35),
(20, 'Jill',   'F', 25);

SELECT person.*, @rank := CASE
    WHEN @partval = gender AND @rankval = age THEN @rank
    WHEN @partval = gender AND (@rankval := age) IS NOT NULL THEN @rank + 1
    WHEN (@partval := gender) IS NOT NULL AND (@rankval := age) IS NOT NULL THEN 1
END AS rnk
FROM person, (SELECT @rank := NULL, @partval := NULL, @rankval := NULL) AS x
ORDER BY gender, age;

Notice that the variable assignments are placed inside the CASE expression. This (in theory) takes care of order of evaluation issue. The IS NOT NULL is added to handle datatype conversion and short circuiting issues.

PS: It can easily be converted to row number over partition by by removing all conditions that check for tie.

| id | firstname | gender | age | rank |
|----|-----------|--------|-----|------|
| 11 | Emily     | F      | 20  | 1    |
| 20 | Jill      | F      | 25  | 2    |
| 3  | Grace     | F      | 25  | 2    |
| 10 | Megan     | F      | 26  | 3    |
| 8  | Lucy      | F      | 27  | 4    |
| 6  | Sarah     | F      | 30  | 5    |
| 9  | Zoe       | F      | 30  | 5    |
| 14 | Kate      | F      | 35  | 6    |
| 4  | Harry     | M      | 20  | 1    |
| 12 | Peter     | M      | 20  | 1    |
| 13 | John      | M      | 21  | 2    |
| 16 | Cole      | M      | 25  | 3    |
| 17 | Dennis    | M      | 27  | 4    |
| 7  | Tony      | M      | 30  | 5    |
| 5  | Scott     | M      | 30  | 5    |
| 2  | Matt      | M      | 31  | 6    |
| 15 | James     | M      | 32  | 7    |
| 1  | Adams     | M      | 33  | 8    |
| 18 | Smith     | M      | 35  | 9    |
| 19 | Zack      | M      | 35  | 9    |

Demo on db<>fiddle

C# Collection was modified; enumeration operation may not execute

The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):

C# Collection was modified; enumeration operation may not execute.

Your problem is the loop

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

wherein you modify the collection rankings. In particular, the offensive line is

rankings[kvp.Key] = rankings[kvp.Key] + 4;

Before you enter the loop, add the following line:

var listOfRankingsToModify = new List<int>();

Replace the offending line with

listOfRankingsToModify.Add(kvp.Key);

and after you exit the loop

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

Jquery onclick on div

Nothing.

$('#content').click(function(e) {  
    alert(1);
});

Will bind to an existing HTML element with the ID set to content, and will show a message box on click.

  • Make sure that #content exists before using that code
  • That the ID is unique
  • Check your Javascript console for any errors or issues

Use the auto keyword in C++ STL

If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features

atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
    ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
    //...
}

Android get image path from drawable as string

These all are ways:

String imageUri = "drawable://" + R.drawable.image;

Other ways I tested

Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");

String path = path.toString();
String path = otherPath .toString();

Do I need <class> elements in persistence.xml?

for JPA 2+ this does the trick

 <jar-file></jar-file>

scan all jars in war for annotated @Entity classes

Android 6.0 multiple permissions

Use helper like this (permissions names do not matter).

public class MyPermission {

private static final int PERMISSION_REQUEST_ALL = 127;
private MainActivity mMainActivity;

MyPermission(MainActivity mainActivity) {
    mMainActivity = mainActivity;
}

public static boolean hasPermission(String permission, Context context) {
    if (isNewPermissionModel()) {
        return (ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED);
    }
    return true;
}

private static boolean hasPermissions(Context context, String... permissions) {
    if (isNewPermissionModel() && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

private static boolean shouldShowRationale(Activity activity, String permission) {
    return isNewPermissionModel() && ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
}

private static boolean isNewPermissionModel() {
    return VERSION.SDK_INT > VERSION_CODES.LOLLIPOP_MR1;
}


/**
 * check all permissions
 */
void checkAll() {
    //check dangerous permissions, make request if need (Android will ask only for the ones it needs)
    String[] PERMISSIONS = {
            permission.READ_CALENDAR,           
            permission.ACCESS_COARSE_LOCATION   
    };

    if (!hasPermissions(mMainActivity, PERMISSIONS)) {
        ActivityCompat.requestPermissions(mMainActivity, PERMISSIONS, PERMISSION_REQUEST_ALL);
    }
}

void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == PERMISSION_REQUEST_ALL) {
        if (grantResults.length > 0) {
            //for not granted
            for (int i = 0; i < permissions.length; i++) {

                if (permissions[i].equals(permission.READ_CALENDAR)) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        smartRequestPermissions(permission.READ_CALENDAR, R.string.permission_required_dialog_read_calendar);
                    }
                } else if (permissions[i].equals(permission.ACCESS_COARSE_LOCATION)) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        smartRequestPermissions(permission.ACCESS_COARSE_LOCATION, R.string.permission_required_dialog_access_coarse_location);
                    }
                }

            }
        }
    }
}

private void smartRequestPermissions(final String permissionName, int permissionRequiredDialog) {
    if (shouldShowRationale(mMainActivity, permissionName)) {// If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false.

        //Show an explanation to the user with action
        mMainActivity.mSnackProgressBarManager.show(
                new SnackProgressBar(
                        SnackProgressBar.TYPE_ACTION, mMainActivity.getString(permissionRequiredDialog)
                )
                        .setAction("OK", new OnActionClickListener() {
                            @Override
                            public void onActionClick() {
                                checkAll();
                            }
                        })
                        .setSwipeToDismiss(true).setAllowUserInput(true)
                , MainActivity.SNACKBAR_WARNING_DURATION
        );

    } // else do nothing
}

}

pytest cannot import module while python can

If it is related to python code that was originally developed in python 2.7 and now migrated into python 3.x than the problem is probably related to an import issue.

e.g. when importing an object from a file: base that is located in the same directory this will work in python 2.x:

from base import MyClass

in python 3.x you should replace with base full path or .base not doing so will cause the above problem. so try:

from .base import MyClass

Settings to Windows Firewall to allow Docker for Windows to share drive

Everything everyone posted DID NOT WORK for me.

THIS DID.

I installed the EDGE release. I then went to WINDOWS DEFENDER and disabled the firewall for DOCKER NAT. (not my actual ethernet adapter, just the docker nat)

Once I disabled windows defender/firewall THAT way it worked fine.

ugh. really hopes that helps some of you!

Error #2032: Stream Error

From a quick google search it seems that the problem is a file or url couldn't be found be the HTTPservice.

Here are the links where I found this information:

http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/

http://curtismorley.com/2008/02/08/actionscript-error-2032/

Getting text from td cells with jQuery

$(".field-group_name").each(function() {
        console.log($(this).text());
    });

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

If you want to select multiple files from the file selector dialog that displays when you select browse then you are mostly out of luck. You will need to use a Java applet or something similar (I think there is one that use a small flash file, I will update if I find it). Currently a single file input only allows the selection of a single file.

If you are talking about using multiple file inputs then there shouldn't be much difference from using one. Post some code and I will try to help further.


Update: There is one method to use a single 'browse' button that uses flash. I have never personally used this but I have read a fair amount about it. I think its your best shot.

http://swfupload.org/

How do I get Maven to use the correct repositories?

By default, Maven will always look in the official Maven repository, which is http://repo1.maven.org.

When Maven tries to build a project, it will look in your local repository (by default ~/.m2/repository but you can configure it by changing the <localRepository> value in your ~/.m2/settings.xml) to find any dependency, plugin or report defined in your pom.xml. If the adequate artifact is not found in your local repository, it will look in all external repositories configured, starting with the default one, http://repo1.maven.org.

You can configure Maven to avoid this default repository by setting a mirror in your settings.xml file:

<mirrors>
    <mirror>
        <id>repoMirror</id>
        <name>Our mirror for Maven repository</name>
        <url>http://the/server/</url>
        <mirrorOf>*</mirrorOf>
    </mirror>
</mirrors>

This way, instead of contacting http://repo1.maven.org, Maven will contact your entreprise repository (http://the/server in this example).

If you want to add another repository, you can define a new one in your settings.xml file:

<profiles>
    <profile>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <repositories>
            <repository>
                <id>foo.bar</id>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
                <url>http://new/repository/server</url>
            </repository>
        </repositories>

You can see the complete settings.xml model here.

Concerning the clean process, you can ask Maven to run it offline. In this case, Maven will not try to reach any external repositories:

mvn -o clean 

How do I push a new local branch to a remote Git repository and track it too?

Building slightly upon the answers here, I've wrapped this process up as a simple Bash script, which could of course be used as a Git alias as well.

The important addition to me is that this prompts me to run unit tests before committing and passes in the current branch name by default.

$ git_push_new_branch.sh

  Have you run your unit tests yet? If so, pass OK or a branch name, and try again

  usage: git_push_new_branch {OK|BRANCH_NAME}

  e.g.

  git_push_new_branch           -> Displays prompt reminding you to run unit tests
  git_push_new_branch OK        -> Pushes the current branch as a new branch to the origin
  git_push_new_branch MYBRANCH  -> Pushes branch MYBRANCH as a new branch to the origin

git_push_new_branch.sh

function show_help()
{
  IT=$(cat <<EOF

  Have you run your unit tests yet? If so, pass OK or a branch name, and try again

  usage: git_push_new_branch {OK|BRANCH_NAME}

  e.g.

  git_push_new_branch.sh           -> Displays prompt reminding you to run unit tests
  git_push_new_branch.sh OK        -> Pushes the current branch as a new branch to the origin
  git_push_new_branch.sh MYBRANCH  -> Pushes branch MYBRANCH as a new branch to the origin

  )
  echo "$IT"
  exit
}

if [ -z "$1" ]
then
  show_help
fi

CURR_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$1" == "OK" ]
then
  BRANCH=$CURR_BRANCH
else
  BRANCH=${1:-$CURR_BRANCH}
fi

git push -u origin $BRANCH

"Sub or Function not defined" when trying to run a VBA script in Outlook

I need to add that, if the Module name and the sub name is the same you have such issue. Consider change the Module name to mod_Test instead of "Test" which is the same as the sub.

TextView - setting the text size programmatically doesn't seem to work

Text size 2 will be practically invisible. Try it with 14 at least. BTW, using xml has a lot of advantages and will make your life easier once you need to do anything more complex than 'Hello World'.

mat-form-field must contain a MatFormFieldControl

Unfortunately content projection into mat-form-field is not supported yet. Please track the following github issue to get the latest news about it.

By now the only solution for you is either place your content directly into mat-form-field component or implement a MatFormFieldControl class thus creating a custom form field component.

CASE .. WHEN expression in Oracle SQL

Following syntax would work :

....
where x.p_NBR =to_number(substr(y.k_str,11,5))
and x.q_nbr = 
 (case 
 when instr(substr(y.m_str,11,9),'_') = 6   then  to_number(substr(y.m_str,11,5))
 when instr(substr(y.m_str,11,9),'_') = 0   then  to_number(substr(y.m_str,11,9))
  else 
       1
  end
)

Plotting 4 curves in a single plot, with 3 y-axes

This is a great chance to introduce you to the File Exchange. Though the organization of late has suffered from some very unfortunately interface design choices, it is still a great resource for pre-packaged solutions to common problems. Though many here have given you the gory details of how to achieve this (@prm!), I had a similar need a few years ago and found that addaxis worked very well. (It was a File Exchange pick of the week at one point!) It has inspired later, probably better mods. Here is some example output:

addaxis example http://www.mathworks.com/matlabcentral/fx_files/9016/1/addaxis_screenshot.jpg

I just searched for "plotyy" at File Exchange.

Though understanding what's going on in important, sometimes you just need to get things done, not do them yourself. Matlab Central is great for that.

How to append new data onto a new line

I had the same issue. And I was able to solve it by using a formatter.

file_name = "abc.txt"
new_string = "I am a new string."
opened_file = open(file_name, 'a')
opened_file.write("%r\n" %new_string)
opened_file.close()

I hope this helps.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

Just using

HttpContext.Current.GetOwinContext()

did the trick in my case.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

Here is specifically what worked for me only when the Excel file being queried was not open and when running the SQL Server Service as me [as a user that has access to the file system]. I see pieces of my answer already given elsewhere, so I apologize for any redundancy, but for the sake of a more succinct answer:

USE [master]
GO

EXEC sp_configure 'Show Advanced Options', 1
RECONFIGURE
GO

EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE
GO

EXEC sp_MSSet_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO

EXEC sp_MSSet_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO


SELECT * 
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                'Excel 12.0;Database=C:\MyExcelFile.xlsx',
                'SELECT * FROM [MyExcelSheetName$]')

Is it correct to use alt tag for an anchor link?

Such things are best answered by looking at the official specification:

  1. go to the specification: https://www.w3.org/TR/html5/

  2. search for "a element": https://www.w3.org/TR/html5/text-level-semantics.html#the-a-element

  3. check "Content attributes", which lists all allowed attributes for the a element:

    • Global attributes
    • href
    • target
    • download
    • rel
    • hreflang
    • type
  4. check the linked "Global attributes": https://www.w3.org/TR/html5/dom.html#global-attributes

As you will see, the alt attribute is not allowed on the a element.
Also you’d notice that the src attribute isn’t allowed either.

By validating your HTML, errors like these are reported to you.


Note that the above is for HTML5, which is W3C’s HTML standard from 2014. In 2016, HTML 5.1 became the next HTML standard. Finding the allowed attributes works in the same way. You’ll see that the a element can have another attribute in HTML 5.1: rev.

You can find all HTML specifications (including the latest standard) on W3C’s HTML Current Status.

sort json object in javascript

First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.

Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.

One option might be to make your data look like this:

var json = [{
    "name": "user1",
    "id": 3
}, {
    "name": "user2",
    "id": 6
}, {
    "name": "user3",
    "id": 1
}];

Now you have an array of objects, and we can sort it.

json.sort(function(a, b){
    return a.id - b.id;
});

The resulting array will look like:

[{
    "name": "user3",
    "id" : 1
}, {
    "name": "user1",
    "id" : 3
}, {
    "name": "user2",
    "id" : 6
}];

How to convert / cast long to String?

1.

long date = curDateFld.getDate();
//convert long to string
String str = String.valueOf(date);

//convert string to long
date = Long.valueOf(str);

2.

 //convert long to string just concat long with empty string
 String str = ""+date;
//convert string to long

date = Long.valueOf(str);

Laravel migration table field's type change

The standard solution didn't work for me, when changing the type from TEXT to LONGTEXT.

I had to it like this:

public function up()
{
    DB::statement('ALTER TABLE mytable MODIFY mycolumn  LONGTEXT;');
}

public function down()
{
    DB::statement('ALTER TABLE mytable MODIFY mycolumn TEXT;');
}

This could be a Doctrine issue. More information here.

Another way to do it is to use the string() method, and set the value to the text type max length:

    Schema::table('mytable', function ($table) {
        // Will set the type to LONGTEXT.
        $table->string('mycolumn', 4294967295)->change();
    });

Delete all rows in table

As other have said, TRUNCATE TABLE is far quicker, but it does have some restrictions (taken from here):

You cannot use TRUNCATE TABLE on tables that:

- Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.)
- Participate in an indexed view.
- Are published by using transactional replication or merge replication.

For tables with one or more of these characteristics, use the DELETE statement instead.

The biggest drawback is that if the table you are trying to empty has foreign keys pointing to it, then the truncate call will fail.

Mockito. Verify method arguments

The other method is to use the org.mockito.internal.matchers.Equals.Equals method instead of redefining one :

verify(myMock).myMethod((inputObject)Mockito.argThat(new Equals(inputObjectWanted)));

How to close Browser Tab After Submitting a Form?

That's because the event onsubmit is triggered before the form is submitted.

Remove your onSubmit and output that JavaScript in your PHP script after you have processed the request. You are closing the window right now, and cancelling the request to your server.

Tree implementation in Java (root, parents and children)

import java.util.ArrayList;
import java.util.List;

public class Node<T> {
    private List<Node<T>> children = new ArrayList<Node<T>>();
    private Node<T> parent = null;
    private T data = null;

    public Node(T data) {
        this.data = data;
    }

    public Node(T data, Node<T> parent) {
        this.data = data;
        this.parent = parent;
    }

    public List<Node<T>> getChildren() {
        return children;
    }

    public void setParent(Node<T> parent) {
        parent.addChild(this);
        this.parent = parent;
    }

    public void addChild(T data) {
        Node<T> child = new Node<T>(data);
        child.setParent(this);
        this.children.add(child);
    }

    public void addChild(Node<T> child) {
        child.setParent(this);
        this.children.add(child);
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    public boolean isLeaf() {
        return this.children.size == 0;
    }

    public void removeParent() {
        this.parent = null;
    }
}

Example:

import java.util.List;

Node<String> parentNode = new Node<String>("Parent"); 
Node<String> childNode1 = new Node<String>("Child 1", parentNode);
Node<String> childNode2 = new Node<String>("Child 2");     

childNode2.setParent(parentNode); 

Node<String> grandchildNode = new Node<String>("Grandchild of parentNode. Child of childNode1", childNode1); 
List<Node<String>> childrenNodes = parentNode.getChildren();

SQL Inner Join On Null Values

If you want null values to be included from Y.QID then Fastest way is

SELECT * FROM Y LEFT JOIN X ON y.QID = X.QID

Note: this solution is applicable only if you need null values from Left table i.e. Y (in above case).

Otherwise INNER JOIN x ON x.qid IS NOT DISTINCT FROM y.qid is right way to do

How to get ER model of database from server with Workbench

I want to enhance Mr. Kamran Ali's answer with pictorial view.

Pictorial View is given step by step:

  1. Go to "Database" Menu option
  2. Select the "Reverse Engineer" option.

enter image description here

  1. A wizard will come. Select from "Stored Connection" and press "Next" button.

enter image description here

  1. Then "Next"..to.."Finish"

Enjoy :)

Adding values to specific DataTable cells

If it were a completely new row that you wanted to only set one value, you would need to add the whole row and then set the individual value:

DataRow dr = dt.NewRow();
dr[3].Value = "Some Value";
dt.Rows.Add(dr);

Otherwise, you can find the existing row and set the cell value

DataRow dr = dt.Rows[theRowNumber];
dr[3] = "New Value";

Double decimal formatting in Java

An alternative method is use the setMinimumFractionDigits method from the NumberFormat class.

Here you basically specify how many numbers you want to appear after the decimal point.

So an input of 4.0 would produce 4.00, assuming your specified amount was 2.

But, if your Double input contains more than the amount specified, it will take the minimum amount specified, then add one more digit rounded up/down

For example, 4.15465454 with a minimum amount of 2 specified will produce 4.155

NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
Double myVal = 4.15465454;
System.out.println(nf.format(myVal));

Try it online

How to know/change current directory in Python shell?

If you import os you can use os.getcwd to get the current working directory, and you can use os.chdir to change your directory

Combining two sorted lists in Python

Python's sort implementation "timsort" is specifically optimized for lists that contain ordered sections. Plus, it's written in C.

http://bugs.python.org/file4451/timsort.txt
http://en.wikipedia.org/wiki/Timsort

As people have mentioned, it may call the comparison function more times by some constant factor (but maybe call it more times in a shorter period in many cases!).

I would never rely on this, however. – Daniel Nadasi

I believe the Python developers are committed to keeping timsort, or at least keeping a sort that's O(n) in this case.

Generalized sorting (i.e. leaving apart radix sorts from limited value domains)
cannot be done in less than O(n log n) on a serial machine. – Barry Kelly

Right, sorting in the general case can't be faster than that. But since O() is an upper bound, timsort being O(n log n) on arbitrary input doesn't contradict its being O(n) given sorted(L1) + sorted(L2).

How to create a file in memory for user to download, but not through server?

As mentioned before, filesaver is a great package to work with files on the client side. But, it is not do well with large files. StreamSaver.js is an alternative solution (which is pointed in FileServer.js) that can handle large files:

const fileStream = streamSaver.createWriteStream('filename.txt', size);
const writer = fileStream.getWriter();
for(var i = 0; i < 100; i++){
    var uint8array = new TextEncoder("utf-8").encode("Plain Text");
    writer.write(uint8array);
}
writer.close()

Run local python script on remote server

It is possible using ssh. Python accepts hyphen(-) as argument to execute the standard input,

cat hello.py | ssh [email protected] python -

Run python --help for more info.

Better way to represent array in java properties file

I can suggest using delimiters and using the

String.split(delimiter)

Example properties file:

MON=0800#Something#Something1, Something2

prop.load(new FileInputStream("\\\\Myseccretnetwork\\Project\\props.properties"));
String[]values = prop.get("MON").toString().split("#");

Hope that helps

What is the PostgreSQL equivalent for ISNULL()

Try:

SELECT COALESCE(NULLIF(field, ''), another_field) FROM table_name

Reusing output from last command in Bash

If you are on mac, and don't mind storing your output in the clipboard instead of writing to a variable, you can use pbcopy and pbpaste as a workaround.

For example, instead of doing this to find a file and diff its contents with another file:

$ find app -name 'one.php' 
/var/bar/app/one.php

$ diff /var/bar/app/one.php /var/bar/two.php

You could do this:

$ find app -name 'one.php' | pbcopy
$ diff $(pbpaste) /var/bar/two.php

The string /var/bar/app/one.php is in the clipboard when you run the first command.

By the way, pb in pbcopy and pbpaste stand for pasteboard, a synonym for clipboard.

compression and decompression of string data in java

This is because of

String outStr = obj.toString("UTF-8");

Send the byte[] which you can get from your ByteArrayOutputStream and use it as such in your ByteArrayInputStream to construct your GZIPInputStream. Following are the changes which need to be done in your code.

byte[] compressed = compress(string); //In the main method

public static byte[] compress(String str) throws Exception {
    ...
    ...
    return obj.toByteArray();
}

public static String decompress(byte[] bytes) throws Exception {
    ...
    GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
    ...
}

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

.htaccess rewrite to redirect root URL to subdirectory

You can use a rewrite rule that uses ^$ to represent the root and rewrite that to your /store directory, like this:

RewriteEngine On
RewriteRule ^$ /store [L]

How to get the top 10 values in postgresql?

Note that if there are ties in top 10 values, you will only get the top 10 rows, not the top 10 values with the answers provided. Ex: if the top 5 values are 10, 11, 12, 13, 14, 15 but your data contains 10, 10, 11, 12, 13, 14, 15 you will only get 10, 10, 11, 12, 13, 14 as your top 5 with a LIMIT

Here is a solution which will return more than 10 rows if there are ties but you will get all the rows where some_value_column is technically in the top 10.

select
  *
from
  (select
     *,
     rank() over (order by some_value_column desc) as my_rank
  from mytable) subquery
where my_rank <= 10

Get file path of image on Android

To get the path of all images in android I am using following code

public void allImages() 
{
    ContentResolver cr = getContentResolver();
    Cursor cursor;
    Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Images.Media._ID + " != 0";

    cursor = cr.query(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA));
                Log.i("Image path ", fullpath + "");


            } while (cursor.moveToNext());
        }
        cursor.close();
    }

}

How to generate unique IDs for form labels in React?

I create a uniqueId generator module (Typescript):

const uniqueId = ((): ((prefix: string) => string) => {
  let counter = 0;
  return (prefix: string): string => `${prefix}${++counter}`;
})();

export default uniqueId;

And use top module to generate unique ids:

import React, { FC, ReactElement } from 'react'
import uniqueId from '../../modules/uniqueId';

const Component: FC = (): ReactElement => {
  const [inputId] = useState(uniqueId('input-'));
  return (
    <label htmlFor={inputId}>
      <span>text</span>
      <input id={inputId} type="text" />
    </label>
  );
};     

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings

Update: this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

How to convert password into md5 in jquery?

Fiddle: http://jsfiddle.net/33HMj/

Js:

var md5 = function(value) {
    return CryptoJS.MD5(value).toString();
}

$("input").keyup(function () {
     var value = $(this).val(),
         hash = md5(value);
     $(".test").html(hash);
 });

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

The following code did the trick for me.

html:

<div class="back" onclick="goBackOrGoHome()">
  Back
</div>

js:

home_url = [YOUR BASE URL];

pathArray = document.referrer.split( '/' );
protocol = pathArray[0];
host = pathArray[2];

url_before = protocol + '//' + host;

url_now = window.location.protocol + "//" + window.location.host;


function goBackOrGoHome(){
  if ( url_before == url_now) {
    window.history.back();    
  }else{
    window.location = home_url;
  };
}

So, you use document.referrer to set the domain of the page you come from. Then you compare that with your current url using window.location.

If they are from the same domain, it means you are coming from your own site and you send them window.history.back(). If they are not the same, you are coming from somewhere else and you should redirect home or do whatever you like.

Dynamically updating css in Angular 2

You can also use hostbinding:

import { HostBinding } from '@angular/core';

export class HomeComponent {
    @HostBinding('style.width') width: Number;
    @HostBinding('style.height') height: Number;
} 

Now when you change the width or height property from within the HomeComponent, this should affect the style attributes.

How does `scp` differ from `rsync`?

The major difference between these tools is how they copy files.

scp basically reads the source file and writes it to the destination. It performs a plain linear copy, locally, or over a network.

rsync also copies files locally or over a network. But it employs a special delta transfer algorithm and a few optimizations to make the operation a lot faster. Consider the call.

rsync A host:B
  • rsync will check files sizes and modification timestamps of both A and B, and skip any further processing if they match.

  • If the destination file B already exists, the delta transfer algorithm will make sure only differences between A and B are sent over the wire.

  • rsync will write data to a temporary file T, and then replace the destination file B with T to make the update look "atomic" to processes that might be using B.

Another difference between them concerns invocation. rsync has a plethora of command line options, allowing the user to fine tune its behavior. It supports complex filter rules, runs in batch mode, daemon mode, etc. scp has only a few switches.

In summary, use scp for your day to day tasks. Commands that you type once in a while on your interactive shell. It's simpler to use, and in those cases rsync optimizations won't help much.

For recurring tasks, like cron jobs, use rsync. As mentioned, on multiple invocations it will take advantage of data already transferred, performing very quickly and saving on resources. It is an excellent tool to keep two directories synchronized over a network.

Also, when dealing with large files, use rsync with the -P option. If the transfer is interrupted, you can resume it where it stopped by reissuing the command. See Sid Kshatriya's answer.

In a simple to understand explanation, what is Runnable in Java?

Runnable is an interface defined as so:

interface Runnable {
    public void run();
}

To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {

It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.

If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.

It should also be noted that Threads implement Runnable, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable) without overriding Thread's run method.

Table and Index size in SQL Server

It’s been a long time since the creation of this post, but I wanted to share my script:

WITH CteIndex
AS
(
SELECT 
     reservedpages = (reserved_page_count)
     ,usedpages = (used_page_count)
     ,pages = (
            CASE
                WHEN (s.index_id < 2) THEN (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
                ELSE lob_used_page_count + row_overflow_used_page_count
            END
            )    
     ,s.object_id   
     ,i.index_id        
     ,i.type_desc AS IndexType
     ,i.name AS indexname
    FROM sys.dm_db_partition_stats s
    INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id   
)
SELECT DISTINCT
DB_NAME(DB_ID()) AS DatabaseName
,o.name AS TableName
,o.object_id
,ct.indexname
,ct.IndexType
,ct.index_id
, IndexSpace = LTRIM (STR ((CASE WHEN usedpages > pages THEN CASE WHEN ct.index_id < 2 THEN  pages ELSE (usedpages - pages) END ELSE 0 END) * 8, 15, 0) + ' KB')
FROM CteIndex ct
INNER JOIN sys.objects o ON o.object_id = ct.object_id
INNER JOIN sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL , NULL) ps ON ps.object_id = o.object_id
AND ps.index_id = ct.index_id
ORDER BY name ASC

This works for :

  • SQL Server (starting with 2008)
  • Includes info for all tables per current database

Removing double quotes from variables in batch file creates problems with CMD environment

Your conclusion (1) sounds wrong. There must be some other factor at play.

The problem of quotes in batch file parameters is normally solved by removing the quotes with %~ and then putting them back manually where appropriate.

E.g.:

set cmd=%~1
set params=%~2 %~3

"%cmd%" %params%

Note the quotes around %cmd%. Without them, path with spaces won't work.

If you could post your entire batch code, maybe more specific answer could be made.

jQuery get input value after keypress

This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added.

Note that, if your element #dSuggest is the same as input:text[name=dSuggest] you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id of another element is not a good idea).

$('#dSuggest').keypress(function() {
    var dInput = this.value;
    console.log(dInput);
    $(".dDimension:contains('" + dInput + "')").css("display","block");
});