Programs & Examples On #Wai aria

WAI-ARIA, the Accessible Rich Internet Applications Suite, defines a way to make web content and web applications more accessible to people with disabilities. It especially helps with dynamic content and advanced user interface controls developed with AJAX, HTML, JavaScript, and related technologies.

What are these attributes: `aria-labelledby` and `aria-hidden`

aria-hidden="true" will hide decorative items like glyphicon icons from screen readers, which doesn't have meaningful pronunciation so as not to cause confusions. It's a nice thing do as matter of good practice.

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.

The hidden attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:

https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden

Using these standards can make it easier for disabled people to use the web.

What is HTML5 ARIA?

What is it?

WAI-ARIA stands for “Web Accessibility Initiative – Accessible Rich Internet Applications”. It is a set of attributes to help enhance the semantics of a web site or web application to help assistive technologies, such as screen readers for the blind, make sense of certain things that are not native to HTML. The information exposed can range from something as simple as telling a screen reader that activating a link or button just showed or hid more items, to widgets as complex as whole menu systems or hierarchical tree views.

This is achieved by applying roles and state attributes to HTML 4.01 or later markup that has no bearing on layout or browser functionality, but provides additional information for assistive technologies.

One corner stone of WAI-ARIA is the role attribute. It tells the browser to tell the assistive technology that the HTML element used is not actually what the element name suggests, but something else. While it originally is only a div element, this div element may be the container to a list of auto-complete items, in which case a role of “listbox” would be appropriate to use. Likewise, another div that is a child of that container div, and which contains a single option item, should then get a role of “option”. Two divs, but through the roles, totally different meaning. The roles are modeled after commonly used desktop application counterparts.

An exception to this are document landmark roles, which don’t change the actual meaning of the element in question, but provide information about this particular place in a document.

The second corner stone are WAI-ARIA states and properties. They define the state of certain native or WAI-ARIA elements such as if something is collapsed or expanded, a form element is required, something has a popup menu attached to it or the like. These are often dynamic and change their values throughout the lifecycle of a web application, and are usually manipulated via JavaScript.

What is it not?

WAI-ARIA is not intended to influence browser behavior. Unlike a real button element, for example, a div which you pour the role of “button” onto does not give you keyboard focusability, an automatic click handler when Space or Enter are being pressed on it, and other properties that are indiginous to a button. The browser itself does not know that a div with role of “button” is a button, only its accessibility API portion does.

As a consequence, this means that you absolutely have to implement keyboard navigation, focusability and other behavioural patterns known from desktop applications yourself. You can find some Advanced ARIA techniques Here.

When should I not use it?

Yes, that’s correct, this section comes first! Because the first rule of using WAI-ARIA is: Don’t use it unless you absolutely have to! The less WAI-ARIA you have, and the more you can count on using native HTML widgets, the better! There are some more rules to follow, you can check them out here.

Converting VS2012 Solution to VS2010

Solution of VS2010 is supported by VS2012. Solution of VS2012 isn't supported by VS2010 --> one-way upgrade only. VS2012 doesn't support setup projects. Find here more about VS2010/VS2012 compatibility: http://msdn.microsoft.com/en-us/library/hh266747(v=vs.110).aspx

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

There's a far more simpler solution to tackle this.

The reason why you get ValueError: Index contains duplicate entries, cannot reshape is because, once you unstack "Location", then the remaining index columns "id" and "date" combinations are no longer unique.

You can avoid this by retaining the default index column (row #) and while setting the index using "id", "date" and "location", add it in "append" mode instead of the default overwrite mode.

So use,

e.set_index(['id', 'date', 'location'], append=True)

Once this is done, your index columns will still have the default index along with the set indexes. And unstack will work.

Let me know how it works out.

Cron job every three days

If you want it to run on specific days of the month, like the 1st, 4th, 7th, etc... then you can just have a conditional in your script that checks for the current day of the month.

I thought all you needed for this was instead of */3 which means every three days, use 1/3 which means every three days starting on the 1st of the month. so 7/3 would mean every three days starting on the 7th of the month, etc.

Running Google Maps v2 on the Android emulator

Please try the following. It was successfully for me.

Steps:

  1. Create a new emulator with this configuration: AVD configuration

  2. Start the emulator and install the following APK files: GoogleLoginService.apk, GoogleServicesFramework.apk, and Phonesky.apk. You can do this with the following commands:

    adb shell mount -o remount,yourAvdName -t yaffs2 /dev/block/mtdblock0 /system
    adb shell chmod 777 /system/app
    adb push GoogleLoginService.apk /system/app/
    adb push GoogleServicesFramework.apk /system/app/
    adb push Phonesky.apk /system/app/
    

    Links for APKs:

    1. GoogleLoginService.apk
    2. GoogleServicesFramework.apk
    3. Phonesky.apk AKA Google Play Store, v.3.5.16
    4. Google Maps, v.6.14.1
    5. Google Play services, v.2.0.10
  3. Install Google Play services and Google Maps in the emulator

    adb install com.google.android.apps.maps-1.apk
    adb install com.google.android.gms-2.apk
    
  4. Download Google Play Service revision 4 from this link and extra to folder sdkmanager->extra->google play service.
  5. Import google-play-services_lib from androidsdk\extras\google\google_play_services.
  6. Create a new project and reference the above project as a library project.
  7. Run the project.

How to make the overflow CSS property work with hidden as value

Ok if anyone else is having this problem this may be your answer:

If you are trying to hide absolute positioned elements make sure the container of those absolute positioned elements is relatively positioned.

strdup() - what does it do in C?

char * strdup(const char * s)
{
  size_t len = 1+strlen(s);
  char *p = malloc(len);

  return p ? memcpy(p, s, len) : NULL;
}

Maybe the code is a bit faster than with strcpy() as the \0 char doesn't need to be searched again (It already was with strlen()).

Best way to store passwords in MYSQL database

Passwords in the database should be stored encrypted. One way encryption (hashing) is recommended, such as SHA2, SHA2, WHIRLPOOL, bcrypt DELETED: MD5 or SHA1. (those are older, vulnerable

In addition to that you can use additional per-user generated random string - 'salt':

$salt = MD5($this->createSalt());

$Password = SHA2($postData['Password'] . $salt);

createSalt() in this case is a function that generates a string from random characters.

EDIT: or if you want more security, you can even add 2 salts: $salt1 . $pass . $salt2

Another security measure you can take is user inactivation: after 5 (or any other number) incorrect login attempts user is blocked for x minutes (15 mins lets say). It should minimize success of brute force attacks.

How to calculate an age based on a birthday?

I don't really understand why you would make this an HTML Helper. I would make it part of the ViewData dictionary in an action method of the controller. Something like this:

ViewData["Age"] = DateTime.Now.Year - birthday.Year;

Given that birthday is passed into an action method and is a DateTime object.

What is the Windows equivalent of the diff command?

If you have installed git on your machine, you can open a git terminal and just use the Linux diff command as normal.

How can I record a Video in my Android App.?

For the benefit of searchers, this example will give you an active preview, with a start/stop button for recording. It was modified from this android blog and seems fairly reliable.

java class (VideoWithSurfaceVw)

package <<your packagename here>>;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

public class VideoWithSurfaceVw extends Activity{

    // Adapted from http://sandyandroidtutorials.blogspot.co.uk/2013/05/android-video-capture-tutorial.html


    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;

    Button myButton;
    SurfaceHolder surfaceHolder;
    boolean recording;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recording = false;

        setContentView(R.layout.activity_video_with_surface_vw);

        //Get Camera for preview
        myCamera = getCameraInstance();
        if(myCamera == null){
            Toast.makeText(VideoWithSurfaceVw.this,
                    "Fail to get Camera",
                    Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
        myCameraPreview.addView(myCameraSurfaceView);

        myButton = (Button)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
    }

    Button.OnClickListener myButtonOnClickListener
            = new Button.OnClickListener(){

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

            try{
                if(recording){
                    // stop recording and release camera
                    mediaRecorder.stop();  // stop the recording
                    releaseMediaRecorder(); // release the MediaRecorder object

                    //Exit after saved
                    //finish();
                    myButton.setText("REC");
                    recording = false;
                }else{

                    //Release Camera before MediaRecorder start
                    releaseCamera();

                    if(!prepareMediaRecorder()){
                        Toast.makeText(VideoWithSurfaceVw.this,
                                "Fail in prepareMediaRecorder()!\n - Ended -",
                                Toast.LENGTH_LONG).show();
                        finish();
                    }

                    mediaRecorder.start();
                    recording = true;
                    myButton.setText("STOP");
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }};

    private Camera getCameraInstance(){
        // TODO Auto-generated method stub
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    private String getFileName_CustomFormat() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    }


    private boolean prepareMediaRecorder(){
        myCamera = getCameraInstance();
        mediaRecorder = new MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));



        mediaRecorder.setOutputFile("/sdcard/" + getFileName_CustomFormat() + ".mp4");
        //mediaRecorder.setOutputFile("/sdcard/myvideo1.mp4");
        mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
        mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M

        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder(){
        if (mediaRecorder != null) {
            mediaRecorder.reset();   // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = new MediaRecorder();
            myCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();        // release the camera for other applications
            myCamera = null;
        }
    }

    public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

        private SurfaceHolder mHolder;
        private Camera mCamera;

        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;

            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                                   int height) {
            // If your preview can change or rotate, take care of those events here.
            // Make sure to stop the preview before resizing or reformatting it.

            if (mHolder.getSurface() == null){
                // preview surface does not exist
                return;
            }

            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e){
                // ignore: tried to stop a non-existent preview
            }

            // make any resize, rotate or reformatting changes here

            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            // The Surface has been created, now tell the camera where to draw the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub

        }
    }
}

activity (activity_video_with_surface_vw)

<RelativeLayout android:id="@+id/surface_camera"     
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:layout_weight="1"
>

<RelativeLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <FrameLayout
        android:id="@+id/videoview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
    <Button
        android:id="@+id/mybutton"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:text="REC"
        android:textSize="12dp"/>
</RelativeLayout>

</RelativeLayout>

Why is @font-face throwing a 404 error on woff files?

Also check your URL rewriter. It may throw 404 if something "weird" was found.

What are the applications of binary trees?

I dont think there is any use for "pure" binary trees. (except for educational purposes) Balanced binary trees, such as Red-Black trees or AVL trees are much more useful, because they guarantee O(logn) operations. Normal binary trees may end up being a list (or almost list) and are not really useful in applications using much data.

Balanced trees are often used for implementing maps or sets. They can also be used for sorting in O(nlogn), even tho there exist better ways to do it.

Also for searching/inserting/deleting Hash tables can be used, which usually have better performance than binary search trees (balanced or not).

An application where (balanced) binary search trees would be useful would be if searching/inserting/deleting and sorting would be needed. Sort could be in-place (almost, ignoring the stack space needed for the recursion), given a ready build balanced tree. It still would be O(nlogn) but with a smaller constant factor and no extra space needed (except for the new array, assuming the data has to be put into an array). Hash tables on the other hand can not be sorted (at least not directly).

Maybe they are also useful in some sophisticated algorithms for doing something, but tbh nothing comes to my mind. If i find more i will edit my post.

Other trees like f.e. B+trees are widely used in databases

Entity Framework vs LINQ to SQL

I found a very good answer here which explains when to use what in simple words:

The basic rule of thumb for which framework to use is how to plan on editing your data in your presentation layer.

  • Linq-To-Sql - use this framework if you plan on editing a one-to-one relationship of your data in your presentation layer. Meaning you don't plan on combining data from more than one table in any one view or page.

  • Entity Framework - use this framework if you plan on combining data from more than one table in your view or page. To make this clearer, the above terms are specific to data that will be manipulated in your view or page, not just displayed. This is important to understand.

With the Entity Framework you are able to "merge" tabled data together to present to the presentation layer in an editable form, and then when that form is submitted, EF will know how to update ALL the data from the various tables.

There are probably more accurate reasons to choose EF over L2S, but this would probably be the easiest one to understand. L2S does not have the capability to merge data for view presentation.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

Had the same issue, in my case the cause was that the web.config file was missing in the virtual dir folder.

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

How do I make a JAR from a .java file?

Here is another fancy way of doing this:

$ ls | grep .java | xargs -I {} javac {} ; jar -cf myJar.jar *.class

Which will grab all the .java files ( ls | grep .java ) from your current directory and compile them into .class (xargs -I {} javac {}) and then create the jar file from the previously compiled classes (jar -cf myJar.jar *.class).

Making a div vertically scrollable using CSS

Well the above answers have give a good explanations to half of the question. For the other half.

Why don't just hide the scroll bar itself. This way it will look more appealing as most of the people ( including me ) hate the scroll bar. You can use this code

::-webkit-scrollbar {
    width: 0px;  /* Remove scrollbar space */
    background: transparent;  /* Optional: just make scrollbar invisible */
}

C++ Object Instantiation

There's no reason to new (on the heap) when you can allocate on the stack (unless for some reason you've got a small stack and want to use the heap.

You might want to consider using a shared_ptr (or one of its variants) from the standard library if you do want to allocate on the heap. That'll handle doing the delete for you once all references to the shared_ptr have gone out of existance.

How to make correct date format when writing data to Excel

This worked for me:

hoja_trabajo.Cells[i + 2, j + 1] = fecha.ToString("dd-MMM-yyyy").Replace(".", "");

How to choose the id generation strategy when using JPA and Hibernate

Basically, you have two major choices:

  • You can generate the identifier yourself, in which case you can use an assigned identifier.
  • You can use the @GeneratedValue annotation and Hibernate will assign the identifier for you.

For the generated identifiers you have two options:

  • UUID identifiers.
  • Numerical identifiers.

For numerical identifiers you have three options:

  • IDENTITY
  • SEQUENCE
  • TABLE

IDENTITY is only a good choice when you cannot use SEQUENCE (e.g. MySQL) because it disables JDBC batch updates.

SEQUENCE is the preferred option, especially when used with an identifier optimizer like pooled or pooled-lo.

TABLE is to be avoided since it uses a separate transaction to fetch the identifier and row-level locks which scales poorly.

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

This is how i solve my problem

let parameters = [
            "station_id" :        "1000",
            "title":      "Murat Akdeniz",
            "body":        "xxxxxx"]

let imgData = UIImageJPEGRepresentation(UIImage(named: "1.png")!,1)



    Alamofire.upload(
        multipartFormData: { MultipartFormData in
        //    multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")

            for (key, value) in parameters {
                MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }

        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[1]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[2]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")


    }, to: "http://platform.twitone.com/station/add-feedback") { (result) in

        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in
                print(response.result.value)
            }

        case .failure(let encodingError): break
            print(encodingError)
        }


    }

Determine the process pid listening on a certain port

netstat -p -l | grep $PORT and lsof -i :$PORT solutions are good but I prefer fuser $PORT/tcp extension syntax to POSIX (which work for coreutils) as with pipe:

pid=`fuser $PORT/tcp`

it prints pure pid so you can drop sed magic out.

One thing that makes fuser my lover tools is ability to send signal to that process directly (this syntax is also extension to POSIX):

$ fuser -k $port/tcp       # with SIGKILL
$ fuser -k -15 $port/tcp   # with SIGTERM
$ fuser -k -TERM $port/tcp # with SIGTERM

Also -k is supported by FreeBSD: http://www.freebsd.org/cgi/man.cgi?query=fuser

RecyclerView: Inconsistency detected. Invalid item position

Very late response, but this may help someone on the feature.

Make sure that your onStop or onPause methods aren't clearing any of your lists

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

MongoDB what are the default user and password?

For MongoDB earlier than 2.6, the command to add a root user is addUser (e.g.)

db.addUser({user:'admin',pwd:'<password>',roles:["root"]})

How to name and retrieve a stash by name in git?

Use a small bash script to look up the number of the stash. Call it "gitapply":

NAME="$1"
if [[ -z "$NAME" ]]; then echo "usage: gitapply [name]"; exit; fi
git stash apply $(git stash list | grep "$NAME" | cut -d: -f1)

Usage:

gitapply foo

...where foo is a substring of the name of the stash you want.

What is the most elegant way to check if all values in a boolean array are true?

I can't believe there's no BitSet solution.

A BitSet is an abstraction over a set of bits so we don't have to use boolean[] for more advanced interactions anymore, because it already contains most of the needed methods. It's also pretty fast in batch operations since it internally uses long values to store the bits and doesn't therefore check every bit separately like we do with boolean[].

BitSet myBitSet = new BitSet(10);
// fills the bitset with ten true values
myBitSet.set(0, 10);

For your particular case, I'd use cardinality():

if (myBitSet.cardinality() == myBitSet.size()) {
    // do something, there are no false bits in the bitset
}

Another alternative is using Guava:

return Booleans.contains(myArray, true);

Using CMake with GNU Make: How can I see the exact commands?

I was trying something similar to ensure the -ggdb flag was present.

Call make in a clean directory and grep the flag you are looking for. Looking for debug rather than ggdb I would just write.

make VERBOSE=1 | grep debug

The -ggdb flag was obscure enough that only the compile commands popped up.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Once I found what format it was looking for in the connection string, it worked just fine like this with Oracle.ManagedDataAccess. Without having to mess around with anything separately.

DATA SOURCE=DSDSDS:1521/ORCL;

Set Background color programmatically

I didn't understand your question ... what do you mean by "when i set every one of my colour"? try this (edit: "#fffff" in original answer changed to "#ffffff"

  yourView.setBackgroundColor(Color.parseColor("#ffffff"));

How do I make a relative reference to another workbook in Excel?

In Excel, there is a way to embed relative reference to file or directory. You can try type in excel cell : =HYPERLINK("..\Name_of_file_or_folder\","DisplayLinkName")

How to reload a page using Angularjs?

You can also try this, after injecting $window service.

$window.location.reload();

libpng warning: iCCP: known incorrect sRGB profile

To add to Glenn's great answer, here's what I did to find which files were faulty:

find . -name "*.png" -type f -print0 | xargs \
       -0 pngcrush_1_8_8_w64.exe -n -q > pngError.txt 2>&1

I used the find and xargs because pngcrush could not handle lots of arguments (which were returned by **/*.png). The -print0 and -0 is required to handle file names containing spaces.

Then search in the output for these lines: iCCP: Not recognizing known sRGB profile that has been edited.

./Installer/Images/installer_background.png:    
Total length of data found in critical chunks            =     11286  
pngcrush: iCCP: Not recognizing known sRGB profile that has been edited

And for each of those, run mogrify on it to fix them.

mogrify ./Installer/Images/installer_background.png

Doing this prevents having a commit changing every single png file in the repository when only a few have actually been modified. Plus it has the advantage to show exactly which files were faulty.

I tested this on Windows with a Cygwin console and a zsh shell. Thanks again to Glenn who put most of the above, I'm just adding an answer as it's usually easier to find than comments :)

PHP Converting Integer to Date, reverse of strtotime

I guess you are asking why is 1388516401 equal to 2014-01-01...?

There is an historical reason for that. There is a 32-bit integer variable, called time_t, that keeps the count of the time elapsed since 1970-01-01 00:00:00. Its value expresses time in seconds. This means that in 2014-01-01 00:00:01 time_t will be equal to 1388516401.

This leads us for sure to another interesting fact... In 2038-01-19 03:14:07 time_t will reach 2147485547, the maximum value for a 32-bit number. Ever heard about John Titor and the Year 2038 problem? :D

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

I know this is late to the game, but I wanted to share in case it helps someone.

Your exact situation may not apply, however I had a similar situation and setting the File attribute helped.

Try to set the File attribute to Normal:

var path = Server.MapPath("~/App_Data/file.txt");
File.SetAttributes(path, FileAttributes.Normal);
System.IO.File.WriteAllText(path, "Hello World");

I hope this helps someone.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

After excluding arm64 I always got ARCHS[@]: unbound variable. For me the only solution was to add x86_64 to the target build setting as mentioned here Problems after upgrading to Xcode 12:ld: building for iOS Simulator, but linking in dylib built for iOS, architecture arm64 You also might remove the exclude arm64 you added before.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

How to remove specific elements in a numpy array

There is a numpy built-in function to help with that.

import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])

Drawing an image from a data URL to a canvas

function drawDataURIOnCanvas(strDataURI, canvas) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

Proper way to empty a C-String

I'm a beginner but...Up to my knowledge,the best way is

strncpy(dest_string,"",strlen(dest_string));

Python iterating through object attributes

Iterate over an objects attributes in python:

class C:
    a = 5
    b = [1,2,3]
    def foobar():
        b = "hi"    

for attr, value in C.__dict__.iteritems():
    print "Attribute: " + str(attr or "")
    print "Value: " + str(value or "")

Prints:

python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:

How to write a multidimensional array to a text file?

Use JSON module for multidimensional arrays, e.g.

import json
with open(filename, 'w') as f:
   json.dump(myndarray.tolist(), f)

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You could return an XmlDocument for the ToXML method in your class, then when you are going to add the Element with the result document just use something like:

XmlDocument returnedDocument = Your_Class.ToXML();

XmlDocument finalDocument = new XmlDocument();
XmlElement createdElement = finalDocument.CreateElement("Desired_Element_Name");
createdElement.InnerXML = docResult.InnerXML;
finalDocument.AppendChild(createdElement);

That way the entire value for "Desired_Element_Name" on your result XmlDocument will be the entire content of the returned Document.

I hope this helps.

Scripting SQL Server permissions

Expanding on the answer provided in https://stackoverflow.com/a/1987215/275388 which fails for database/schema wide rights and database user types you can use:

SELECT
  CASE
      WHEN dp.class_desc = 'OBJECT_OR_COLUMN' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON ' + '[' + obj_sch.name + ']' + '.' + '[' + o.name + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'DATABASE' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'SCHEMA' THEN
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' ON SCHEMA :: ' + '[' + SCHEMA_NAME(dp.major_id) + ']' +
        ' TO ' + '[' + dpr.name + ']'
      WHEN dp.class_desc = 'TYPE' THEN
        dp.state_desc + ' ' + dp.permission_name collate Latin1_General_CS_AS + 
        ' ON TYPE :: [' + s_types.name + '].[' + t.name + ']'
            + ' TO [' + dpr.name + ']'
      WHEN dp.class_desc = 'CERTIFICATE' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
        ' TO ' + '[' + dpr.name + ']' 
      WHEN dp.class_desc = 'SYMMETRIC_KEYS' THEN 
        dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as + 
      ' TO ' + '[' + dpr.name + ']' 
      ELSE 
        'ERROR: Unhandled class_desc: ' + dp.class_desc
  END
 AS GRANT_STMT
FROM sys.database_permissions AS dp 
  JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
  LEFT JOIN sys.objects AS o ON dp.major_id=o.object_id
  LEFT JOIN sys.schemas AS obj_sch ON o.schema_id = obj_sch.schema_id
  LEFT JOIN sys.types AS t ON dp.major_id = t.user_type_id
  LEFT JOIN sys.schemas AS s_types ON t.schema_id = s_types.schema_id
WHERE 
dpr.name NOT IN ('public','guest') 
--  AND o.name IN ('My_Procedure')      -- Uncomment to filter to specific object(s)
--  AND (o.name NOT IN ('My_Procedure') or o.name is null)  -- Uncomment to filter out specific object(s), but include rows with no o.name (VIEW DEFINITION etc.)
--  AND dp.permission_name='EXECUTE'    -- Uncomment to filter to just the EXECUTEs
--  AND dpr.name LIKE '%user_name%'     -- Uncomment to filter to just matching users
ORDER BY dpr.name, dp.class_desc, dp.permission_name

Format ints into string of hex

Similar to my other answer, except repeating the format string:

>>> numbers = [1, 15, 255]
>>> fmt = '{:02X}' * len(numbers)
>>> fmt.format(*numbers)
'010FFF'

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

Add android:noHistory="true" in manifest file .

<manifest >
        <activity
            android:name="UI"
            android:noHistory="true"/>

</manifest>

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

How to disable input conditionally in vue.js

You can manipulate :disabled attribute in vue.js.

It will accept a boolean, if it's true, then the input gets disabled, otherwise it will be enabled...

Something like structured like below in your case for example:

<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="validated ? false : true">

Also read this below:

Conditionally Disabling Input Elements via JavaScript Expression

You can conditionally disable input elements inline with a JavaScript expression. This compact approach provides a quick way to apply simple conditional logic. For example, if you only needed to check the length of the password, you may consider doing something like this.

<h3>Change Your Password</h3>
<div class="form-group">
  <label for="newPassword">Please choose a new password</label>
  <input type="password" class="form-control" id="newPassword" placeholder="Password" v-model="newPassword">
</div>

<div class="form-group">
  <label for="confirmPassword">Please confirm your new password</label>
  <input type="password" class="form-control" id="confirmPassword" placeholder="Password" v-model="confirmPassword" v-bind:disabled="newPassword.length === 0 ? true : false">
</div>

How do I get the name of the current executable in C#?

You can use Environment.GetCommandLineArgs() to obtain the arguments and Environment.CommandLine to obtain the actual command line as entered.

Also, you can use Assembly.GetEntryAssembly() or Process.GetCurrentProcess().

However, when debugging, you should be careful as this final example may give your debugger's executable name (depending on how you attach the debugger) rather than your executable, as may the other examples.

Convert an array to string

You can join your array using the following:

string.Join(",", Client);

Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.

In Java, can you modify a List while iterating through it?

Java 8's stream() interface provides a great way to update a list in place.

To safely update items in the list, use map():

List<String> letters = new ArrayList<>();

// add stuff to list

letters = letters.stream().map(x -> "D").collect(Collectors.toList());

To safely remove items in place, use filter():


letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());

Find a file by name in Visual Studio Code

I believe the action name is "workbench.action.quickOpen".

The declared package does not match the expected package ""

Make sure that You have created a correct package.You might get a chance to create folder instead of package

Removing spaces from string

I also had this problem. To sort out the problem of spaces in the middle of the string this line of code always works:

String field = field.replaceAll("\\s+", "");

Spring Boot Rest Controller how to return different HTTP status codes?

Try this code:

@RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(@QueryParam("jsonInput") final String jsonInput) {
    int numberHTTPDesired = 400;
    ErrorBean responseBean = new ErrorBean();
    responseBean.setError("ERROR");
    responseBean.setMensaje("Error in validation!");

    return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}

When should an Excel VBA variable be killed or set to Nothing?

I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:

Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)

When UserForm was destroyed (after Unload Me) the memory allocated for the data loaded in the mainPicture was not being de-allocated. I had to add an explicit

mainPicture = Nothing

in the terminate event.

How to match "any character" in regular expression?

Specific Solution to the example problem:-

Try [A-Z]*123$ will match 123, AAA123, ASDFRRF123. In case you need at least a character before 123 use [A-Z]+123$.

General Solution to the question (How to match "any character" in the regular expression):

  1. If you are looking for anything including whitespace you can try [\w|\W]{min_char_to_match,}.
  2. If you are trying to match anything except whitespace you can try [\S]{min_char_to_match,}.

Pandas convert dataframe to array of tuples

How about:

subset = data_set[['data_date', 'data_1', 'data_2']]
tuples = [tuple(x) for x in subset.to_numpy()]

for pandas < 0.24 use

tuples = [tuple(x) for x in subset.values]

Git copy file preserving history

This process preserve history, but is little workarround:

# make branchs to new files
$: git mv arquivos && git commit

# in original branch, remove original files
$: git rm arquivos && git commit

# do merge and fix conflicts
$: git merge branch-copia-arquivos

# back to original branch and revert commit removing files
$: git revert commit

Make an image follow mouse pointer

by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.

example as below http://jsfiddle.net/BfLAh/1/

_x000D_
_x000D_
$(document).mousemove(function(e) {
  $("#follow").css({
    left: e.pageX,
    top: e.pageY
  });
});
_x000D_
#follow {
  position: absolute;
  text-align: center;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
_x000D_
_x000D_
_x000D_

updated to follow slowly

http://jsfiddle.net/BfLAh/3/

for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with

-webkit-transform: rotate(-90deg); 
-moz-transform: rotate(-90deg); 

for the speed , you can set the jquery .animation duration to certain amount.

Is there a macro to conditionally copy rows to another worksheet?

This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.

You may want to add logic to sort your monthly data after it's all been copied

Public Sub MoveData(MonthNumber As Integer, SheetName As String)

Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range

Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
    If Format(cell.Value, "MM") = MonthNumber Then
        copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
    End If
Next cell

End Sub

Sub copyRowTo(rng As Range, ws As Worksheet)
    Dim newRange As Range
    Set newRange = ws.Range("A1")
    If newRange.Offset(1).Value <> "" Then
        Set newRange = newRange.End(xlDown).Offset(1)
        Else
        Set newRange = newRange.Offset(1)
    End If
    rng.Copy
    newRange.PasteSpecial (xlPasteAll)
End Sub

How do you round UP a number in Python?

I'm basically a beginner at Python, but if you're just trying to round up instead of down why not do:

round(integer) + 1

Npm install failed with "cannot run in wd"

I have experienced the same problem when trying to publish my nodejs app in a private server running CentOs using root user. The same error is fired by "postinstall": "./node_modules/bower/bin/bower install" in my package.json file so the only solution that was working for me is to use both options to avoid the error:

1: use --allow-root option for bower install command

"postinstall": "./node_modules/bower/bin/bower --allow-root install"

2: use --unsafe-perm option for npm install command

npm install --unsafe-perm

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

Check filenames.
You might need to create a new database in phpmyadmin that matches the database you're trying to import.

How to add 10 days to current time in Rails

Use

Time.now + 10.days

or even

10.days.from_now

Both definitely work. Are you sure you're in Rails and not just Ruby?

If you definitely are in Rails, where are you trying to run this from? Note that Active Support has to be loaded.

vi/vim editor, copy a block (not usual action)

just use V to select lines or v to select chars or Ctrlv to select a block.

When the selection spans the area you'd like to copy just hit y and use p to paste it anywhere you like...

Getting multiple keys of specified value of a generic Dictionary?

Can't you create a subclass of Dictionary which has that functionality?


    public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
    {
        private Dictionary < TValue, TKey > _keys;

        public TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set 
            { 
                base[key] = value;
                _keys[value] = key;
            }
        }

        public MyDict()
        {
            _keys = new Dictionary < TValue, TKey >();
        }

        public TKey GetKeyFromValue(TValue value)
        {
            return _keys[value];
        }
    }

EDIT: Sorry, didn't get code right first time.

Setting up a cron job in Windows

The windows equivalent to a cron job is a scheduled task.

A scheduled task can be created as described by Alex and Rudu, but it can also be done command line with schtasks (if you for instance need to script it or add it to version control).

An example:

schtasks /create /tn calculate /tr calc /sc weekly /d MON /st 06:05 /ru "System"

Creates the task calculate, which starts the calculator(calc) every monday at 6:05 (should you ever need that.)

All available commands can be found here: http://technet.microsoft.com/en-us/library/cc772785%28WS.10%29.aspx

It works on windows server 2008 as well as windows server 2003.

How to set .net Framework 4.5 version in IIS 7 application pool

There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:

appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5

Appcmd is located in %windir%\System32\inetsrv. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.

MS article on setting .Net version for App Pool

Difference between CR LF, LF and CR line break types?

Since there's no answer stating just this, summarized succinctly:

Carriage Return (MAC pre-OSX)

  • CR
  • \r
  • ASCII code 13

Line Feed (Linux, MAC OSX)

  • LF
  • \n
  • ASCII code 10

Carriage Return and Line Feed (Windows)

  • CRLF
  • \r\n
  • ASCII code 13 and then ASCII code 10

If you see ASCII code in a strange format, they are merely the number 13 and 10 in a different radix/base, usually base 8 (octal) or base 16 (hexadecimal).

http://www.bluesock.org/~willg/dev/ascii.html

Why can't I initialize non-const static member or static array in class?

I think it's to prevent you from mixing declarations and definitions. (Think about the problems that could occur if you include the file in multiple places.)

Access item in a list of lists

You can use itertools.cycle:

>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0])   # lis[0] is [10,13,17]
36

Here the generator expression inside sum would return something like this:

>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]

You can also use zip here:

>>> cyc = cycle((-1, 1))
>>> [x*y for x, y  in zip(lis[0], cyc)]
[-10, 13, -17]

How do I limit the number of returned items?

models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
 // `posts` with sorted length of 20
});

Disable Tensorflow debugging information

2.0 Update (10/8/19) Setting TF_CPP_MIN_LOG_LEVEL should still work (see below in v0.12+ update), but there is currently an issue open (see issue #31870). If setting TF_CPP_MIN_LOG_LEVEL does not work for you (again, see below), try doing the following to set the log level:

import tensorflow as tf
tf.get_logger().setLevel('INFO')

In addition, please see the documentation on tf.autograph.set_verbosity which sets the verbosity of autograph log messages - for example:

# Can also be set using the AUTOGRAPH_VERBOSITY environment variable
tf.autograph.set_verbosity(1)

v0.12+ Update (5/20/17), Working through TF 2.0+:

In TensorFlow 0.12+, per this issue, you can now control logging via the environmental variable called TF_CPP_MIN_LOG_LEVEL; it defaults to 0 (all logs shown) but can be set to one of the following values under the Level column.

  Level | Level for Humans | Level Description                  
 -------|------------------|------------------------------------ 
  0     | DEBUG            | [Default] Print all messages       
  1     | INFO             | Filter out INFO messages           
  2     | WARNING          | Filter out INFO & WARNING messages 
  3     | ERROR            | Filter out all messages      

See the following generic OS example using Python:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
import tensorflow as tf

You can set this environmental variable in the environment that you run your script in. For example, with bash this can be in the file ~/.bashrc, /etc/environment, /etc/profile, or in the actual shell as:

TF_CPP_MIN_LOG_LEVEL=2 python my_tf_script.py

To be thorough, you call also set the level for the Python tf_logging module, which is used in e.g. summary ops, tensorboard, various estimators, etc.

# append to lines above
tf.logging.set_verbosity(tf.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

For 1.14 you will receive warnings if you do not change to use the v1 API as follows:

# append to lines above
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

**For Prior Versions of TensorFlow or TF-Learn Logging (v0.11.x or lower):**

View the page below for information on TensorFlow logging; with the new update, you're able to set the logging verbosity to either DEBUG, INFO, WARN, ERROR, or FATAL. For example:

tf.logging.set_verbosity(tf.logging.ERROR)

The page additionally goes over monitors which can be used with TF-Learn models. Here is the page.

This doesn't block all logging, though (only TF-Learn). I have two solutions; one is a 'technically correct' solution (Linux) and the other involves rebuilding TensorFlow.

script -c 'python [FILENAME].py' | grep -v 'I tensorflow/'

For the other, please see this answer which involves modifying source and rebuilding TensorFlow.

Regex for allowing alphanumeric,-,_ and space

var string = 'test- _ 0Test';
string.match(/^[-_ a-zA-Z0-9]+$/)

Get current value when change select option - Angular2

For me, passing ($event.target.value) as suggested by @microniks did not work. What worked was ($event.value) instead. I am using Angular 4.2.x and Angular Material 2

<select (change)="onItemChange($event.value)">
    <option *ngFor="#value of values" [value]="value.key">
       {{value.value}}
    </option>
</select>

Is it possible to have empty RequestParam values use the defaultValue?

You can also do something like this -

 @RequestParam(value= "i", defaultValue = "20") Optional<Integer> i

How to Query Database Name in Oracle SQL Developer?

I know this is an old thread but you can also get some useful info from the V$INSTANCE view as well. the V$DATABASE displays info from the control file, the V$INSTANCE view displays state of the current instance.

How do I trap ctrl-c (SIGINT) in a C# console app

This question is very similar to:

Capture console exit C#

Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.

namespace CancelSample
{
    using System;
    using System.Threading;
    using System.Runtime.InteropServices;

    internal class Program
    {
        /// <summary>
        /// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process
        /// </summary>
        /// <param name="handler">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>
        /// <param name="add">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);

        /// <summary>
        /// The console close handler delegate.
        /// </summary>
        /// <param name="closeReason">
        /// The close reason.
        /// </param>
        /// <returns>
        /// True if cleanup is complete, false to run other registered close handlers.
        /// </returns>
        private delegate bool ConsoleCloseHandler(int closeReason);

        /// <summary>
        ///  Event set when the process is terminated.
        /// </summary>
        private static readonly ManualResetEvent TerminationRequestedEvent;

        /// <summary>
        /// Event set when the process terminates.
        /// </summary>
        private static readonly ManualResetEvent TerminationCompletedEvent;

        /// <summary>
        /// Static constructor
        /// </summary>
        static Program()
        {
            // Do this initialization here to avoid polluting Main() with it
            // also this is a great place to initialize multiple static
            // variables.
            TerminationRequestedEvent = new ManualResetEvent(false);
            TerminationCompletedEvent = new ManualResetEvent(false);
            SetConsoleCtrlHandler(OnConsoleCloseEvent, true);
        }

        /// <summary>
        /// The main console entry point.
        /// </summary>
        /// <param name="args">The commandline arguments.</param>
        private static void Main(string[] args)
        {
            // Wait for the termination event
            while (!TerminationRequestedEvent.WaitOne(0))
            {
                // Something to do while waiting
                Console.WriteLine("Work");
            }

            // Sleep until termination
            TerminationRequestedEvent.WaitOne();

            // Print a message which represents the operation
            Console.WriteLine("Cleanup");

            // Set this to terminate immediately (if not set, the OS will
            // eventually kill the process)
            TerminationCompletedEvent.Set();
        }

        /// <summary>
        /// Method called when the user presses Ctrl-C
        /// </summary>
        /// <param name="reason">The close reason</param>
        private static bool OnConsoleCloseEvent(int reason)
        {
            // Signal termination
            TerminationRequestedEvent.Set();

            // Wait for cleanup
            TerminationCompletedEvent.WaitOne();

            // Don't run other handlers, just exit.
            return true;
        }
    }
}

What are the basic rules and idioms for operator overloading?

The Three Basic Rules of Operator Overloading in C++

When it comes to operator overloading in C++, there are three basic rules you should follow. As with all such rules, there are indeed exceptions. Sometimes people have deviated from them and the outcome was not bad code, but such positive deviations are few and far between. At the very least, 99 out of 100 such deviations I have seen were unjustified. However, it might just as well have been 999 out of 1000. So you’d better stick to the following rules.

  1. Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded. Instead, provide a function with a well-chosen name.
    Basically, the first and foremost rule for overloading operators, at its very heart, says: Don’t do it. That might seem strange, because there is a lot to be known about operator overloading and so a lot of articles, book chapters, and other texts deal with all this. But despite this seemingly obvious evidence, there are only a surprisingly few cases where operator overloading is appropriate. The reason is that actually it is hard to understand the semantics behind the application of an operator unless the use of the operator in the application domain is well known and undisputed. Contrary to popular belief, this is hardly ever the case.

  2. Always stick to the operator’s well-known semantics.
    C++ poses no limitations on the semantics of overloaded operators. Your compiler will happily accept code that implements the binary + operator to subtract from its right operand. However, the users of such an operator would never suspect the expression a + b to subtract a from b. Of course, this supposes that the semantics of the operator in the application domain is undisputed.

  3. Always provide all out of a set of related operations.
    Operators are related to each other and to other operations. If your type supports a + b, users will expect to be able to call a += b, too. If it supports prefix increment ++a, they will expect a++ to work as well. If they can check whether a < b, they will most certainly expect to also to be able to check whether a > b. If they can copy-construct your type, they expect assignment to work as well.


Continue to The Decision between Member and Non-member.

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

Change/Get check state of CheckBox

I know this is late info, but in jQuery, using .checked is possible and easy! If your element is something like:

<td>
    <input type="radio" name="bob" />
</td>

You can easily get/set checked state as such:

$("td").each(function()
{
    $(this).click(function()
    {
        var thisInput  = $(this).find("input[type=radio]");
        var checked = thisInput.is(":checked");
        thisInput[0].checked = (checked) ?  false : true;
    }
});

The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object! ENJOY!

Set variable with multiple values and use IN

You need a table variable:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

find if an integer exists in a list of integers

The best of code and complete is here:

NumbersList.Exists(p => p.Equals(Input)

Use:

List<int> NumbersList = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
    int Input = Convert.ToInt32(textBox1.Text);
    if (!NumbersList.Exists(p => p.Equals(Input)))
    {
       NumbersList.Add(Input);
    }
    else
    {
        MessageBox.Show("The number entered is in the list","Error");
    }
}

How to get index of object by its property in JavaScript?

If you're fine with using ES6. Arrays now have the findIndex function. Which means you can do something like this:

const index = Data.findIndex(item => item.name === 'John');

Pure css close button

I become frustrated trying to implement something that looked consistent in all browsers and went with an svg button which can be styled with css.

html

<svg>
    <circle cx="12" cy="12" r="11" stroke="black" stroke-width="2" fill="white" />
    <path stroke="black" stroke-width="4" fill="none" d="M6.25,6.25,17.75,17.75" />
    <path stroke="black" stroke-width="4" fill="none" d="M6.25,17.75,17.75,6.25" />
</svg>

css

svg {
    cursor: pointer;
    height: 24px;
    width: 24px;
}
svg > circle {
    stroke: black;
    fill: white;
}
svg > path {
    stroke: black;
}
svg:hover > circle {
    fill: red;
}
svg:hover > path {
    stroke: white;
}

http://jsfiddle.net/purves/5exav2m7/

How to get the absolute path to the public_html folder?

Whenever you want any sort of configuration information you can use phpinfo().

Clear android application user data

The command pm clear com.android.browser requires root permission.
So, run su first.

Here is the sample code:

private static final String CHARSET_NAME = "UTF-8";
String cmd = "pm clear com.android.browser";

ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true).command("su");
Process p = pb.start();

// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(), CHARSET_NAME);
stdoutReader.start();

out = p.getOutputStream();
out.write((cmd + "\n").getBytes(CHARSET_NAME));
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
out.flush();

p.waitFor();
String result = stdoutReader.getResult();

The class StreamReader:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;

class StreamReader extends Thread {
    private InputStream is;
    private StringBuffer mBuffer;
    private String mCharset;
    private CountDownLatch mCountDownLatch;

    StreamReader(InputStream is, String charset) {
        this.is = is;
        mCharset = charset;
        mBuffer = new StringBuffer("");
        mCountDownLatch = new CountDownLatch(1);
    }

    String getResult() {
        try {
            mCountDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return mBuffer.toString();
    }

    @Override
    public void run() {
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(is, mCharset);
            int c = -1;
            while ((c = isr.read()) != -1) {
                mBuffer.append((char) c);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null)
                    isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mCountDownLatch.countDown();
        }
    }
}

Where IN clause in LINQ

This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.

Problem:

Let say we have document table. Schema as follows schema : document(name,version,auther,modifieddate) composite Keys : name,version

So we need to get latest versions of all documents.

soloution

 var result = (from t in Context.document
                          where ((from tt in Context.document where t.Name == tt.Name
                                orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
                          select t).ToList();

Get all unique values in a JavaScript array (remove duplicates)

You don't need .indexOf() at all; you can do this O(n):

function SelectDistinct(array) {
    const seenIt = new Set();

    return array.filter(function (val) {
        if (seenIt.has(val)) { 
            return false;
        }

        seenIt.add(val);

        return true;
    });
}

var hasDuplicates = [1,2,3,4,5,5,6,7,7];
console.log(SelectDistinct(hasDuplicates)) //[1,2,3,4,5,6,7]

If you don't want to use .filter():

function SelectDistinct(array) {
    const seenIt = new Set();
    const distinct = [];

    for (let i = 0; i < array.length; i++) {
        const value = array[i];

        if (!seenIt.has(value)) {
            seenIt.add(value);
            distinct.push(value);
        }
    }
    
    return distinct; 
    /* you could also drop the 'distinct' array and return 'Array.from(seenIt)', which converts the set object to an array */
}

Differences between "java -cp" and "java -jar"?

java -cp CLASSPATH is necesssary if you wish to specify all code in the classpath. This is useful for debugging code.

The jarred executable format: java -jar JarFile can be used if you wish to start the app with a single short command. You can specify additional dependent jar files in your MANIFEST using space separated jars in a Class-Path entry, e.g.:

Class-Path: mysql.jar infobus.jar acme/beans.jar

Both are comparable in terms of performance.

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Uninstall your application from the emulator or device. Run the app again. (OnCreate() is not executed when the database already exists)

What is the OAuth 2.0 Bearer Token exactly?

Please read the example in rfc6749 sec 7.1 first.

The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.

PoP means kind of multi-factor authentication to make access token more secure. ref

Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).

Maybe it's not the case, but I would say,

  • access token = payment methods
  • bearer token = cash
  • access token with PoP mechanism = credit card (signature or password will be verified, sometimes need to show your ID to match the name on the card)

BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.

What is the default initialization of an array in Java?

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character '\u0000' (whose decimal equivalent is 0).

When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

Python requests - print entire http request (raw)?

Here is a code, which makes the same, but with response headers:

import socket
def patch_requests():
    old_readline = socket._fileobject.readline
    if not hasattr(old_readline, 'patched'):
        def new_readline(self, size=-1):
            res = old_readline(self, size)
            print res,
            return res
        new_readline.patched = True
        socket._fileobject.readline = new_readline
patch_requests()

I spent a lot of time searching for this, so I'm leaving it here, if someone needs.

How can I generate an MD5 hash?

import java.security.MessageDigest

val digest = MessageDigest.getInstance("MD5")

//Quick MD5 of text
val text = "MD5 this text!"
val md5hash1 = digest.digest(text.getBytes).map("%02x".format(_)).mkString

//MD5 of text with updates
digest.update("MD5 ".getBytes())
digest.update("this ".getBytes())
digest.update("text!".getBytes())
val md5hash2 = digest.digest().map(0xFF & _).map("%02x".format(_)).mkString

//Output
println(md5hash1 + " should be the same as " + md5hash2)

How to load an ImageView by URL in Android?

You'll have to download the image firstly

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

Then use the Imageview.setImageBitmap to set bitmap into the ImageView

MongoDB: Is it possible to make a case-insensitive query?

Using a filter works for me in C#.

string s = "searchTerm";
    var filter = Builders<Model>.Filter.Where(p => p.Title.ToLower().Contains(s.ToLower()));
                var listSorted = collection.Find(filter).ToList();
                var list = collection.Find(filter).ToList();

It may even use the index because I believe the methods are called after the return happens but I haven't tested this out yet.

This also avoids a problem of

var filter = Builders<Model>.Filter.Eq(p => p.Title.ToLower(), s.ToLower());

that mongodb will think p.Title.ToLower() is a property and won't map properly.

Eclipse error ... cannot be resolved to a type

To solve the error "...cannot be resolved to a type.." do the followings:

  1. Right click on the class and select "Build Path-->Exclude"
  2. Again right click on the class and select "Build Path-->Include"

It works for me.

How do I set hostname in docker-compose?

I needed to spin freeipa container to have a working kdc and had to give it a hostname otherwise it wouldn't run. What eventually did work for me is setting the HOSTNAME env variable in compose:

version: 2
services:
  freeipa:
    environment:
      - HOSTNAME=ipa.example.test

Now its working:

docker exec -it freeipa_freeipa_1 hostname
ipa.example.test

How can I count occurrences with groupBy?

Here are slightly different options to accomplish the task at hand.

using toMap:

list.stream()
    .collect(Collectors.toMap(Function.identity(), e -> 1, Math::addExact));

using Map::merge:

Map<String, Integer> accumulator = new HashMap<>();
list.forEach(s -> accumulator.merge(s, 1, Math::addExact));

How do you cast a List of supertypes to a List of subtypes?

Since this is a widely referenced question, and the current answers mainly explain why it does not work (or propose hacky, dangerous solutions that I would never ever like to see in production code), I think it is appropriate to add another answer, showing the pitfalls, and a possible solution.


The reason why this does not work in general has already been pointed out in other answers: Whether or not the conversion is actually valid depends on the types of the objects that are contained in the original list. When there are objects in the list whose type is not of type TestB, but of a different subclass of TestA, then the cast is not valid.


Of course, the casts may be valid. You sometimes have information about the types that is not available for the compiler. In these cases, it is possible to cast the lists, but in general, it is not recommended:

One could either...

  • ... cast the whole list or
  • ... cast all elements of the list

The implications of the first approach (which corresponds to the currently accepted answer) are subtle. It might seem to work properly at the first glance. But if there are wrong types in the input list, then a ClassCastException will be thrown, maybe at a completely different location in the code, and it may be hard to debug this and to find out where the wrong element slipped into the list. The worst problem is that someone might even add the invalid elements after the list has been casted, making debugging even more difficult.

The problem of debugging these spurious ClassCastExceptions can be alleviated with the Collections#checkedCollection family of methods.


Filtering the list based on the type

A more type-safe way of converting from a List<Supertype> to a List<Subtype> is to actually filter the list, and create a new list that contains only elements that have certain type. There are some degrees of freedom for the implementation of such a method (e.g. regarding the treatment of null entries), but one possible implementation may look like this:

/**
 * Filter the given list, and create a new list that only contains
 * the elements that are (subtypes) of the class c
 * 
 * @param listA The input list
 * @param c The class to filter for
 * @return The filtered list
 */
private static <T> List<T> filter(List<?> listA, Class<T> c)
{
    List<T> listB = new ArrayList<T>();
    for (Object a : listA)
    {
        if (c.isInstance(a))
        {
            listB.add(c.cast(a));
        }
    }
    return listB;
}

This method can be used in order to filter arbitrary lists (not only with a given Subtype-Supertype relationship regarding the type parameters), as in this example:

// A list of type "List<Number>" that actually 
// contains Integer, Double and Float values
List<Number> mixedNumbers = 
    new ArrayList<Number>(Arrays.asList(12, 3.4, 5.6f, 78));

// Filter the list, and create a list that contains
// only the Integer values:
List<Integer> integers = filter(mixedNumbers, Integer.class);

System.out.println(integers); // Prints [12, 78]

Jaxb, Class has two properties of the same name

ModeleREP#getTimeSeries() have to be with @Transient annotation. That would help.

Add Favicon with React and Webpack

This worked for me:

Add this in index.html (inside src folder along with favicon.ico)

**<link rel="icon" href="/src/favicon.ico" type="image/x-icon" />**

webpack.config.js is like:

 plugins: [new HtmlWebpackPlugin({`enter code here`
        template: './src/index.html'
    })],

How to use the unsigned Integer in Java 8 and Java 9?

    // Java 8
    int vInt = Integer.parseUnsignedInt("4294967295");
    System.out.println(vInt); // -1
    String sInt = Integer.toUnsignedString(vInt);
    System.out.println(sInt); // 4294967295

    long vLong = Long.parseUnsignedLong("18446744073709551615");
    System.out.println(vLong); // -1
    String sLong = Long.toUnsignedString(vLong);
    System.out.println(sLong); // 18446744073709551615

    // Guava 18.0
    int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
    System.out.println(vIntGu); // -1
    String sIntGu = UnsignedInts.toString(vIntGu);
    System.out.println(sIntGu); // 4294967295

    long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
    System.out.println(vLongGu); // -1
    String sLongGu = UnsignedLongs.toString(vLongGu);
    System.out.println(sLongGu); // 18446744073709551615

    /**
     Integer - Max range
     Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
     Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1

     Long - Max range
     Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
     Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
     */

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

What does "pending" mean for request in Chrome Developer Window?

In my case, there's an update for Chrome that makes it won't load before you restart the browser. Cheers

Refresh (reload) a page once using jQuery?

Alright, I think I got what you're asking for. Try this

if(window.top==window) {
    // You're not in a frame, so you reload the site.
    window.setTimeout('location.reload()', 3000); //Reloads after three seconds
}
else {
    //You're inside a frame, so you stop reloading.
}

If it is once, then just do

$('#div-id').triggerevent(function(){
    $('#div-id').html(newContent);
});

If it is periodically

function updateDiv(){
    //Get new content through Ajax
    ...
    $('#div-id').html(newContent);
}

setInterval(updateDiv, 5000); // That's five seconds

So, every five seconds the div #div-id content will refresh. Better than refreshing the whole page.

How can I call a WordPress shortcode within a template?

echo do_shortcode('[CONTACT-US-FORM]');

Use this in your template.

Look here for more: Do Shortcode

Error while trying to run project: Unable to start program. Cannot find the file specified

Deleting and restoring the entire solution from the repository resolved the issue for me. I didn't find this solution listed in any of the other answers, so thought it might help someone.

Can I nest a <button> element inside an <a> using HTML5?

It would be really weird if that was valid, and I would expect it to be invalid. What should it mean to have one clickable element inside of another clickable element? Which is it -- a button, or a link?

How to change values in a tuple?

EDIT: This doesn't work on tuples with duplicate entries yet!!

Based on Pooya's idea:

If you are planning on doing this often (which you shouldn't since tuples are inmutable for a reason) you should do something like this:

def modTupByIndex(tup, index, ins):
    return tuple(tup[0:index]) + (ins,) + tuple(tup[index+1:])

print modTupByIndex((1,2,3),2,"a")

Or based on Jon's idea:

def modTupByIndex(tup, index, ins):
    lst = list(tup)
    lst[index] = ins
    return tuple(lst)

print modTupByIndex((1,2,3),1,"a")

How to get browser width using JavaScript code?

Here is a shorter version of the function presented above:

function getWidth() {
    if (self.innerWidth) {
       return self.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientHeight){
        return document.documentElement.clientWidth;
    }
    else if (document.body) {
        return document.body.clientWidth;
    }
    return 0;
}

CSS: Set Div height to 100% - Pixels

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Mercurial: how to amend the last commit?

Recent versions of Mercurial include the evolve extension which provides the hg amend command. This allows amending a commit without losing the pre-amend history in your version control.

hg amend [OPTION]... [FILE]...

aliases: refresh

combine a changeset with updates and replace it with a new one

Commits a new changeset incorporating both the changes to the given files
and all the changes from the current parent changeset into the repository.

See 'hg commit' for details about committing changes.

If you don't specify -m, the parent's message will be reused.

Behind the scenes, Mercurial first commits the update as a regular child
of the current parent. Then it creates a new commit on the parent's
parents with the updated contents. Then it changes the working copy parent
to this new combined changeset. Finally, the old changeset and its update
are hidden from 'hg log' (unless you use --hidden with log).

See https://www.mercurial-scm.org/doc/evolution/user-guide.html#example-3-amend-a-changeset-with-evolve for a complete description of the evolve extension.

How to view the list of compile errors in IntelliJ?

You should disable Power Save Mode

For me I clicked over this button

enter image description here

then disable Power Save Mode

Good examples of python-memcache (memcached) being used in Python?

A good rule of thumb: use the built-in help system in Python. Example below...

jdoe@server:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)

------------------------------------------
NAME
    memcache - client module for memcached (memory cache daemon)

FILE
    /usr/lib/python2.7/dist-packages/memcache.py

MODULE DOCS
    http://docs.python.org/library/memcache

DESCRIPTION
    Overview
    ========

    See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

    Usage summary
    =============
...
------------------------------------------

SQLAlchemy: how to filter date field?

from app import SQLAlchemyDB as db

Chance.query.filter(Chance.repo_id==repo_id, 
                    Chance.status=="1", 
                    db.func.date(Chance.apply_time)<=end, 
                    db.func.date(Chance.apply_time)>=start).count()

it is equal to:

select
   count(id)
from
   Chance
where
   repo_id=:repo_id 
   and status='1'
   and date(apple_time) <= end
   and date(apple_time) >= start

wish can help you.

IIS URL Rewrite and Web.config

1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRewrite" stopProcessing="true">
                <match url="^page$" />
                <action type="Rewrite" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="DynamicRewrite" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                </conditions>
                <action type="Rewrite" url="/{R:1}.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

How to set Sqlite3 to be case insensitive when string comparing?

Another option is to create your own custom collation. You can then set that collation on the column or add it to your select clauses. It will be used for ordering and comparisons.

This can be used to make 'VOILA' LIKE 'voilà'.

http://www.sqlite.org/capi3ref.html#sqlite3_create_collation

The collating function must return an integer that is negative, zero, or positive if the first string is less than, equal to, or greater than the second, respectively.

How to identify object types in java

Use value instanceof YourClass

Load CSV data into MySQL in Python

Fastest way is to use MySQL bulk loader by "load data infile" statement. It is the fastest way by far than any way you can come up with in Python. If you have to use Python, you can call statement "load data infile" from Python itself.

Inserting a blank table row with a smaller height

I know this question already has an answer, but I found out an even simpler way of doing this.

Just add

<tr height = 20px></tr>

Into the table where you want to have an empty row. It works fine in my program and it's probably the quickest solution possible.

How do I lock the orientation to portrait mode in a iPhone Web Application?

I have a similar issue, but to make landscape... I believe the code below should do the trick:

_x000D_
_x000D_
//This code consider you are using the fullscreen portrait mode_x000D_
function processOrientation(forceOrientation) {_x000D_
  var orientation = window.orientation;_x000D_
  if (forceOrientation != undefined)_x000D_
    orientation = forceOrientation;_x000D_
  var domElement = document.getElementById('fullscreen-element-div');_x000D_
  switch(orientation) {_x000D_
    case 90:_x000D_
      var width = window.innerHeight;_x000D_
      var height = window.innerWidth;_x000D_
      domElement.style.width = "100vh";_x000D_
      domElement.style.height = "100vw";_x000D_
      domElement.style.transformOrigin="50% 50%";_x000D_
      domElement.style.transform="translate("+(window.innerWidth/2-width/2)+"px, "+(window.innerHeight/2-height/2)+"px) rotate(-90deg)";_x000D_
      break;_x000D_
    case -90:_x000D_
      var width = window.innerHeight;_x000D_
      var height = window.innerWidth;_x000D_
      domElement.style.width = "100vh";_x000D_
      domElement.style.height = "100vw";_x000D_
      domElement.style.transformOrigin="50% 50%";_x000D_
      domElement.style.transform="translate("+(window.innerWidth/2-width/2)+"px, "+(window.innerHeight/2-height/2)+"px) rotate(90deg)";_x000D_
      break;_x000D_
    default:_x000D_
      domElement.style.width = "100vw";_x000D_
      domElement.style.height = "100vh";_x000D_
      domElement.style.transformOrigin="";_x000D_
      domElement.style.transform="";_x000D_
      break;_x000D_
  }_x000D_
}_x000D_
window.addEventListener('orientationchange', processOrientation);_x000D_
processOrientation();
_x000D_
<html>_x000D_
<head></head>_x000D_
<body style="margin:0;padding:0;overflow: hidden;">_x000D_
  <div id="fullscreen-element-div" style="background-color:#00ff00;width:100vw;height:100vh;margin:0;padding:0"> Test_x000D_
  <br>_x000D_
  <input type="button" value="force 90" onclick="processOrientation(90);" /><br>_x000D_
  <input type="button" value="force -90" onclick="processOrientation(-90);" /><br>_x000D_
  <input type="button" value="back to normal" onclick="processOrientation();" />_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

how to replace an entire column on Pandas.DataFrame

If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning. Your example:

df = df.assign(B=df1['E'])

Equivalent of Math.Min & Math.Max for Dates?

There is no overload for DateTime values, but you can get the long value Ticks that is what the values contain, compare them and then create a new DateTime value from the result:

new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))

(Note that the DateTime structure also contains a Kind property, that is not retained in the new value. This is normally not a problem; if you compare DateTime values of different kinds the comparison doesn't make sense anyway.)

Javascript switch vs. if...else if...else

Answering in generalities:

  1. Yes, usually.
  2. See More Info Here
  3. Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.

Test site

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

One way to solve this problem is by turning the warnings off.

SET ANSI_WARNINGS OFF;
GO

How can I tell if a VARCHAR variable contains a substring?

The standard SQL way is to use like:

where @stringVar like '%thisstring%'

That is in a query statement. You can also do this in TSQL:

if @stringVar like '%thisstring%'

What's the difference between Invoke() and BeginInvoke()

Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want.

In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially if that delegate performs I/O (which could make the delegate and your thread block).

In those cases the BeginInvoke would be useful. By calling it, you're telling the delegate to start but then your thread is free to do other things in parallel with the delegate.

Using BeginInvoke increases the complexity of your code but there are times when the improved performance is worth the complexity.

using wildcards in LDAP search filters/queries

This should work, at least according to the Search Filter Syntax article on MSDN network.

The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.

You may also try separating the filter into two parts:

(|(displayName=*searchstring)(displayName=searchstring*))

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Spring can you autowire inside an abstract class?

In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:

public abstract class EO {
    @Autowired
    protected SmsNotificationService smsNotificationService;
    @Autowired
    protected SendEmailService sendEmailService;
    ...
    protected abstract void executeOperation(GenericMessage gMessage);
}

public final class OperationsExecutor {
    public enum OperationsType {
        ENROLL, CAMPAIGN
    }

    private OperationsExecutor() {
    }

    public static Object delegateOperation(OperationsType type, Object obj) 
    {
        switch(type) {
            case ENROLL:
                if (obj == null) {
                    return new EnrollOperation();
                }
                return EnrollOperation.validateRequestParams(obj);
            case CAMPAIGN:
                if (obj == null) {
                    return new CampaignOperation();
                }
                return CampaignOperation.validateRequestParams(obj);
            default:
                throw new IllegalArgumentException("OperationsType not supported.");
        }
    }
}

@Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
    @Override
    public void executeOperation(GenericMessage genericMessage) {
        LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
    }
}

Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)** annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.

<context:annotation-config />
<context:component-scan base-package="com.xyz" />

I also tried these other references to find a solution:

  1. http://www.captaindebug.com/2011/06/implementing-springs-factorybean.html#.WqF5pJPwaAN
  2. http://forum.spring.io/forum/spring-projects/container/46815-problem-with-autowired-in-abstract-class
  3. https://github.com/cavallefano/Abstract-Factory-Pattern-Spring-Annotation
  4. http://www.jcombat.com/spring/factory-implementation-using-servicelocatorfactorybean-in-spring
  5. https://www.madbit.org/blog/programming/1074/1074/#sthash.XEJXdIR5.dpbs
  6. Using abstract factory with Spring framework
  7. Spring Autowiring not working for Abstract classes
  8. Inject spring dependency in abstract super class
  9. Spring and Abstract class - injecting properties in abstract classes
    1. Spring autowire dependency defined in an abstract class

Please try using **@Configurable(dependencyCheck = true)** and update this post, I might try helping you if you face any problems.

Can't get Python to import from a different folder

The right way to import a module located on a parent folder, when you don't have a standard package structure, is:

import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))

(you can merge the last two lines but this way is easier to understand).

This solution is cross-platform and is general enough to need not modify in other circumstances.

Python read next()

next() does not work in your case because you first call readlines() which basically sets the file iterator to point to the end of file.

Since you are reading in all the lines anyway you can refer to the next line using an index:

filne = "in"
with open(filne, 'r+') as f:
    lines = f.readlines()
    for i in range(0, len(lines)):
        line = lines[i]
        print line
        if line[:5] == "anim ":
            ne = lines[i + 1] # you may want to check that i < len(lines)
            print ' ne ',ne,'\n'
            break

Excel VBA Password via Hex Editor

  1. Open xls file with a hex editor.
  2. Search for DPB
  3. Replace DPB to DPx
  4. Save file.
  5. Open file in Excel.
  6. Click "Yes" if you get any message box.
  7. Set new password from VBA Project Properties.
  8. Close and open again file, then type your new password to unprotect.

Check http://blog.getspool.com/396/best-vba-password-recovery-cracker-tool-remove/

Convert command line arguments into an array in Bash

The importance of the double quotes is worth emphasizing. Suppose an argument contains whitespace.

Code:

#!/bin/bash
printf 'arguments:%s\n' "$@"
declare -a arrayGOOD=( "$@" )
declare -a arrayBAAD=(  $@  )

printf '\n%s:\n' arrayGOOD
declare -p arrayGOOD
arrayGOODlength=${#arrayGOOD[@]}
for (( i=1; i<${arrayGOODlength}+1; i++ ));
do
   echo "${arrayGOOD[$i-1]}"
done

printf '\n%s:\n' arrayBAAD
declare -p arrayBAAD
arrayBAADlength=${#arrayBAAD[@]}
for (( i=1; i<${arrayBAADlength}+1; i++ ));
do
   echo "${arrayBAAD[$i-1]}"
done

Output:

> ./bash-array-practice.sh 'The dog ate the "flea" -- and ' the mouse.
arguments:The dog ate the "flea" -- and 
arguments:the
arguments:mouse.

arrayGOOD:
declare -a arrayGOOD='([0]="The dog ate the \"flea\" -- and " [1]="the" [2]="mouse.")'
The dog ate the "flea" -- and 
the
mouse.

arrayBAAD:
declare -a arrayBAAD='([0]="The" [1]="dog" [2]="ate" [3]="the" [4]="\"flea\"" [5]="--" [6]="and" [7]="the" [8]="mouse.")'
The
dog
ate
the
"flea"
--
and
the
mouse.
> 

How to change text transparency in HTML/CSS?

There is no CSS property like background-opacity that you can use only for changing the opacity or transparency of an element's background without affecting the child elements, on the other hand if you will try to use the CSS opacity property it will not only changes the opacity of background but changes the opacity of all the child elements as well. In such situation you can use RGBA color introduced in CSS3 that includes alpha transparency as part of the color value. Using RGBA color you can set the color of the background as well as its transparency.

Extract value of attribute node via XPath

As answered above:

//Parent[@id='1']/Children/child/@name 

will only output the name attribute of the 4 child nodes belonging to the Parent specified by its predicate [@id=1]. You'll then need to change the predicate to [@id=2] to get the set of child nodes for the next Parent.

However, if you ignore the Parent node altogether and use:

//child/@name

you can select name attribute of all child nodes in one go.

name="Child_2"
name="Child_4"
name="Child_1"
name="Child_3"
name="Child_1"
name="Child_2"
name="Child_4"
name="Child_3"

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

  1. Open "Settings"
  2. Search for "Maven"
  3. Click on "Ignored Files" under "Maven"
  4. Uncheck the pom.xml files contains the missing dependencies
  5. Click "OK"
  6. Click File -> Invalidate Caches/Restart...
  7. Click "Invalidate and Restart"

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

How to import a module given its name as string?

With Python older than 2.7/3.1, that's pretty much how you do it.

For newer versions, see importlib.import_module for Python 2 and and Python 3.

You can use exec if you want to as well.

Or using __import__ you can import a list of modules by doing this:

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)

Ripped straight from Dive Into Python.

Mockito: List Matchers with generics

For Java 8 and above, it's easy:

when(mock.process(Matchers.anyList()));

For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz):

when(mock.process(Matchers.anyListOf(Bar.class)));

Javascript: getFullyear() is not a function

Try this...

 var start = new Date(document.getElementById('Stardate').value);
 var y = start.getFullYear();

How to convert Seconds to HH:MM:SS using T-SQL

DECLARE @TimeinSecond INT
SET @TimeinSecond = 340 -- Change the seconds
SELECT RIGHT('0' + CAST(@TimeinSecond / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((@TimeinSecond / 60) % 60 AS VARCHAR),2)  + ':' +
RIGHT('0' + CAST(@TimeinSecond % 60 AS VARCHAR),2)

How to implement a FSM - Finite State Machine in Java

You can implement Finite State Machine in two different ways.

Option 1:

Finite State machine with a pre-defined workflow : Recommended if you know all states in advance and state machine is almost fixed without any changes in future

  1. Identify all possible states in your application

  2. Identify all the events in your application

  3. Identify all the conditions in your application, which may lead state transition

  4. Occurrence of an event may cause transitions of state

  5. Build a finite state machine by deciding a workflow of states & transitions.

    e.g If an event 1 occurs at State 1, the state will be updated and machine state may still be in state 1.

    If an event 2 occurs at State 1, on some condition evaluation, the system will move from State 1 to State 2

This design is based on State and Context patterns.

Have a look at Finite State Machine prototype classes.

Option 2:

Behavioural trees: Recommended if there are frequent changes to state machine workflow. You can dynamically add new behaviour without breaking the tree.

enter image description here

The base Task class provides a interface for all these tasks, the leaf tasks are the ones just mentioned, and the parent tasks are the interior nodes that decide which task to execute next.

The Tasks have only the logic they need to actually do what is required of them, all the decision logic of whether a task has started or not, if it needs to update, if it has finished with success, etc. is grouped in the TaskController class, and added by composition.

The decorators are tasks that “decorate” another class by wrapping over it and giving it additional logic.

Finally, the Blackboard class is a class owned by the parent AI that every task has a reference to. It works as a knowledge database for all the leaf tasks

Have a look at this article by Jaime Barrachina Verdia for more details

Check if array is empty or null

User JQuery is EmptyObject to check whether array is contains elements or not.

var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true

Android notification is not showing

You also need to change the build.gradle file, and add the used Android SDK version into it:

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

This worked like a charm in my case.

How to redirect to another page using AngularJS?

You can redirect to a new URL in different ways.

  1. You can use $window which will also refresh the page
  2. You can "stay inside" the single page app and use $location in which case you can choose between $location.path(YOUR_URL); or $location.url(YOUR_URL);. So the basic difference between the 2 methods is that $location.url() also affects get parameters whilst $location.path() does not.

I would recommend reading the docs on $location and $window so you get a better grasp on the differences between them.

How to initialize a list with constructor?

ContactNumbers = new List<ContactNumber>();

If you want it to be passed in, just take

public Human(List<ContactNumber> numbers)
{
 ContactNumbers = numbers;
}

Class type check in TypeScript

You can use the instanceof operator for this. From MDN:

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

_x000D_
_x000D_
    class Animal {_x000D_
        name;_x000D_
    _x000D_
        constructor(name) {_x000D_
            this.name = name;_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    const animal = new Animal('fluffy');_x000D_
    _x000D_
    // true because Animal in on the prototype chain of animal_x000D_
    console.log(animal instanceof Animal); // true_x000D_
    // Proof that Animal is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
    _x000D_
    // true because Object in on the prototype chain of animal_x000D_
    console.log(animal instanceof Object); _x000D_
    // Proof that Object is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
    _x000D_
    console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

The prototype chain in this example is:

animal > Animal.prototype > Object.prototype

How to stop flask application without using ctrl-c

This is a bit old thread, but if someone experimenting, learning, or testing basic flask app, started from a script that runs in the background, the quickest way to stop it is to kill the process running on the port you are running your app on. Note: I am aware the author is looking for a way not to kill or stop the app. But this may help someone who is learning.

sudo netstat -tulnp | grep :5001

You'll get something like this.

tcp 0 0 0.0.0.0:5001 0.0.0.0:* LISTEN 28834/python

To stop the app, kill the process

sudo kill 28834

Converting two lists into a matrix

Assuming lengths of portfolio and index are the same:

matrix = []
for i in range(len(portfolio)):
    matrix.append([portfolio[i], index[i]])

Or a one-liner using list comprehension:

matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]

Sending a JSON to server and retrieving a JSON in return, without JQuery

Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending and receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

How to add an Android Studio project to GitHub

You need to create the project on GitHub first. After that go to the project directory and run in terminal:

git init
git remote add origin https://github.com/xxx/yyy.git
git add .
git commit -m "first commit"
git push -u origin master

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.

http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/

AWS EFS vs EBS vs S3 (differences & when to use?)

AWS EFS, EBS and S3. From Functional Standpoint, here is the difference

EFS:

  1. Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security

  2. Highly available, scalable service.

  3. Running any application that has a high workload, requires scalable storage, and must produce output quickly.

  4. It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.

  5. Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.

  6. Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.

EBS:

  1. for NoSQL databases, EBS offers NoSQL databases the low-latency performance and dependability they need for peak performance.

S3:

Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.

2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.

  1. Backup and restoration: Secure, robust backup and restoration solutions
  2. Data archiving
  3. S3 is an object store good at storing vast numbers of backups or user files. Unlike EBS or EFS, S3 is not limited to EC2. Files stored within an S3 bucket can be accessed programmatically or directly from services such as AWS CloudFront. Many websites use it to hold their content and media files, which may be served efficiently via AWS CloudFront.

JPanel Padding in Java

I will suppose your JPanel contains JTextField, for the sake of the demo.

Those components provides JTextComponent#setMargin() method which seems to be what you're looking for.

If you're looking for an empty border of any size around your text, well, use EmptyBorder

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

CSS3 background image transition

Unfortunately you can't use transition on background-image, see the w3c list of animatable properties.

You may want to do some tricks with background-position.

Getting the ID of the element that fired an event

You can use (this) to reference the object that fired the function.

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/

an htop-like tool to display disk activity in linux

Use collectl which has extensive process I/O monitoring including monitoring threads.

Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html

Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?

ReflectionException: Class ClassName does not exist - Laravel

Not strictly related to the question but received the error ReflectionException: Class config does not exist

I had added a new .env variable with spaces in it. Running php artisan config:clear told me that any .env variable with spaces in it should be surrounded by "s.

Did this and my application stated working again, no need for config clear as still in development on Laravel Homestead (5.4)

How do you change library location in R?

You can edit Rprofile in the base library (in 'C:/Program Files/R.Files/library/base/R' by default) to include code to be run on startup. Append

########        User code        ########
.libPaths('C:/my/dir')

to Rprofile using any text editor (like Notepad) to cause R to add 'C:/my/dir' to the list of libraries it knows about.

(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)

In Python how should I test if a variable is None, True or False

There are many good answers. I would like to add one more point. A bug can get into your code if you are working with numerical values, and your answer is happened to be 0.

a = 0 
b = 10 
c = None

### Common approach that can cause a problem

if not a:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if not b:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}")

if not c:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")
Answer is not found. Answer is 0.   
Answer is: 10.   
Answer is not found. Answer is None.
### Safer approach 
if a is None:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if b is None:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}.")

if c is None:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")

Answer is: 0.
Answer is: 10.
Answer is not found. Answer is None.

Timeout a command in bash without unnecessary delay

I think this is precisely what you are asking for:

http://www.bashcookbook.com/bashinfo/source/bash-4.0/examples/scripts/timeout3

#!/bin/bash
#
# The Bash shell script executes a command with a time-out.
# Upon time-out expiration SIGTERM (15) is sent to the process. If the signal
# is blocked, then the subsequent SIGKILL (9) terminates it.
#
# Based on the Bash documentation example.

# Hello Chet,
# please find attached a "little easier"  :-)  to comprehend
# time-out example.  If you find it suitable, feel free to include
# anywhere: the very same logic as in the original examples/scripts, a
# little more transparent implementation to my taste.
#
# Dmitry V Golovashkin <[email protected]>

scriptName="${0##*/}"

declare -i DEFAULT_TIMEOUT=9
declare -i DEFAULT_INTERVAL=1
declare -i DEFAULT_DELAY=1

# Timeout.
declare -i timeout=DEFAULT_TIMEOUT
# Interval between checks if the process is still alive.
declare -i interval=DEFAULT_INTERVAL
# Delay between posting the SIGTERM signal and destroying the process by SIGKILL.
declare -i delay=DEFAULT_DELAY

function printUsage() {
    cat <<EOF

Synopsis
    $scriptName [-t timeout] [-i interval] [-d delay] command
    Execute a command with a time-out.
    Upon time-out expiration SIGTERM (15) is sent to the process. If SIGTERM
    signal is blocked, then the subsequent SIGKILL (9) terminates it.

    -t timeout
        Number of seconds to wait for command completion.
        Default value: $DEFAULT_TIMEOUT seconds.

    -i interval
        Interval between checks if the process is still alive.
        Positive integer, default value: $DEFAULT_INTERVAL seconds.

    -d delay
        Delay between posting the SIGTERM signal and destroying the
        process by SIGKILL. Default value: $DEFAULT_DELAY seconds.

As of today, Bash does not support floating point arithmetic (sleep does),
therefore all delay/time values must be integers.
EOF
}

# Options.
while getopts ":t:i:d:" option; do
    case "$option" in
        t) timeout=$OPTARG ;;
        i) interval=$OPTARG ;;
        d) delay=$OPTARG ;;
        *) printUsage; exit 1 ;;
    esac
done
shift $((OPTIND - 1))

# $# should be at least 1 (the command to execute), however it may be strictly
# greater than 1 if the command itself has options.
if (($# == 0 || interval <= 0)); then
    printUsage
    exit 1
fi

# kill -0 pid   Exit code indicates if a signal may be sent to $pid process.
(
    ((t = timeout))

    while ((t > 0)); do
        sleep $interval
        kill -0 $$ || exit 0
        ((t -= interval))
    done

    # Be nice, post SIGTERM first.
    # The 'exit 0' below will be executed if any preceeding command fails.
    kill -s SIGTERM $$ && kill -0 $$ || exit 0
    sleep $delay
    kill -s SIGKILL $$
) 2> /dev/null &

exec "$@"

Display JSON as HTML

I think you meant something like this: JSON Visualization

Don't know if you might use it, but you might ask the author.

WPF What is the correct way of using SVG files as icons in WPF

Install the SharpVectors library

Install-Package SharpVectors

Add the following in XAML

<UserControl xmlns:svgc="http://sharpvectors.codeplex.com/svgc">
    <svgc:SvgViewbox Source="/Icons/icon.svg"/>
</UserControl>

How to make an AJAX call without jQuery?

You can get the correct object according to the browser with

function getXmlDoc() {
  var xmlDoc;

  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlDoc = new XMLHttpRequest();
  }
  else {
    // code for IE6, IE5
    xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
  }

  return xmlDoc;
}

With the correct object, a GET might can be abstracted to:

function myGet(url, callback) {
  var xmlDoc = getXmlDoc();

  xmlDoc.open('GET', url, true);

  xmlDoc.onreadystatechange = function() {
    if (xmlDoc.readyState === 4 && xmlDoc.status === 200) {
      callback(xmlDoc);
    }
  }

  xmlDoc.send();
}

And a POST to:

function myPost(url, data, callback) {
  var xmlDoc = getXmlDoc();

  xmlDoc.open('POST', url, true);
  xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xmlDoc.onreadystatechange = function() {
    if (xmlDoc.readyState === 4 && xmlDoc.status === 200) {
      callback(xmlDoc);
    }
  }

  xmlDoc.send(data);
}

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

this problem occurs when we make custom header for request.This request that uses the HTTP OPTIONS and includes several headers.

The required header for this request is Access-Control-Request-Headers , which should be part of response header and should allow request from all the origin. Sometimes it needs Content-Type as well in header of response. So your response header should be like that -

response.header("Access-Control-Allow-Origin", "*"); // allow request from all origin
response.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
response.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization");

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

For all that you add xmlbeans-2.3.0.jar and it is not working,you must use HSSFWorkbook instead of XSSFWorkbook after add jar.For instance;

    Workbook workbook = new HSSFWorkbook();
    Sheet listSheet = workbook.createSheet("Kisi Listesi");

    int rowIndex = 0;
    for (KayitParam kp : kayitList) {
        Row row = listSheet.createRow(rowIndex++);
        int cellIndex = 0;
        row.createCell(cellIndex++).setCellValue(kp.getAd());
        row.createCell(cellIndex++).setCellValue(kp.getSoyad());
        row.createCell(cellIndex++).setCellValue(kp.getEposta());
        row.createCell(cellIndex++).setCellValue(kp.getCinsiyet());
        row.createCell(cellIndex++).setCellValue(kp.getDogumtarihi());
        row.createCell(cellIndex++).setCellValue(kp.getTahsil());
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        AMedia amedia = new AMedia("Kisiler.xls", "xls",
                "application/file", baos.toByteArray());
        Filedownload.save(amedia);
        baos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

Making a drop down list using swift?

Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines

If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.

Alternatively

you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well

you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

How do I find a default constraint using INFORMATION_SCHEMA?

There seems to be no Default Constraint names in the Information_Schema views.

use SELECT * FROM sysobjects WHERE xtype = 'D' AND name = @name to find a default constraint by name

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

The compiler is already telling you, it's not value but variable. You are looking for -Wno-unused-variable. Also, try g++ --help=warnings to see a list of available options.

Multiple queries executed in java in single statement

Hint: If you have more than one connection property then separate them with:

&amp;

To give you somthing like:

url="jdbc:mysql://localhost/glyndwr?autoReconnect=true&amp;allowMultiQueries=true"

I hope this helps some one.

Regards,

Glyn

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

angular2 submit form by pressing enter without submit button

Edit:

  <form (submit)="submit()" >
    <input />
    <button type="submit" style="display:none">hidden submit</button>
  </form>

In order to use this method, you need to have a submit button even if it's not displayed "Thanks for Toolkit's answer"

Old Answer:

Yes, exactly as you wrote it, except the event name is (submit) instead of (ngSubmit):

<form [ngFormModel]="xxx" (submit)="xxxx()">
  <input [(ngModel)]="lxxR"   ngControl="xxxxx"/>
</form>

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

For me the solution was simple: the user name is case sensitive. Failing to use the correct caps will also lead to the error.

Build a simple HTTP server in C

An HTTP server is conceptually simple:

  • Open port 80 for listening
  • When contact is made, gather a little information (get mainly - you can ignore the rest for now)
  • Translate the request into a file request
  • Open the file and spit it back at the client

It gets more difficult depending on how much of HTTP you want to support - POST is a little more complicated, scripts, handling multiple requests, etc.

But the base is very simple.

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

How to perform mouseover function in Selenium WebDriver using Java?

Based on this blog post I was able to trigger hovering using the following code with Selenium 2 Webdriver:

String javaScript = "var evObj = document.createEvent('MouseEvents');" +
                    "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" +
                    "arguments[0].dispatchEvent(evObj);";


((JavascriptExecutor)driver).executeScript(javaScript, webElement);

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

You're probably missing some dependencies.

Locate the dependencies you're missing with mvn dependency:tree, then install them manually, and build your project with the -o (offline) option.

Why is char[] preferred over String for passwords?

To quote an official document, the Java Cryptography Architecture guide says this about char[] vs. String passwords (about password-based encryption, but this is more generally about passwords of course):

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

Guideline 2-2 of the Secure Coding Guidelines for the Java Programming Language, Version 4.0 also says something similar (although it is originally in the context of logging):

Guideline 2-2: Do not log highly sensitive information

Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators. For instance, it should not be sent to log files and its presence should not be detectable through searches. Some transient data may be kept in mutable data structures, such as char arrays, and cleared immediately after use. Clearing data structures has reduced effectiveness on typical Java runtime systems as objects are moved in memory transparently to the programmer.

This guideline also has implications for implementation and use of lower-level libraries that do not have semantic knowledge of the data they are dealing with. As an example, a low-level string parsing library may log the text it works on. An application may parse an SSN with the library. This creates a situation where the SSNs are available to administrators with access to the log files.

Python for and if on one line

Found this one:

[x for (i,x) in enumerate(my_list) if my_list[i] == "two"]

Will print:

["two"]

How to change the height of a div dynamically based on another div using css?

In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...

function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}

You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/

Laravel 4: how to "order by" using Eloquent ORM

If you are using post as a model (without dependency injection), you can also do:

$posts = Post::orderBy('id', 'DESC')->get();

Postgres DB Size Command

You can enter the following psql meta-command to get some details about a specified database, including its size:

\l+ <database_name>

And to get sizes of all databases (that you can connect to):

\l+

How to call a MySQL stored procedure from within PHP code?

I now found solution by using mysqli instead of mysql.

<?php 

// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$connection = mysqli_connect("hostname", "user", "password", "db", "port");

//run the store proc
$result = mysqli_query($connection, "CALL StoreProcName");

//loop the result set
while ($row = mysqli_fetch_array($result)){     
  echo $row[0] . " - " . + $row[1]; 
}

I found that many people seem to have a problem with using mysql_connect, mysql_query and mysql_fetch_array.

How can I use a JavaScript variable as a PHP variable?

You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.

Omitting the first line from any Linux command output

The tail program can do this:

ls -lart | tail -n +2

The -n +2 means “start passing through on the second line of output”.

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Another way to do this is described below.

First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation. Then set maximum iterations to 1000.

After doing this, use the following formula.

=If(D55="","",IF(C55="",NOW(),C55))

Once anything is typed into cell D55 (for this example) then C55 populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.

This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.

Pip freeze vs. pip list

Look at the pip documentation, which describes the functionality of both as:

pip list

List installed packages, including editables.

pip freeze

Output installed packages in requirements format.

So there are two differences:

  1. Output format, freeze gives us the standard requirement format that may be used later with pip install -r to install requirements from.

  2. Output content, pip list include editables which pip freeze does not.

Changes in import statement python3

Added another case to Michal Górny's answer:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.