Programs & Examples On #Configuration management

Software configuration management (SCM) is the task of tracking and controlling changes in the software deployments

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

Selenium WebDriver.get(url) does not open the URL

I got the same error when issuing a URL without the protocol (like localhost:4200) instead of a correct one also specifying the protocol (e.g. http://localhost:4200).

Google Chrome works fine without the protocol (it takes http as the default), but Firefox crashes with this error.

How to check if $_GET is empty?

I would use the following if statement because it is easier to read (and modify in the future)


if(!isset($_GET) || !is_array($_GET) || count($_GET)==0) {
   // empty, let's make sure it's an empty array for further reference
   $_GET=array();
   // or unset it 
   // or set it to null
   // etc...
}

Loading context in Spring using web.xml

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info

How to convert FormData (HTML5 object) to JSON

Even though the answer from @dzuc is already very good, you could use array destructuring (available in modern browsers or with Babel) to make it even a bit more elegant:

// original version from @dzuc
const data = Array.from(formData.entries())
  .reduce((memo, pair) => ({
    ...memo,
    [pair[0]: pair[1],
  }), {})

// with array destructuring
const data = Array.from(formData.entries())
  .reduce((memo,[key, value]) => ({
    ...memo,
    [key]: value,
  }), {})

How to execute an SSIS package from .NET?

To add to @Craig Schwarze answer,

Here are some related MSDN links:

Loading and Running a Local Package Programmatically:

Loading and Running a Remote Package Programmatically

Capturing Events from a Running Package:

using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace RunFromClientAppWithEventsCS
{
  class MyEventListener : DefaultEvents
  {
    public override bool OnError(DtsObject source, int errorCode, string subComponent, 
      string description, string helpFile, int helpContext, string idofInterfaceWithError)
    {
      // Add application-specific diagnostics here.
      Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
      return false;
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      string pkgLocation;
      Package pkg;
      Application app;
      DTSExecResult pkgResults;

      MyEventListener eventListener = new MyEventListener();

      pkgLocation =
        @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
        @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
      app = new Application();
      pkg = app.LoadPackage(pkgLocation, eventListener);
      pkgResults = pkg.Execute(null, null, eventListener, null, null);

      Console.WriteLine(pkgResults.ToString());
      Console.ReadKey();
    }
  }
}

Where can I get Google developer key

Go to https://code.google.com/p/google-api-php-client/wiki/OAuth2

Scroll down to where it says 'Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.'

Click on the 'Google API Console' link.

When it pops up and says 'Welcome to the new Google Developers Console! Prefer the old console? Go back | Dismiss' Click on 'GO BACK'

Setting DIV width and height in JavaScript

The properties you're using may not work in Firefox, Chrome, and other non-IE browsers. To make this work in all browsers, I also suggest adding the following:

document.getElementById('div_register').setAttribute("style","width:500px");

For cross-compatibility, you will still need to use the property. Order may also matter. For instance, in my code, when setting style properties with JavaScript, I set the style attribute first, then I set the properties:

document.getElementById("mydiv").setAttribute("style","display:block;cursor:pointer;cursor:hand;");
document.getElementById("mydiv").style.display = "block";
document.getElementById("mydiv").style.cursor = "hand";

Thus, the most cross-browser compatible example for you would be:

document.getElementById('div_register').setAttribute("style","display:block;width:500px");
document.getElementById('div_register').style.width='500px';

I also want to point out that a much easier method of managing styles is to use a CSS class selector and put your styles in external CSS files. Not only will your code be much more maintainable, but you'll actually make friends with your Web designers!

document.getElementById("div_register").setAttribute("class","wide");

.wide {
    display:block;
    width:500px;
}

.hide {
    display:none;
}

.narrow {
    display:block;
    width:100px;
}

Now, I can easily just add and remove a class attribute, one single property, instead of calling multiple properties. In addition, when your Web designer wants to change the definition of what it means to be wide, he or she does not need to go poking around in your beautifully maintained JavaScript code. Your JavaScript code remains untouched, yet the theme of your application can be easily customized.

This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS).

Including .cpp files

You should just include header file(s).

If you include header file, header file automatically finds .cpp file. --> This process is done by LINKER.

Bash loop ping successful

I use this Bash script to test the internet status every minute on OSX

#address=192.168.1.99  # forced bad address for testing/debugging
address=23.208.224.170 # www.cisco.com
internet=1             # default to internet is up

while true;
do
    # %a  Day of Week, textual
    # %b  Month, textual, abbreviated
    # %d  Day, numeric
    # %r  Timestamp AM/PM
    echo -n $(date +"%a, %b %d, %r") "-- " 
    ping -c 1 ${address} > /tmp/ping.$
    if [[ $? -ne 0 ]]; then
        if [[ ${internet} -eq 1 ]]; then   # edge trigger -- was up now down
            echo -n $(say "Internet down") # OSX Text-to-Speech
            echo -n "Internet DOWN"
        else
            echo -n "... still down"
        fi
        internet=0
    else
        if [[ ${internet} -eq 0 ]]; then     # edge trigger -- was down now up
            echo -n $(say "Internet back up") # OSX Text-To-Speech
        fi
        internet=1
    fi   
    cat /tmp/ping.$ | head -2 | tail -1
    sleep 60 ; # sleep 60 seconds =1 min
done

Select multiple images from android gallery

Define these variables in the class:

int PICK_IMAGE_MULTIPLE = 1; 
String imageEncoded;    
List<String> imagesEncodedList;

Let's Assume that onClick on a button it should open gallery to select images

 Intent intent = new Intent();
 intent.setType("image/*");
 intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 intent.setAction(Intent.ACTION_GET_CONTENT);
 startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);

Then you should override onActivityResult Method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        // When an Image is picked
        if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
                    && null != data) {
            // Get the Image from data

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            imagesEncodedList = new ArrayList<String>();
            if(data.getData()!=null){

                Uri mImageUri=data.getData();

                // Get the cursor
                Cursor cursor = getContentResolver().query(mImageUri,
                            filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imageEncoded  = cursor.getString(columnIndex);
                cursor.close();

            } else {
                if (data.getClipData() != null) {
                    ClipData mClipData = data.getClipData();
                    ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                    for (int i = 0; i < mClipData.getItemCount(); i++) {

                        ClipData.Item item = mClipData.getItemAt(i);
                        Uri uri = item.getUri();
                        mArrayUri.add(uri);
                        // Get the cursor
                        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                        // Move to first row
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        imageEncoded  = cursor.getString(columnIndex);
                        imagesEncodedList.add(imageEncoded);
                        cursor.close();

                    }
                    Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
                }
            }
        } else {
            Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
    }

    super.onActivityResult(requestCode, resultCode, data);
}

NOTE THAT: the gallery doesn't give you the ability to select multi-images so we here open all images studio that you can select multi-images from them. and don't forget to add the permissions to your manifest

VERY IMPORTANT: getData(); to get one single image and I've stored it here in imageEncoded String if the user select multi-images then they should be stored in the list

So you have to check which is null to use the other

Wish you have a nice try and to others

How to enable C++11/C++0x support in Eclipse CDT?

I can't yet comment so am writing my own answer:

It's related to __GXX_EXPERIMENTAL_CXX0X__ and it's valid for Eclipse Juno and CDT 8.x.

Some parts of this answer are already covered in other answers but I want it to be coherent.

To make it possible to build using stdc++11, one have to add specific flag for compiler. You can do that via project properties. To modify project properties RMB andProject properties or ALT + ENTER. Then C/C++ Build -> Settings -> Tool Settings -> GCC C++ Compiler -> Miscellaneous -> Other Flags. Put -std=c++11 at the end of line, for GCC it will look something like: -c -fmessage-length=0 -std=c++11. By adding -stdc++11 flag compiler (GCC) will declare __GXX_EXPERIMENTAL_CXX0X__ by itself.

At this point you can build project using all the goodness of C++11.

The problem is that Eclipse has it's own parser to check for errors - that's why you're still getting all the nasty errors in Eclipse editor, while at the same time you can build and run project without any. There is a way to solve this problem by explicitly declaring __GXX_EXPERIMENTAL_CXX0X__ flag for the project, one can do that (just like Carsten Greiner said): C/C++ General -> Paths and Symbols -> Symbols -> GNU C++. Click "Add..." and past __GXX_EXPERIMENTAL_CXX0X__ (ensure to append and prepend two underscores) into "Name" and leave "Value" blank. And now is the extra part I wanted to cover in comment to the first answer, go to: C/C++ General -> Preprocessor Include Path Macros etc. -> Providers, and Select CDT Managed Build Setting Entries then click APPLY and go back to Entries tab, under GNU C++ there should be now CDT Managed Build Setting Entries check if inside there is defined __GXX_EXPERIMENTAL_CXX0X__ if it is -> APPLY and rebuild index you should be fine at this point.

How to convert seconds to time format?

1 day = 86400000 milliseconds.

DecodeTime(milliseconds/86400000,hr,min,sec,msec)

Ups! I was thinking in delphi, there must be something similar in all languages.

Definition of "downstream" and "upstream"

When you read in git tag man page:

One important aspect of git is it is distributed, and being distributed largely means there is no inherent "upstream" or "downstream" in the system.

, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:

If "yourRepo" has declared "otherRepo" as a remote one, then:

  • you are pulling from upstream "otherRepo" ("otherRepo" is "upstream from you", and you are "downstream for otherRepo").
  • you are pushing to upstream ("otherRepo" is still "upstream", where the information now goes back to).

Note the "from" and "for": you are not just "downstream", you are "downstream from/for", hence the relative aspect.


The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.

  • you know what upstream is (the repos you are pulling from or pushing to)
  • you don't know what downstream is made of (the other repos pulling from or pushing to your repo).

Basically:

In term of "flow of data", your repo is at the bottom ("downstream") of a flow coming from upstream repos ("pull from") and going back to (the same or other) upstream repos ("push to").


You can see an illustration in the git-rebase man page with the paragraph "RECOVERING FROM UPSTREAM REBASE":

It means you are pulling from an "upstream" repo where a rebase took place, and you (the "downstream" repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).

That is bad because for one "upstream" repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.

Again, with the "flow of data" analogy, in a DVCS, one bad command "upstream" can have a "ripple effect" downstream.


Note: this is not limited to data.
It also applies to parameters, as git commands (like the "porcelain" ones) often call internally other git commands (the "plumbing" ones). See rev-parse man page:

Many git porcelainish commands take mixture of flags (i.e. parameters that begin with a dash '-') and parameters meant for the underlying git rev-list command they use internally and flags and parameters for the other commands they use downstream of git rev-list. This command is used to distinguish between them.

What is the difference between “int” and “uint” / “long” and “ulong”?

It's been a while since I C++'d but these answers are off a bit.

As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.

So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.

It's never polite to discuss the size of your bits in public.

When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.

So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.

Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder

A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html

use int if you really don't care how large your bits are; it can change.

Use size_t and ssize_t if you want to know how large something is.

If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.

I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.

It's crappy coding when you mix int.

use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).

Assign result of dynamic sql to variable

Most of these answers use sp_executesql as the solution to this problem. I have found that there are some limitations when using sp_executesql, which I will not go into, but I wanted to offer an alternative using EXEC(). I am using SQL Server 2008 and I know that some of the objects I am using in this script are not available in earlier versions of SQL Server so be wary.

DECLARE @CountResults TABLE (CountReturned INT)
DECLARE 
    @SqlStatement VARCHAR(8000) = 'SELECT COUNT(*) FROM table'
    , @Count INT

INSERT @CountResults
EXEC(@SqlStatement)

SET @Count = (SELECT CountReturned FROM @CountResults)
SELECT @Count

How to clear memory to prevent "out of memory error" in excel vba?

I had a similar problem that I resolved myself.... I think it was partially my code hogging too much memory while too many "big things"

in my application - the workbook goes out and grabs another departments "daily report".. and I extract out all the information our team needs (to minimize mistakes and data entry).

I pull in their sheets directly... but I hate the fact that they use Merged cells... which I get rid of (ie unmerge, then find the resulting blank cells, and fill with the values from above)

I made my problem go away by

a)unmerging only the "used cells" - rather than merely attempting to do entire column... ie finding the last used row in the column, and unmerging only this range (there is literally 1000s of rows on each of the sheet I grab)

b) Knowing that the undo only looks after the last ~16 events... between each "unmerge" - i put 15 events which clear out what is stored in the "undo" to minimize the amount of memory held up (ie go to some cell with data in it.. and copy// paste special value... I was GUESSING that the accumulated sum of 30sheets each with 3 columns worth of data might be taxing memory set as side for undoing

Yes it doesn't allow for any chance of an Undo... but the entire purpose is to purge the old information and pull in the new time sensitive data for analysis so it wasn't an issue

Sound corny - but my problem went away

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

After lot of failed tried attempts ,I found the solution

It was the ";" at end of JAVA_HOME which I always put at end of each new variable I set. So get rid of the ;.

JAVA_HOME set it in User Variable also (without the ";" ofcourse)

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

You defined your method as non-static and you are trying to invoke it as static. That said...

1.if you want to invoke a static method, you should use the :: and define your method as static.

// Defining a static method in a Foo class.
public static function getAll() { /* code */ }

// Invoking that static method
Foo::getAll();

2.otherwise, if you want to invoke an instance method you should instance your class, use ->.

// Defining a non-static method in a Foo class.
public function getAll() { /* code */ }

// Invoking that non-static method.
$foo = new Foo();
$foo->getAll();

Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:

$foos = Foo::all()->take(10)->get();

In that code we are statically calling the all method via Facade. After that, all other methods are being called as instance methods.

how to use getSharedPreferences in android

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

Bootstrap 3 breakpoints and media queries

I know this is a bit old, but i thought i would contribute. Basing myself on the answer by @Sophy, this is what I did to add a .xxs breakpoint. I have not taken care of visible-inline, table.visible, etc classes.

/*==========  Mobile First Method  ==========*/

  .col-xxs-12, .col-xxs-11, .col-xxs-10, .col-xxs-9, .col-xxs-8, .col-xxs-7, .col-xxs-6, .col-xxs-5, .col-xxs-4, .col-xxs-3, .col-xxs-2, .col-xxs-1 {
    position: relative;
    min-height: 1px;
    padding-left: 15px;
    padding-right: 15px;
    float: left;
  }

.visible-xxs {
  display:none !important;
}

/* Custom, iPhone Retina */
@media only screen and (min-width : 320px) and (max-width:479px) {

  .visible-xxs {
    display: block !important;
  }
  .visible-xs {
    display:none !important;
  }

  .hidden-xs {
    display:block !important;
  }

  .hidden-xxs {
    display:none !important;
  }

  .col-xxs-12 {
    width: 100%;
  }
  .col-xxs-11 {
    width: 91.66666667%;
  }
  .col-xxs-10 {
    width: 83.33333333%;
  }
  .col-xxs-9 {
    width: 75%;
  }
  .col-xxs-8 {
    width: 66.66666667%;
  }
  .col-xxs-7 {
    width: 58.33333333%;
  }
  .col-xxs-6 {
    width: 50%;
  }
  .col-xxs-5 {
    width: 41.66666667%;
  }
  .col-xxs-4 {
    width: 33.33333333%;
  }
  .col-xxs-3 {
    width: 25%;
  }
  .col-xxs-2 {
    width: 16.66666667%;
  }
  .col-xxs-1 {
    width: 8.33333333%;
  }
  .col-xxs-pull-12 {
    right: 100%;
  }
  .col-xxs-pull-11 {
    right: 91.66666667%;
  }
  .col-xxs-pull-10 {
    right: 83.33333333%;
  }
  .col-xxs-pull-9 {
    right: 75%;
  }
  .col-xxs-pull-8 {
    right: 66.66666667%;
  }
  .col-xxs-pull-7 {
    right: 58.33333333%;
  }
  .col-xxs-pull-6 {
    right: 50%;
  }
  .col-xxs-pull-5 {
    right: 41.66666667%;
  }
  .col-xxs-pull-4 {
    right: 33.33333333%;
  }
  .col-xxs-pull-3 {
    right: 25%;
  }
  .col-xxs-pull-2 {
    right: 16.66666667%;
  }
  .col-xxs-pull-1 {
    right: 8.33333333%;
  }
  .col-xxs-pull-0 {
    right: auto;
  }
  .col-xxs-push-12 {
    left: 100%;
  }
  .col-xxs-push-11 {
    left: 91.66666667%;
  }
  .col-xxs-push-10 {
    left: 83.33333333%;
  }
  .col-xxs-push-9 {
    left: 75%;
  }
  .col-xxs-push-8 {
    left: 66.66666667%;
  }
  .col-xxs-push-7 {
    left: 58.33333333%;
  }
  .col-xxs-push-6 {
    left: 50%;
  }
  .col-xxs-push-5 {
    left: 41.66666667%;
  }
  .col-xxs-push-4 {
    left: 33.33333333%;
  }
  .col-xxs-push-3 {
    left: 25%;
  }
  .col-xxs-push-2 {
    left: 16.66666667%;
  }
  .col-xxs-push-1 {
    left: 8.33333333%;
  }
  .col-xxs-push-0 {
    left: auto;
  }
  .col-xxs-offset-12 {
    margin-left: 100%;
  }
  .col-xxs-offset-11 {
    margin-left: 91.66666667%;
  }
  .col-xxs-offset-10 {
    margin-left: 83.33333333%;
  }
  .col-xxs-offset-9 {
    margin-left: 75%;
  }
  .col-xxs-offset-8 {
    margin-left: 66.66666667%;
  }
  .col-xxs-offset-7 {
    margin-left: 58.33333333%;
  }
  .col-xxs-offset-6 {
    margin-left: 50%;
  }
  .col-xxs-offset-5 {
    margin-left: 41.66666667%;
  }
  .col-xxs-offset-4 {
    margin-left: 33.33333333%;
  }
  .col-xxs-offset-3 {
    margin-left: 25%;
  }
  .col-xxs-offset-2 {
    margin-left: 16.66666667%;
  }
  .col-xxs-offset-1 {
    margin-left: 8.33333333%;
  }
  .col-xxs-offset-0 {
    margin-left: 0%;
  }

}

/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px) {

  .visible-xs {
    display:block !important;
  }

}

/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {

  .visible-xs {
    display:none !important;
  }

}

/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {

}

/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {

}

How to find top three highest salary in emp table in oracle?

solution for to find top 5 salary in sq l server

select top(1) name, salary from salary where salary in(select distinct top(3) salary from salary order by salary disc)

How to preview an image before and after upload?

                    #######################
                    ###  the img page   ###
                    #######################


<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#f').live('change' ,function(){
            $('#fo').ajaxForm({target: '#d'}).submit();
        });
    });
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
    <input type="file" name="f" id="f" value="start upload" />
    <input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>


                    #############################
                    ###    the nextimg page   ###
                    #############################


<?php
     $name=$_FILES['f']['name'];
     $tmp=$_FILES['f']['tmp_name'];
     $new=time().$name;
     $new="upload/".$new;
     move_uploaded_file($tmp,$new);
     if($_FILES['f']['error']==0)
     {
?>
     <h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
     }
?>

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

accessing a variable from another class

Filename=url.java

public class url {

    public static final String BASEURL = "http://192.168.1.122/";

}

if u want to call the variable just use this:

url.BASEURL + "your code here";

How to access local files of the filesystem in the Android emulator?

In addition to the accepted answer, if you are using Android Studio you can

  1. invoke Android Device Monitor,
  2. select the device in the Devices tab on the left,
  3. select File Explorer tab on the right,
  4. navigate to the file you want, and
  5. click the Pull a file from the device button to save it to your local file system

Taken from Working with an emulator or device's file system

Ruby optional parameters

This isn't possible with ruby currently. You can't pass 'empty' attributes to methods. The closest you can get is to pass nil:

ldap_get(base_dn, filter, nil, X)

However, this will set the scope to nil, not LDAP::LDAP_SCOPE_SUBTREE.

What you can do is set the default value within your method:

def ldap_get(base_dn, filter, scope = nil, attrs = nil)
  scope ||= LDAP::LDAP_SCOPE_SUBTREE
  ... do something ...
end

Now if you call the method as above, the behaviour will be as you expect.

Javascript + Regex = Nothing to repeat error?

Well, in my case I had to test a Phone Number with the help of regex, and I was getting the same error,

Invalid regular expression: /+923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/: Nothing to repeat'

So, what was the error in my case was that + operator after the / in the start of the regex. So enclosing the + operator with square brackets [+], and again sending the request, worked like a charm.

Following will work:

/[+]923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/

This answer may be helpful for those, who got the same type of error, but their chances of getting the error from this point of view, as mine! Cheers :)

force Maven to copy dependencies into target/lib

If you want to deliver a bundle of your application jar, together with all its dependencies and some scripts to invoke the MainClass, look at the appassembler-maven-plugin.

The following configuration will generate scripts for Window and Linux to launch the application (with a generated path referencing all the dependency jars, download all dependencies (into a lib folder below target/appassembler). The assembly plugin can then be used to package the whole appassembler directory to a zip which is installed/deployed along with the jar to the repository.

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>appassembler-maven-plugin</artifactId>
    <version>1.0</version>
    <executions>
      <execution>
        <id>generate-jsw-scripts</id>
        <phase>package</phase>
        <goals>
          <goal>generate-daemons</goal>
        </goals>
        <configuration>
          <!--declare the JSW config -->
          <daemons>
            <daemon>
              <id>myApp</id>
              <mainClass>name.seller.rich.MyMainClass</mainClass>
              <commandLineArguments>
                <commandLineArgument>start</commandLineArgument>
              </commandLineArguments>
              <platforms>
                <platform>jsw</platform>
              </platforms>              
            </daemon>
          </daemons>
          <target>${project.build.directory}/appassembler</target>
        </configuration>
      </execution>
      <execution>
        <id>assemble-standalone</id>
        <phase>integration-test</phase>
        <goals>
          <goal>assemble</goal>
        </goals>
        <configuration>
          <programs>
            <program>
              <mainClass>name.seller.rich.MyMainClass</mainClass>
              <!-- the name of the bat/sh files to be generated -->
              <name>mymain</name>
            </program>
          </programs>
          <platforms>
            <platform>windows</platform>
            <platform>unix</platform>
          </platforms>
          <repositoryLayout>flat</repositoryLayout>
          <repositoryName>lib</repositoryName>
        </configuration>
      </execution>
    </executions>
  </plugin>
  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2-beta-4</version>
    <executions>
      <execution>
        <phase>integration-test</phase>
        <goals>
          <goal>single</goal>
        </goals>
        <configuration>
          <descriptors>
            <descriptor>src/main/assembly/archive.xml</descriptor>
          </descriptors>
        </configuration>
      </execution>
    </executions>
  </plugin> 

The assembly descriptor (in src/main/assembly) to package the direcotry as a zip would be:

<assembly>
  <id>archive</id>
  <formats>
    <format>zip</format>
  </formats>
  <fileSets>
    <fileSet>
     <directory>${project.build.directory}/appassembler</directory>
     <outputDirectory>/</outputDirectory>
    </fileSet>
  </fileSets>
</assembly>

Why do I get a "permission denied" error while installing a gem?

I wanted to share the steps that I followed that fixed this issue for me in the hopes that it can help someone else (and also as a reminder for me in case something like this happens again)

The issues I'd been having (which were the same as OP's) may have to do with using homebrew to install Ruby.

To fix this, first I updated homebrew:

brew update && brew upgrade
brew doctor

(If brew doctor comes up with any issues, fix them first.) Then I uninstalled ruby

brew uninstall ruby

If rbenv is NOT installed at this point, then

brew install rbenv
brew install ruby-build
echo 'export RBENV_ROOT=/usr/local/var/rbenv' >> ~/.bash_profile
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile

Then I used rbenv to install ruby. First, find the desired version:

rbenv install -l

Install that version (e.g. 2.2.2)

rbenv install 2.2.2

Then set the global version to the desired ruby version:

rbenv global 2.2.2

At this point you should see the desired version set for the following commands:

rbenv versions

and

ruby --version

Now you should be able to install bundler:

gem install bundler

And once in the desired project folder, you can install all the required gems:

bundle
bundle install

Is there a way to instantiate a class by name in Java?

Two ways:

Method 1 - only for classes having a no-arg constructor

If your class has a no-arg constructor, you can get a Class object using Class.forName() and use the newInstance() method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).

For example:

Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.newInstance();

Method 2

An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor object and call a newInstance() method on this object:

Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);

Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:

  • the JVM can't find or can't load your class
  • the class you're trying to instantiate doesn't have the right sort of constructors
  • the constructor itself threw an exception
  • the constructor you're trying to invoke isn't public
  • a security manager has been installed and is preventing reflection from occurring

Converting a year from 4 digit to 2 digit and back again in C#

1st solution (fastest) :

yourDateTime.Year % 100

2nd solution (more elegant in my opinion) :

yourDateTime.ToString("yy")

How can I clear the content of a file?

You can use the File.WriteAllText method.

System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);

PHP Fatal error: Cannot access empty property

As I see in your code, it seems you are following an old documentation/tutorial about OOP in PHP based on PHP4 (OOP wasn't supported but adapted somehow to be used in a simple ways), since PHP5 an official support was added and the notation has been changed from what it was.

Please see this code review here:

<?php
class my_class{

    public $my_value = array();

    function __construct( $value ) { // the constructor name is __construct instead of the class name
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->my_value = $value; // remove the $ sign
    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string 
// $a->my_class('d'); // you can call this if you mean calling the contructor 


// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
    echo $value;
}

?>

I hope it helps

String comparison using '==' vs. 'strcmp()'

PHP Instead of using alphabetical sorting, use the ASCII value of the character to make the comparison. Lowercase letters have a higher ASCII value than capitals. It's better to use the identity operator === to make this sort of comparison. strcmp() is a function to perform binary safe string comparisons. It takes two strings as arguments and returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. There is also a case-insensitive version named strcasecmp() that first converts strings to lowercase and then compares them.

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

I believe the responses already posted should get people going in the right direction. However here is what I did that made sense for the legacy code I was updating. The legacy code was using the URI from the gallery to change and then save the images.

Prior to 4.4 (and google drive), the URIs would look like this: content://media/external/images/media/41

As stated in the question, they more often look like this: content://com.android.providers.media.documents/document/image:3951

Since I needed the ability to save images and not disturb the already existing code, I just copied the URI from the gallery into the data folder of the app. Then originated a new URI from the saved image file in the data folder.

Here's the idea:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent), CHOOSE_IMAGE_REQUEST);

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    File tempFile = new File(this.getFilesDir().getAbsolutePath(), "temp_image");

    //Copy URI contents into temporary file.
    try {
        tempFile.createNewFile();
        copyAndClose(this.getContentResolver().openInputStream(data.getData()),new FileOutputStream(tempFile));
    }
    catch (IOException e) {
        //Log Error
    }

    //Now fetch the new URI
    Uri newUri = Uri.fromFile(tempFile);

    /* Use new URI object just like you used to */
 }

Note - copyAndClose() just does file I/O to copy InputStream into a FileOutputStream. The code is not posted.

How to set timeout in Retrofit library?

public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }`enter code here`

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}


-------------------------------------------------------------------------


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

__proto__ VS. prototype in JavaScript

To make it a little bit clear in addition to above great answers:

function Person(name){
    this.name = name
 }; 

var eve = new Person("Eve");

eve.__proto__ == Person.prototype //true

eve.prototype  //undefined

Instances have __proto__, classes have prototype.

POST Content-Length exceeds the limit

post_max_size should be slightly bigger than upload_max_filesize, because when uploading using HTTP POST method the text also includes headers with file size and name, etc.

If you want to successfully uppload 1GiB files, you have to set:

upload_max_filesize = 1024M
post_max_size = 1025M

Note, the correct suffix for GB is G, i.e. upload_max_filesize = 1G.

No need to set memory_limit.

How do I remove time part from JavaScript date?

The previous answers are fine, just adding my preferred way of handling this:

var timePortion = myDate.getTime() % (3600 * 1000 * 24);
var dateOnly = new Date(myDate - timePortion);

If you start with a string, you first need to parse it like so:

var myDate = new Date(dateString);

And if you come across timezone related problems as I have, this should fix it:

var timePortion = (myDate.getTime() - myDate.getTimezoneOffset() * 60 * 1000) % (3600 * 1000 * 24);

Insert a new row into DataTable

// create table
var dt = new System.Data.DataTable("tableName");

// create fields
dt.Columns.Add("field1", typeof(int));
dt.Columns.Add("field2", typeof(string));
dt.Columns.Add("field3", typeof(DateTime));

// insert row values
dt.Rows.Add(new Object[]{
                123456,
                "test",
                DateTime.Now
           });

How do I implement a progress bar in C#?

When you perform operations on Background thread and you want to update UI, you can not call or set anything from background thread. In case of WPF you need Dispatcher.BeginInvoke and in case of WinForms you need Invoke method.

WPF:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Dispatcher.BeginInvoke((Action)delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

WinForms:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Invoke(delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

for WinForms delegate may require some casting or you may need little help there, dont remember the exact syntax now.

How to solve error: "Clock skew detected"?

One of the reason may be improper date/time of your PC.

In Ubuntu PC to check the date and time using:

date

Example, One of the ways to update date and time is:

date -s "23 MAR 2017 17:06:00"

Convert long/lat to pixel x/y on a given picture

You will have to implement the Google Maps API projection in your language. I have the C# source code for this:

public class GoogleMapsAPIProjection
{
    private readonly double PixelTileSize = 256d;
    private readonly double DegreesToRadiansRatio = 180d / Math.PI;
    private readonly double RadiansToDegreesRatio = Math.PI / 180d;
    private readonly PointF PixelGlobeCenter;
    private readonly double XPixelsToDegreesRatio;
    private readonly double YPixelsToRadiansRatio;

    public GoogleMapsAPIProjection(double zoomLevel)
    {
        var pixelGlobeSize = this.PixelTileSize * Math.Pow(2d, zoomLevel);
        this.XPixelsToDegreesRatio = pixelGlobeSize / 360d;
        this.YPixelsToRadiansRatio = pixelGlobeSize / (2d * Math.PI);
        var halfPixelGlobeSize = Convert.ToSingle(pixelGlobeSize / 2d);
        this.PixelGlobeCenter = new PointF(
            halfPixelGlobeSize, halfPixelGlobeSize);
    }

    public PointF FromCoordinatesToPixel(PointF coordinates)
    {
        var x = Math.Round(this.PixelGlobeCenter.X
            + (coordinates.X * this.XPixelsToDegreesRatio));
        var f = Math.Min(
            Math.Max(
                 Math.Sin(coordinates.Y * RadiansToDegreesRatio),
                -0.9999d),
            0.9999d);
        var y = Math.Round(this.PixelGlobeCenter.Y + .5d * 
            Math.Log((1d + f) / (1d - f)) * -this.YPixelsToRadiansRatio);
        return new PointF(Convert.ToSingle(x), Convert.ToSingle(y));
    }

    public PointF FromPixelToCoordinates(PointF pixel)
    {
        var longitude = (pixel.X - this.PixelGlobeCenter.X) /
            this.XPixelsToDegreesRatio;
        var latitude = (2 * Math.Atan(Math.Exp(
            (pixel.Y - this.PixelGlobeCenter.Y) / -this.YPixelsToRadiansRatio))
            - Math.PI / 2) * DegreesToRadiansRatio;
        return new PointF(
            Convert.ToSingle(latitude),
            Convert.ToSingle(longitude));
    }
}

Source:

http://code.google.com/p/geographical-dot-net/source/browse/trunk/GeographicalDotNet/GeographicalDotNet/Projection/GoogleMapsAPIProjection.cs

cor shows only NA or 1 for correlations - Why?

very simple and correct answer

Tell the correlation to ignore the NAs with use argument, e.g.:

cor(data$price, data$exprice, use = "complete.obs")

Getting list of files in documents folder

Simple and dynamic solution (Swift 5):

extension FileManager {

  class func directoryUrl() -> URL? {
      let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
      return paths.first
  }

  class func allRecordedData() -> [URL]? {
     if let documentsUrl = FileManager.directoryUrl() {
        do {
            let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
            return directoryContents.filter{ $0.pathExtension == "m4a" }
        } catch {
            return nil
        }
     }
     return nil
  }}

How to handle invalid SSL certificates with Apache HttpClient?

I happened to face the same issue, all of a sudden all my imports were missing. I tried deleting all the contents in my .m2 folder. And trying to re-import everything , but still nothing worked. Finally what I did was opened the website for which the IDE was complaining that it couldn't download in my browser. And saw the certificate it was using, and saw in my

$ keytool -v -list  PATH_TO_JAVA_KEYSTORE

Path to my keystore was /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts

that particular certificate was not there.

So all you have to do is put the certificate into the JAVA JVM keystore again. It can be done using the below command.

$ keytool -import -alias ANY_NAME_YOU_WANT_TO_GIVE -file PATH_TO_YOUR_CERTIFICATE -keystore PATH_OF_JAVA_KEYSTORE

If it asks for password, try the default password 'changeit' If you get permission error when running the above command. In windows open it in administration mode. In mac and unix use sudo.

After you have successfully added the key, You can view it using :

$ keytool -v -list  /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts 

You can view just the SHA-1 using teh command

$ keytool -list  /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts 

Protecting cells in Excel but allow these to be modified by VBA script

You can modify a sheet via code by taking these actions

  • Unprotect
  • Modify
  • Protect

In code this would be:

Sub UnProtect_Modify_Protect()

  ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="Password"
'Unprotect

  ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify

  ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password"
'Protect

End Sub

The weakness of this method is that if the code is interrupted and error handling does not capture it, the worksheet could be left in an unprotected state.

The code could be improved by taking these actions

  • Re-protect
  • Modify

The code to do this would be:

Sub Re-Protect_Modify()

ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
 UserInterfaceOnly:=True
'Protect, even if already protected

  ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify

End Sub

This code renews the protection on the worksheet, but with the ‘UserInterfaceOnly’ set to true. This allows VBA code to modify the worksheet, while keeping the worksheet protected from user input via the UI, even if execution is interrupted.

This setting is lost when the workbook is closed and re-opened. The worksheet protection is still maintained.

So the 'Re-protection' code needs to be included at the start of any procedure that attempts to modify the worksheet or can just be run once when the workbook is opened.

Recursive Fibonacci

int fib(int x) 
{
    if (x == 0)
      return 0;
    else if (x == 1 || x == 2) 
      return 1;
    else 
      return (fib(x - 1) + fib(x - 2));
}

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

Convert a String representation of a Dictionary to a dictionary?

using json.loads:

>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> d = json.loads(h)
>>> d
{u'foo': u'bar', u'foo2': u'bar2'}
>>> type(d)
<type 'dict'>

Nullable type as a generic parameter possible?

Disclaimer: This answer works, but is intended for educational purposes only. :) James Jones' solution is probably the best here and certainly the one I'd go with.

C# 4.0's dynamic keyword makes this even easier, if less safe:

public static dynamic GetNullableValue(this IDataRecord record, string columnName)
{
  var val = reader[columnName];

  return (val == DBNull.Value ? null : val);
}

Now you don't need the explicit type hinting on the RHS:

int? value = myDataReader.GetNullableValue("MyColumnName");

In fact, you don't need it anywhere!

var value = myDataReader.GetNullableValue("MyColumnName");

value will now be an int, or a string, or whatever type was returned from the DB.

The only problem is that this does not prevent you from using non-nullable types on the LHS, in which case you'll get a rather nasty runtime exception like:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert null to 'int' because it is a non-nullable value type

As with all code that uses dynamic: caveat coder.

How to Sign an Already Compiled Apk

Automated Process:

Use this tool (uses the new apksigner from Google):

https://github.com/patrickfav/uber-apk-signer

Disclaimer: Im the developer :)

Manual Process:

Step 1: Generate Keystore (only once)

You need to generate a keystore once and use it to sign your unsigned apk. Use the keytool provided by the JDK found in %JAVA_HOME%/bin/

keytool -genkey -v -keystore my.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias app

Step 2 or 4: Zipalign

zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimization step if you want to upload the apk to the Play Store.

zipalign -p 4 my.apk my-aligned.apk

Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner).

You can verify the alignment with

zipalign -c 4 my-aligned.apk

Step 3: Sign & Verify

Using build-tools 24.0.2 and older

Use jarsigner which, like the keytool, comes with the JDK distribution found in %JAVA_HOME%/bin/ and use it like so:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore my-app.apk my_alias_name

and can be verified with

jarsigner -verify -verbose my_application.apk

Using build-tools 24.0.3 and newer

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files (See here and here for more details). Therefore, Google implemented their own apk signer called apksigner (duh!) The script file can be found in %ANDROID_HOME%/sdk/build-tools/24.0.3/ (the .jar is in the /lib subfolder). Use it like this

apksigner sign --ks my.keystore my-app.apk --ks-key-alias alias_name

and can be verified with

apksigner verify my-app.apk

The official documentation can be found here.

Expand and collapse with angular js

You can solve this fully in the html:

<div>
  <input ng-model=collapse type=checkbox>Title
  <div ng-show=collapse>
     Only shown when checkbox is clicked
  </div>
</div>

This also works well with ng-repeat since it will create a local scope for each member.

<table>
  <tbody ng-repeat='m in members'>
    <tr>
       <td><input type=checkbox ng-model=collapse></td>
       <td>{{m.title}}</td>
    </tr>
    <tr ng-show=collapse>
      <td> </td>
      <td>{{ m.content }}</td>
    </tr>
  </tbody>
</table>

Be aware that even though a repeat has its own scope, initially it will inherit the value from collapse from super scopes. This allows you to set the initial value in one place but it can be surprising.

You can of course restyle the checkbox. See http://jsfiddle.net/azD5m/5/

Updated fiddle: http://jsfiddle.net/azD5m/374/ Original fiddle used closing </input> tags to add the HTML text label instead of using <label> tags.

What is the role of the package-lock.json?

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.

{
    "name": "mobileapp",
    "version": "1.0.0",
    "lockfileVersion": 1,
    "requires": true,
    "dependencies": {
    "@angular-devkit/architect": {
      "version": "0.11.4",
      "resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
      "integrity": "sha512-2zi6S9tPlk52vyqNFg==",
      "dev": true,
      "requires": {
        "@angular-devkit/core": "7.1.4",
        "rxjs": "6.3.3"
      }
    },
}       

What is log4j's default log file dumping path

You have copy this sample code from Here,right?
now, as you can see there property file they have define, have you done same thing? if not then add below code in your project with property file for log4j

So the content of log4j.properties file would be as follows:

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

make changes as per your requirement like log path

How to redirect a page using onclick event in php?

you are using onclick which is javascript event. there is two ways

Javascript

<input type="button" value="Home" class="homebutton" id="btnHome" 
onClick="window.location = 'http://google.com'" />

Or PHP

create another page as redirect.php and put

<?php header('location : google.com') ?>

and insert this link on any page within the same directory

<a href="redirect.php">google<a/>

hope this helps its simplest!!

Python class returning value

Use __new__ to return value from a class.

As others suggest __repr__,__str__ or even __init__ (somehow) CAN give you what you want, But __new__ will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.

Read this answer for more insights into __str__ and __repr__ https://stackoverflow.com/a/19331543/4985585

class MyClass():
    def __new__(cls):
        return list() #or anything you want

>>> MyClass()
[]   #Returns a true list not a repr or string

What does [object Object] mean? (JavaScript)

It means you are alerting an instance of an object. When alerting the object, toString() is called on the object, and the default implementation returns [object Object].

var objA = {};
var objB = new Object;
var objC = {};

objC.toString = function () { return "objC" };

alert(objA); // [object Object]
alert(objB); // [object Object]
alert(objC); // objC

If you want to inspect the object, you should either console.log it, JSON.stringify() it, or enumerate over it's properties and inspect them individually using for in.

Is there a label/goto in Python?

It is technically feasible to add a 'goto' like statement to python with some work. We will use the "dis" and "new" modules, both very useful for scanning and modifying python byte code.

The main idea behind the implementation is to first mark a block of code as using "goto" and "label" statements. A special "@goto" decorator will be used for the purpose of marking "goto" functions. Afterwards we scan that code for these two statements and apply the necessary modifications to the underlying byte code. This all happens at source code compile time.

import dis, new

def goto(fn):
    """
    A function decorator to add the goto command for a function.

        Specify labels like so:
        label .foo

        Goto labels like so:
        goto .foo

        Note: you can write a goto statement before the correspnding label statement
    """
    labels = {}
    gotos = {}
    globalName = None
    index = 0
    end = len(fn.func_code.co_code)
    i = 0

    # scan through the byte codes to find the labels and gotos
    while i < end:
        op = ord(fn.func_code.co_code[i])
        i += 1
        name = dis.opname[op]

        if op > dis.HAVE_ARGUMENT:
            b1 = ord(fn.func_code.co_code[i])
            b2 = ord(fn.func_code.co_code[i+1])
            num = b2 * 256 + b1

            if name == 'LOAD_GLOBAL':
                globalName = fn.func_code.co_names[num]
                index = i - 1
                i += 2
                continue

            if name == 'LOAD_ATTR':
                if globalName == 'label':
                    labels[fn.func_code.co_names[num]] = index
                elif globalName == 'goto':
                    gotos[fn.func_code.co_names[num]] = index

            name = None
            i += 2

    # no-op the labels
    ilist = list(fn.func_code.co_code)
    for label,index in labels.items():
        ilist[index:index+7] = [chr(dis.opmap['NOP'])]*7

    # change gotos to jumps
    for label,index in gotos.items():
        if label not in labels:
            raise Exception("Missing label: %s"%label)

        target = labels[label] + 7   # skip NOPs
        ilist[index] = chr(dis.opmap['JUMP_ABSOLUTE'])
        ilist[index + 1] = chr(target & 255)
        ilist[index + 2] = chr(target >> 8)

    # create new function from existing function
    c = fn.func_code
    newcode = new.code(c.co_argcount,
                       c.co_nlocals,
                       c.co_stacksize,
                       c.co_flags,
                       ''.join(ilist),
                       c.co_consts,
                       c.co_names,
                       c.co_varnames,
                       c.co_filename,
                       c.co_name,
                       c.co_firstlineno,
                       c.co_lnotab)
    newfn = new.function(newcode,fn.func_globals)
    return newfn


if __name__ == '__main__':

    @goto
    def test1():
        print 'Hello' 

        goto .the_end
        print 'world'

        label .the_end
        print 'the end'

    test1()

Hope this answers the question.

Export SQL query data to Excel

I see that you’re trying to export SQL data to Excel to avoid copy-pasting your very large data set into Excel.

You might be interested in learning how to export SQL data to Excel and update the export automatically (with any SQL database: MySQL, Microsoft SQL Server, PostgreSQL).

To export data from SQL to Excel, you need to follow 2 steps:

  • Step 1: Connect Excel to your SQL database? (Microsoft SQL Server, MySQL, PostgreSQL...)
  • Step 2: Import your SQL data into Excel

The result will be the list of tables you want to query data from your SQL database into Excel:

?

Step1: Connect Excel to an external data source: your SQL database

  1. Install An ODBC
  2. Install A Driver
  3. Avoid A Common Error
  4. Create a DSN

Step 2: Import your SQL data into Excel

  1. Click Where You Want Your Pivot Table
  2. Click Insert
  3. Click Pivot Table
  4. Click Use an external data source, then Choose Connection
  5. Click on the System DSN tab
  6. Select the DSN created in ODBC Manager
  7. Fill the requested username and password
  8. Avoid a Common Error
  9. Access The Microsoft Query Dialog Box
  10. Click on the arrow to see the list of tables in your database
  11. Select the table you want to query data from your SQL database into Excel
  12. Click on Return Data when you’re done with your selection

To update the export automatically, there are 2 additional steps:

  1. Create a Pivot Table with an external SQL data source
  2. Automate Your SQL Data Update In Excel With The GETPIVOTDATA Function

I’ve created a step-by-step tutorial about this whole process, from connecting Excel to SQL, up to having the whole thing automatically updated. You might find the detailed explanations and screenshots useful.

How can I calculate an md5 checksum of a directory?

If you want one md5sum spanning the whole directory, I would do something like

cat *.py | md5sum 

How to import an Oracle database from dmp file and log file?

If you are using impdp command example from @sathyajith-bhat response:

impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;

you will need to use mandatory parameter directory and create and grant it as:

CREATE OR REPLACE DIRECTORY DMP_DIR AS 'c:\Users\USER\Downloads';
GRANT READ, WRITE ON DIRECTORY DMP_DIR TO {USER};

or use one of defined:

select * from DBA_DIRECTORIES;

My ORACLE Express 11g R2 has default named DATA_PUMP_DIR (located at {inst_dir}\app\oracle/admin/xe/dpdump/) you sill need to grant it for your user.

How can I set a cookie in react?

By default, when you fetch your URL, React native sets the cookie.

To see cookies and make sure that you can use the https://www.npmjs.com/package/react-native-cookie package. I used to be very satisfied with it.

Of course, Fetch does this when it does

credentials: "include",// or "some-origin"

Well, but how to use it

--- after installation this package ----

to get cookies:

import Cookie from 'react-native-cookie';

Cookie.get('url').then((cookie) => {
   console.log(cookie);
});

to set cookies:

Cookie.set('url', 'name of cookies', 'value  of cookies');

only this

But if you want a few, you can do it

1- as nested:

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1')
        .then(() => {
            Cookie.set('url', 'name of cookies 2', 'value  of cookies 2')
            .then(() => {
                ...
            })
        })

2- as back together

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1');
Cookie.set('url', 'name of cookies 2', 'value  of cookies 2');
Cookie.set('url', 'name of cookies 3', 'value  of cookies 3');
....

Now, if you want to make sure the cookies are set up, you can get it again to make sure.

Cookie.get('url').then((cookie) => {
  console.log(cookie);
});

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Split string on whitespace in Python

Using split() will be the most Pythonic way of splitting on a string.

It's also useful to remember that if you use split() on a string that does not have a whitespace then that string will be returned to you in a list.

Example:

>>> "ark".split()
['ark']

How can I hide or encrypt JavaScript code?

You can obfuscate it, but there's no way of protecting it completely.

example obfuscator: https://obfuscator.io

How to place a JButton at a desired location in a JFrame using Java

Following line should be called before you add your component

pnlButton.setLayout(null);

Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds method.

In general I wouldn't recommend using absolute layout.

How to Find the Default Charset/Encoding in Java?

I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.

setTimeout / clearTimeout problems

Practical example Using Jquery for a dropdown menu ! On mouse over on #IconLoggedinUxExternal shows div#ExternalMenuLogin and set time out to hide the div#ExternalMenuLogin

On mouse over on div#ExternalMenuLogin it cancels the timeout. On mouse out on div#ExternalMenuLogin it sets the timeout.

The point here is always to invoke clearTimeout before set the timeout, as so, avoiding double calls

var ExternalMenuLoginTO;
$('#IconLoggedinUxExternal').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
    $("#ExternalMenuLogin").show()
});

$('#IconLoggedinUxExternal').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )    
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,1000
    );
    $("#ExternalMenuLogin").show()
});

$('#ExternalMenuLogin').on('mouseover mouseenter', function () {

    clearTimeout( ExternalMenuLoginTO )
});
$('#ExternalMenuLogin').on('mouseleave mouseout', function () {

    clearTimeout( ExternalMenuLoginTO )
    ExternalMenuLoginTO = setTimeout(
        function () {

            $("#ExternalMenuLogin").hide()

        }
        ,500
    );
});

There are No resources that can be added or removed from the server

I encountered this error even though the Project Facets were set appropriately. The problem was that the "Runtime Environment" property was not set on the server:

Empty Runtime Environment for Eclipse Tomcat

It simply needed to be set to the appropriate Runtime:

Runtime Environment for Eclipse Tomcat

Calculate correlation for more than two variables?

If you would like to combine the matrix with some visualisations I can recommend (I am using the built in iris dataset):

library(psych)
pairs.panels(iris[1:4])  # select columns 1-4

enter image description here

The Performance Analytics basically does the same but includes significance indicators by default.

library(PerformanceAnalytics)
chart.Correlation(iris[1:4])

Correlation Chart

Or this nice and simple visualisation:

library(corrplot)
x <- cor(iris[1:4])
corrplot(x, type="upper", order="hclust")

corrplot

How do I turn a String into a InputStreamReader in java?

I also found the apache commons IOUtils class , so :

InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN
IF THEN ELSE
IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

So your code should appear like this.

    declare
        var_number number;
    begin
        var_number := 10;
        if var_number > 100 then
           dbms_output.put_line(var_number ||' is greater than 100');
--elseif should be replaced with elsif
        elsif var_number < 100 then
           dbms_output.put_line(var_number ||' is less than 100');
        else
           dbms_output.put_line(var_number ||' is equal to 100');
        end if;
    end; 

Push local Git repo to new remote including all branches and tags

Based in @Daniel answer I did:

for remote in \`git branch | grep -v master\`
do 
    git push -u origin $remote
done

How to delete multiple files at once in Bash on Linux?

if you want to delete all files that belong to a directory at once. For example: your Directory name is "log" and "log" directory include abc.log.2012-03-14, abc.log.2012-03-15,... etc files. You have to be above the log directory and:

rm -rf /log/*

How do I update a Linq to SQL dbml file?

There are three ways to keep the model in sync.

  1. Delete the modified tables from the designer, and drag them back onto the designer surface from the Database Explorer. I have found that, for this to work reliably, you have to:

    a. Refresh the database schema in the Database Explorer (right-click, refresh)
    b. Save the designer after deleting the tables
    c. Save again after dragging the tables back.

    Note though that if you have modified any properties (for instance, turning off the child property of an association), this will obviously lose those modifications — you'll have to make them again.

  2. Use SQLMetal to regenerate the schema from your database. I have seen a number of blog posts that show how to script this.

  3. Make changes directly in the Properties pane of the DBML. This works for simple changes, like allowing nulls on a field.

The DBML designer is not installed by default in Visual Studio 2015, 2017 or 2019. You will have to close VS, start the VS installer and modify your installation. The LINQ to SQL tools is the feature you must install. For VS 2017/2019, you can find it under Individual Components > Code Tools.

3 column layout HTML/CSS

CSS:

.container {
    position: relative;
    width: 500px;
}
.container div {
    height: 300px;
}

.column-left {
    width: 33%;
    left: 0;
    background: #00F;
    position: absolute;
}
.column-center {
    width: 34%;
    background: #933;
    margin-left: 33%;
    position: absolute;
}
.column-right {
    width: 33%;
    right: 0;
    position: absolute;
    background: #999;
}

HTML:

<div class="container">
   <div class="column-center">Column center</div>
   <div class="column-left">Column left</div>
   <div class="column-right">Column right</div>
</div>

Here is the Demo : http://jsfiddle.net/nyitsol/f0dv3q3z/

Switch statement for greater-than/less-than

switch (Math.floor(scrollLeft/1000)) {
  case 0: // (<1000)
   //do stuff
   break;
  case 1: // (>=1000 && <2000)
   //do stuff;
   break;
}

Only works if you have regular steps...

EDIT: since this solution keeps getting upvotes, I must advice that mofolo's solution is a way better

Correct way to focus an element in Selenium WebDriver using Java

This code actually doesn't provide focus:

new Actions(driver).moveToElement(element).perform();

It provides a hover effect.

Additionally, the JS code .focus() requires that the window be active in order to work.

js.executeScript("element.focus();");

I have found that this code works:

element.sendKeys(Keys.SHIFT);

For my own code, I use both:

element.sendKeys(Keys.SHIFT);
js.executeScript("element.focus();");

PowerShell script to return members of multiple security groups

This is cleaner and will put in a csv.

Import-Module ActiveDirectory

$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)


$Table = @()

$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}



Foreach ($Group in $Groups)
{

$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname

foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord

}

}

$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).

At startup, we do:

TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));

And set the desired timezone to the DateFormat:

fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))

jQuery: how to trigger anchor link's click event

Even though this post is caput, I think it's an excellent demonstration of some walls that one can run into with jQuery, i.e. thinking click() actually clicks on an element, rather than just sending a click event bubbling up through the DOM. Let's say you actually need to simulate a click event (i.e. for testing purposes, etc.) If that's the case, provided that you're using a modern browser you can just use HTMLElement.prototype.click (see here for method details as well as a link to the W3 spec). This should work on almost all browsers, especially if you're dealing with links, and you can fall back to window.open pretty easily if you need to:

var clickLink = function(linkEl) {
  if (HTMLElement.prototype.click) {
    // You'll want to create a new element so you don't alter the page element's
    // attributes, unless of course the target attr is already _blank
    // or you don't need to alter anything
    var linkElCopy = $.extend(true, Object.create(linkEl), linkEl);
    $(linkElCopy).attr('target', '_blank');
    linkElCopy.click();
  } else {
    // As Daniel Doezema had said
    window.open($(linkEl).attr('href'));
  }
};

535-5.7.8 Username and Password not accepted

If you still cannot solve the problem after you turn on the less secure apps. The other possible reason which might cause this error is you are not using gmail account.

-    : user_name  =>  '[email protected]' ,  # It can not be used since it is not a gmail address 
+    : user_name  =>  '[email protected]' ,  # since it's a gmail address

Refer to here.

Also, bear in mind that it might take some times to enable the less secure apps. I have to do it several times (before it works, every time I access the link it will shows that it is off) and wait for a while until it really work.

How to find Google's IP address?

Here is a bash script that returns the IP (v4 and v6) ranges using @WorkWise's answer:

domainsToDig=$(dig @8.8.8.8 _spf.google.com TXT +short | \
    sed \
        -e 's/"v=spf1//' \
        -e 's/ ~all"//' \
        -e 's/ include:/\n/g' | \
    tail -n+2)
for domain in $domainsToDig ; do
    dig @8.8.8.8 $domain TXT +short | \
        sed \
            -e 's/"v=spf1//' \
            -e 's/ ~all"//' \
            -e 's/ ip.:/\n/g' | \
        tail -n+2
done

How to hide TabPage from TabControl

+1 for microsoft :-) .
I managed to do it this way:
(it assumes you have a Next button that displays the next TabPage - tabSteps is the name of the Tab control)
At start up, save all the tabpages in a proper list.
When user presses Next button, remove all the TabPages in the tab control, then add that with the proper index:

int step = -1;
List<TabPage> savedTabPages;

private void FMain_Load(object sender, EventArgs e) {
    // save all tabpages in the list
    savedTabPages = new List<TabPage>();
    foreach (TabPage tp in tabSteps.TabPages) {
        savedTabPages.Add(tp);
    }
    SelectNextStep();
}

private void SelectNextStep() {
    step++;
    // remove all tabs
    for (int i = tabSteps.TabPages.Count - 1; i >= 0 ; i--) {
            tabSteps.TabPages.Remove(tabSteps.TabPages[i]);
    }

    // add required tab
    tabSteps.TabPages.Add(savedTabPages[step]);
}

private void btnNext_Click(object sender, EventArgs e) {
    SelectNextStep();
}

Update

public class TabControlHelper {
    private TabControl tc;
    private List<TabPage> pages;
    public TabControlHelper(TabControl tabControl) {
        tc = tabControl;
        pages = new List<TabPage>();
        foreach (TabPage p in tc.TabPages) {
            pages.Add(p);
        }
    }

    public void HideAllPages() {
        foreach(TabPage p in pages) {
            tc.TabPages.Remove(p);
        }
    }

    public void ShowAllPages() {
        foreach (TabPage p in pages) {
            tc.TabPages.Add(p);
        }
    }

    public void HidePage(TabPage tp) {
        tc.TabPages.Remove(tp);
    }        

    public void ShowPage(TabPage tp) {
        tc.TabPages.Add(tp);
    }
}  

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

To fix this issue, I simply let Tortoise Git install its update.

How to dynamically add a class to manual class names?

Here is the Best Option for Dynamic className , just do some concatenation like we do in Javascript.

     className={
        "badge " +
        (this.state.value ? "badge-primary " : "badge-danger ") +
        " m-4"
      }

A variable modified inside a while loop is not remembered

I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value

f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
  echo $s > /dev/null;  # some work
  echo $i > 2
  let i++
done;
read -r i < 2
echo $i

Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

i=1
while read -r s;
do
  echo $s > /dev/null
  let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i

AngularJS toggle class using ng-class

Add more than one class based on the condition:

<div ng-click="AbrirPopUp(s)" 
ng-class="{'class1 class2 class3':!isNew, 
           'class1 class4': isNew}">{{ isNew }}</div>

Apply: class1 + class2 + class3 when isNew=false,

Apply: class1+ class4 when isNew=true

How can I specify the required Node.js version in package.json?

There's another, simpler way to do this:

  1. npm install Node@8 (saves Node 8 as dependency in package.json)
  2. Your app will run using Node 8 for anyone - even Yarn users!

This works because node is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.

See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360

Javascript Append Child AFTER Element

after is now a JavaScript method

MDN Documentation

Quoting MDN

The ChildNode.after() method inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just after this ChildNode. DOMString objects are inserted as equivalent Text nodes.

The browser support is Chrome(54+), Firefox(49+) and Opera(39+). It doesn't support IE and Edge.

Snippet

_x000D_
_x000D_
var elm=document.getElementById('div1');
var elm1 = document.createElement('p');
var elm2 = elm1.cloneNode();
elm.append(elm1,elm2);

//added 2 paragraphs
elm1.after("This is sample text");
//added a text content
elm1.after(document.createElement("span"));
//added an element
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
_x000D_
_x000D_

In the snippet, I used another term append too

How to retrieve the hash for the current commit in Git?

To turn arbitrary extended object reference into SHA-1, use simply git-rev-parse, for example

git rev-parse HEAD

or

git rev-parse --verify HEAD

You can also retrieve the short version like this

git rev-parse --short HEAD

Sidenote: If you want to turn references (branches and tags) into SHA-1, there is git show-ref and git for-each-ref.

Apache won't start in wamp

This solved the issue for me:

Right click on the WAMP system try icon -> Tools -> Reinstall all services

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

Android Studio - How to Change Android SDK Path

While first installation There are two situations either you have pre-installed Android SDK if you had used it in past or you have nothing at all, At a time of installation Installer always ask user how you want to configure SDK with your studio.

You can simply give a path here or browse folder where sdk is available in local system. If you already have SDK, Another option as shown in below picture at Left down corner there is a nice option for download SDK, by clicking it you can download SDK with latest release right from there,You can also use third option see in right down corner setup Android SDK for me by clicking it you can step by step set your sdk.

enter image description here

Although you can also set it up when Android shows you list of available projects, a starting prompt window shown below

enter image description here

That's pretty easy, and also sometime if you want to change your SDK you can always change it right in your Android Studio from

On windows system File --> Project Structure and then you will see SDK Location Option and from there you can set it up by providing a path or by browse it.

enter image description here

Or if you are on MAC system then from Platform settings.

enter image description here

How to write some data to excel file(.xlsx)

It is possible to write to an excel file without opening it using the Microsoft.Jet.OLEDB.4.0 and OleDb. Using OleDb, it behaves as if you were writing to a table using sql.

Here is the code I used to create and write to an new excel file. No extra references are needed

var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
using (var excelConnection = new OleDbConnection(connectionString))
{
    // The excel file does not need to exist, opening the connection will create the
    // excel file for you
    if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); }

    // data is an object so it works with DBNull.Value
    object propertyOneValue = "cool!";
    object propertyTwoValue = "testing";

    var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)";

    // Executing this command will create the worksheet inside of the workbook
    // the table name will be the new worksheet name
    using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); }

    // Add (insert) data to the worksheet
    var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)";

    using (var command = new OleDbCommand(commandText, excelConnection))
    {
        // We need to allow for nulls just like we would with
        // sql, if your data is null a DBNull.Value should be used
        // instead of null 
        command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value);
        command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value);

        command.ExecuteNonQuery();
    }
}

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :

blob.getBytes

use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0)
blob.free();

Could not load file or assembly 'System.Data.SQLite'

This is an old post, but it may help some people searching on this error to try setting "Enable 32-Bit Applications" to True for the app pool. That is what resolved the error for me. I came upon this solution by reading some the comments to @beckelmw's answer.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

I just use eco to do the job for me. eco is supported by Sprockets by default. It's a shorthand for Embedded Coffeescript which takes a eco file and compile into a Javascript template file, and the file will be treated like any other js files you have in your assets folder.

All you need to do is to create a template with extension .jst.eco and write some html code in there, and rails will automatically compile and serve the file with the assets pipeline, and the way to access the template is really easy: JST['path/to/file']({var: value}); where path/to/file is based on the logical path, so if you have file in /assets/javascript/path/file.jst.eco, you can access the template at JST['path/file']()

To make it work with angularjs, you can pass it into the template attribute instead of templateDir, and it will start working magically!

eloquent laravel: How to get a row count from a ->get()

Direct get a count of row

Using Eloquent

 //Useing Eloquent
 $count = Model::count();    

 //example            
 $count1 = Wordlist::count();

Using query builder

 //Using query builder
 $count = \DB::table('table_name')->count();

 //example
 $count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();

2 column div layout: right column with fixed width, left fluid

I have simplified it : I have edited jackjoe's answer. The height auto etc not required I think.

CSS:

#container {
position: relative;
margin:0 auto;
width: 1000px;
background: #C63;
padding: 10px;
}

#leftCol {
background: #e8f6fe;
width: auto;
}

#rightCol {
float:right;
width:30%;
background: #aafed6;
}

.box {
position:relative;
clear:both;
background:#F39;
 }
</style>

HTML:

<div id="container">

  <div id="rightCol"> 
   <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
 </div>

 <div id="leftCol">

   <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

</div>

</div>

<div class="box">
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
</div>

iPhone system font

If you're doing programatic customisation, don't hard code the system font. Use UIFont systemFontOfSize:, UIFont boldSystemFontOfSize: and UIFont italicSystemFontOfSize (Apple documentation).

This has become especially relevant since iOS 7, which changed the system font to Helvetica Neue.

This has become super especially relevant since iOS 9, which changed the system font again to San Francisco.

Highcharts - redraw() vs. new Highcharts.chart

var newData = [1,2,3,4,5,6,7];
var chart = $('#chartjs').highcharts();
chart.series[0].setData(newData, true);

Explanation:
Variable newData contains value that want to update in chart. Variable chart is an object of a chart. setData is a method provided by highchart to update data.

Method setData contains two parameters, in first parameter we need to pass new value as array and second param is Boolean value. If true then chart updates itself and if false then we have to use redraw() method to update chart (i.e chart.redraw();)

http://jsfiddle.net/NxEnH/8/

How do I ignore files in Subversion?

SVN ignore is easy to manage in TortoiseSVN. Open TortoiseSVN and right-click on file menu then select Add to ignore list.

This will add the files in the svn:ignore property. When we checking in the files then those file which is matched with svn:ignore that will be ignored and will not commit.

In Visual Studio project we have added following files to ignore:

bin obj
*.exe
*.dll
*.pdb
*.suo

We are managing source code on SVN of Comparetrap using this method successfully

TypeScript function overloading

Function overloading in typescript:

According to Wikipedia, (and many programming books) the definition of method/function overloading is the following:

In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

In typescript we cannot have different implementations of the same function that are called according to the number and type of arguments. This is because when TS is compiled to JS, the functions in JS have the following characteristics:

  • JavaScript function definitions do not specify data types for their parameters
  • JavaScript functions do not check the number of arguments when called

Therefore, in a strict sense, one could argue that TS function overloading doesn't exists. However, there are things you can do within your TS code that can perfectly mimick function overloading.

Here is an example:

function add(a: number, b: number, c: number): number;
function add(a: number, b: number): any;
function add(a: string, b: string): any;

function add(a: any, b: any, c?: any): any {
  if (c) {
    return a + c;
  }
  if (typeof a === 'string') {
    return `a is ${a}, b is ${b}`;
  } else {
    return a + b;
  }
}

The TS docs call this method overloading, and what we basically did is supplying multiple method signatures (descriptions of possible parameters and types) to the TS compiler. Now TS can figure out if we called our function correctly during compile time and give us an error if we called the function incorrectly.

How to match "any character" in regular expression?

The most common way I have seen to encode this is with a character class whose members form a partition of the set of all possible characters.

Usually people write that as [\s\S] (whitespace or non-whitespace), though [\w\W], [\d\D], etc. would all work.

.htaccess rewrite to redirect root URL to subdirectory

Try this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
RewriteRule ^$ store [L]

If you want an external redirect (which cause the visiting browser to show the redirected URL), set the R flag there as well:

RewriteRule ^$ /store [L,R=301]

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

The issue is caused by the DNS failing to resolve the hostname. Try using the IP address instead of the "computer name".

PHP date() format when inserting into datetime in MySQL

Using DateTime class in PHP7+:

function getMysqlDatetimeFromDate(int $day, int $month, int $year): string
{
 $dt = new DateTime();
 $dt->setDate($year, $month, $day);
 $dt->setTime(0, 0, 0, 0); // set time to midnight

 return $dt->format('Y-m-d H:i:s');
}

Iterating through struct fieldnames in MATLAB

You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.

>> signal
signal = 
sin: {{1x1x25 cell}  {1x1x25 cell}}
cos: {{1x1x25 cell}  {1x1x25 cell}}

>> each(fieldnames(signal))
ans = 
CellIterator with properties:

NumberOfIterations: 2.0000e+000

Usage:

for bridge = each(fieldnames(signal))
   signal.(bridge) = rand(10);
end

I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.

How to find where gem files are installed

After installing the gems, if you want to know where a particular gem is. Try typing:

 gem list

You will be able to see the list of gems you have installed. Now use bundle show and name the gem you want to know the path for, like this:

 bundle show <gemName>

Or (as of younger versions of bundler):

 bundle info <gemName>

How to sort by two fields in Java?

For those able to use the Java 8 streaming API, there is a neater approach that is well documented here: Lambdas and sorting

I was looking for the equivalent of the C# LINQ:

.ThenBy(...)

I found the mechanism in Java 8 on the Comparator:

.thenComparing(...)

So here is the snippet that demonstrates the algorithm.

    Comparator<Person> comparator = Comparator.comparing(person -> person.name);
    comparator = comparator.thenComparing(Comparator.comparing(person -> person.age));

Check out the link above for a neater way and an explanation about how Java's type inference makes it a bit more clunky to define compared to LINQ.

Here is the full unit test for reference:

@Test
public void testChainedSorting()
{
    // Create the collection of people:
    ArrayList<Person> people = new ArrayList<>();
    people.add(new Person("Dan", 4));
    people.add(new Person("Andi", 2));
    people.add(new Person("Bob", 42));
    people.add(new Person("Debby", 3));
    people.add(new Person("Bob", 72));
    people.add(new Person("Barry", 20));
    people.add(new Person("Cathy", 40));
    people.add(new Person("Bob", 40));
    people.add(new Person("Barry", 50));

    // Define chained comparators:
    // Great article explaining this and how to make it even neater:
    // http://blog.jooq.org/2014/01/31/java-8-friday-goodies-lambdas-and-sorting/
    Comparator<Person> comparator = Comparator.comparing(person -> person.name);
    comparator = comparator.thenComparing(Comparator.comparing(person -> person.age));

    // Sort the stream:
    Stream<Person> personStream = people.stream().sorted(comparator);

    // Make sure that the output is as expected:
    List<Person> sortedPeople = personStream.collect(Collectors.toList());
    Assert.assertEquals("Andi",  sortedPeople.get(0).name); Assert.assertEquals(2,  sortedPeople.get(0).age);
    Assert.assertEquals("Barry", sortedPeople.get(1).name); Assert.assertEquals(20, sortedPeople.get(1).age);
    Assert.assertEquals("Barry", sortedPeople.get(2).name); Assert.assertEquals(50, sortedPeople.get(2).age);
    Assert.assertEquals("Bob",   sortedPeople.get(3).name); Assert.assertEquals(40, sortedPeople.get(3).age);
    Assert.assertEquals("Bob",   sortedPeople.get(4).name); Assert.assertEquals(42, sortedPeople.get(4).age);
    Assert.assertEquals("Bob",   sortedPeople.get(5).name); Assert.assertEquals(72, sortedPeople.get(5).age);
    Assert.assertEquals("Cathy", sortedPeople.get(6).name); Assert.assertEquals(40, sortedPeople.get(6).age);
    Assert.assertEquals("Dan",   sortedPeople.get(7).name); Assert.assertEquals(4,  sortedPeople.get(7).age);
    Assert.assertEquals("Debby", sortedPeople.get(8).name); Assert.assertEquals(3,  sortedPeople.get(8).age);
    // Andi     : 2
    // Barry    : 20
    // Barry    : 50
    // Bob      : 40
    // Bob      : 42
    // Bob      : 72
    // Cathy    : 40
    // Dan      : 4
    // Debby    : 3
}

/**
 * A person in our system.
 */
public static class Person
{
    /**
     * Creates a new person.
     * @param name The name of the person.
     * @param age The age of the person.
     */
    public Person(String name, int age)
    {
        this.age = age;
        this.name = name;
    }

    /**
     * The name of the person.
     */
    public String name;

    /**
     * The age of the person.
     */
    public int age;

    @Override
    public String toString()
    {
        if (name == null) return super.toString();
        else return String.format("%s : %d", this.name, this.age);
    }
}

Which Android IDE is better - Android Studio or Eclipse?

The use of IDE is your personal preference. But personally if I had to choose, Eclipse is a widely known, trusted and certainly offers more features then Android Studio. Android Studio is a little new right now. May be it's upcoming versions keep up to Eclipse level soon.

How do I encode a JavaScript object as JSON?

I think you can use JSON.stringify:

// after your each loop
JSON.stringify(values);

'names' attribute must be the same length as the vector

In the spirit of @Chris W, just try to replicate the exact error you are getting. An example would have helped but maybe you're doing:

  x <- c(1,2)
  y <- c("a","b","c")
  names(x) <- y

Error in names(x) <- y : 
  'names' attribute [3] must be the same length as the vector [2]

I suspect you're trying to give names to a vector (x) that is shorter than your vector of names (y).

Does Java have an exponential operator?

There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).

Javascript "Uncaught TypeError: object is not a function" associativity question

Your code experiences a case where the Automatic Semicolon Insertion (ASI) process doesn't happen.

You should never rely on ASI. You should use semicolons to properly separate statements:

var postTypes = new Array('hello', 'there'); // <--- Place a semicolon here!!

(function() { alert('hello there') })();

Your code was actually trying to invoke the array object.

Android Material and appcompat Manifest merger failed

Create new project and compare your build.gradle files and replaced all

implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.1'

and other dependencies with the same as were in a new project someting like that

implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'

implementation 'androidx.constraintlayout:constraintlayout:1.1.2'

implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0-alpha1'

androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'

androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'

implementation 'androidx.core:core-ktx:1.0.0-alpha3'

And then fixed imports to use androidx in kotlin files.

Does Hibernate create tables in the database automatically

If property hibernate.ddl-auto = update, then it will not create the tables automatically. To create tables automatically, you need to set the property to hibernate.ddl-auto = create

The list of option which is used in the spring boot are

  • validate: validate the schema, makes no changes to the database.

  • update: update the schema.

  • create: creates the schema, destroying previous data.

  • create-drop: drop the schema at the end of the session

  • none: is all other cases

So for the first time you can set it to create and then next time on-wards you should set it to update.

Are members of a C++ struct initialized to 0 by default?

In general, no. However, a struct declared as file-scope or static in a function /will/ be initialized to 0 (just like all other variables of those scopes):

int x; // 0
int y = 42; // 42
struct { int a, b; } foo; // 0, 0

void foo() {
  struct { int a, b; } bar; // undefined
  static struct { int c, d; } quux; // 0, 0
}

What is the difference between display: inline and display: inline-block?

display: inline; is a display mode to use in a sentence. For instance, if you have a paragraph and want to highlight a single word you do:

<p>
    Pellentesque habitant morbi <em>tristique</em> senectus
    et netus et malesuada fames ac turpis egestas.
</p>

The <em> element has a display: inline; by default, because this tag is always used in a sentence. The <p> element has a display: block; by default, because it's neither a sentence nor in a sentence, it's a block of sentences.

An element with display: inline; cannot have a height or a width or a vertical margin. An element with display: block; can have a width, height and margin.
If you want to add a height to the <em> element, you need to set this element to display: inline-block;. Now you can add a height to the element and every other block style (the block part of inline-block), but it is placed in a sentence (the inline part of inline-block).

Get current clipboard content?

Following will give you the selected content as well as updating the clipboard.

Bind the element id with copy event and then get the selected text. You could replace or modify the text. Get the clipboard and set the new text. To get the exact formatting you need to set the type as "text/hmtl". You may also bind it to the document instead of element.

document.querySelector('element').bind('copy', function(event) {
  var selectedText = window.getSelection().toString(); 
  selectedText = selectedText.replace(/\u200B/g, "");

  clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
  clipboardData.setData('text/html', selectedText);

  event.preventDefault();
});

Static variables in C++

Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.

When static variable is declared in a header file is its scope limited to .h file or across all units.

There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.

As such, a static variable declared in a header file is like a static variable in each individual source file.

Since declaring a variable static this way means internal linkage, every translation unit #includeing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.

I would like to know what is the difference between static variables in a header file vs declared in a class.

In a class declaration, static means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static (or "class") variable, it's the same value for all objects. You could think of it as a "class global".

Also generally static variable is initialized in .cpp file when declared in a class right ?

Yes, one (and only one) translation unit must initialize the class variable.

So that does mean static variable scope is limited to 2 compilation units ?

As I said:

  • A header is not a compilation unit,
  • static means completely different things depending on context.

Global static limits scope to the translation unit. Class static means global to all instances.

I hope this helps.

PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )

How to set the allowed url length for a nginx request (error code: 414, uri too large)

For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;

You will need the sudo password.

sudo nano /etc/nginx/conf.d/uploads.conf

Replace contents with the following;

fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;

client_max_body_size 24M;
client_body_buffer_size 128k;

client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;

Get the last insert id with doctrine 2?

Calling flush() can potentially add lots of new entities, so there isnt really the notion of "lastInsertId". However Doctrine will populate the identity fields whenever one is generated, so accessing the id field after calling flush will always contain the ID of a newly "persisted" entity.

What's the fastest way to read a text file line-by-line?

While File.ReadAllLines() is one of the simplest ways to read a file, it is also one of the slowest.

If you're just wanting to read lines in a file without doing much, according to these benchmarks, the fastest way to read a file is the age old method of:

using (StreamReader sr = File.OpenText(fileName))
{
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null)
        {
               //do minimal amount of work here
        }
}

However, if you have to do a lot with each line, then this article concludes that the best way is the following (and it's faster to pre-allocate a string[] if you know how many lines you're going to read) :

AllLines = new string[MAX]; //only allocate memory here

using (StreamReader sr = File.OpenText(fileName))
{
        int x = 0;
        while (!sr.EndOfStream)
        {
               AllLines[x] = sr.ReadLine();
               x += 1;
        }
} //Finished. Close the file

//Now parallel process each line in the file
Parallel.For(0, AllLines.Length, x =>
{
    DoYourStuff(AllLines[x]); //do your work here
});

Android studio, gradle and NDK

We have released a first version of the integration as a preview in 1.3: http://tools.android.com/tech-docs/android-ndk-preview

The integration will stay a preview even after 1.3 becomes final. No current ETA as to when it'll be final (as of 2015/07/10).

More information here: http://tools.android.com/tech-docs/android-ndk-preview

Validating Phone Numbers Using Javascript

Try this I It's working.

_x000D_
_x000D_
<form>_x000D_
<input type="text" name="mobile" pattern="[1-9]{1}[0-9]{9}" title="Enter 10 digit mobile number" placeholder="Mobile number" required>_x000D_
<button>_x000D_
Save_x000D_
</button>_x000D_
</form>_x000D_
 
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/guljarpd/12b7v330/

Is it possible to overwrite a function in PHP

Monkey patch in namespace php >= 5.3

A less evasive method than modifying the interpreter is the monkey patch.

Monkey patching is the art of replacing the actual implementation with a similar "patch" of your own.

Ninja skills

Before you can monkey patch like a PHP Ninja we first have to understand PHPs namespaces.

Since PHP 5.3 we got introduced to namespaces which you might at first glance denote to be equivalent to something like java packages perhaps, but it's not quite the same. Namespaces, in PHP, is a way to encapsulate scope by creating a hierarchy of focus, especially for functions and constants. As this topic, fallback to global functions, aims to explain.

If you don't provide a namespace when calling a function, PHP first looks in the current namespace then moves down the hierarchy until it finds the first function declared within that prefixed namespace and executes that. For our example if you are calling print_r(); from namespace My\Awesome\Namespace; What PHP does is to first look for a function called My\Awesome\Namespace\print_r(); then My\Awesome\print_r(); then My\print_r(); until it finds the PHP built in function in the global namespace \print_r();.

You will not be able to define a function print_r($object) {} in the global namespace because this will cause a name collision since a function with that name already exists.

Expect a fatal error to the likes of:

Fatal error: Cannot redeclare print_r()

But nothing stops you, however, from doing just that within the scope of a namespace.

Patching the monkey

Say you have a script using several print_r(); calls.

Example:

<?php
     print_r($some_object);
     // do some stuff
     print_r($another_object);
     // do some other stuff
     print_r($data_object);
     // do more stuff
     print_r($debug_object);

But you later change your mind and you want the output wrapped in <pre></pre> tags instead. Ever happened to you?

Before you go and change every call to print_r(); consider monkey patching instead.

Example:

<?php
    namespace MyNamespace {
        function print_r($object) 
        {
            echo "<pre>", \print_r($object, true), "</pre>"; 
        }

        print_r($some_object);
        // do some stuff
        print_r($another_object);
        // do some other stuff
        print_r($data_object);
        // do more stuff
        print_r($debug_object);
    }

Your script will now be using MyNamespace\print_r(); instead of the global \print_r();

Works great for mocking unit tests.

nJoy!

How to dynamically create CSS class in JavaScript and apply?

Looked through the answers and the most obvious and straight forward is missing: use document.write() to write out a chunk of CSS you need.

Here is an example (view it on codepen: http://codepen.io/ssh33/pen/zGjWga):

<style>
   @import url(http://fonts.googleapis.com/css?family=Open+Sans:800);
   .d, body{ font: 3vw 'Open Sans'; padding-top: 1em; }
   .d {
       text-align: center; background: #aaf;
       margin: auto; color: #fff; overflow: hidden; 
       width: 12em; height: 5em;
   }
</style>

<script>
   function w(s){document.write(s)}
   w("<style>.long-shadow { text-shadow: ");
   for(var i=0; i<449; i++) {
      if(i!= 0) w(","); w(i+"px "+i+"px #444");
   }
   w(";}</style>");
</script> 

<div class="d">
    <div class="long-shadow">Long Shadow<br> Short Code</div>
</div>

How to grant remote access permissions to mysql server for user?

Open the /etc/mysql/mysql.conf.d/mysqld.cnf file and comment the following line:

#bind-address = 127.0.0.1

JavaScript/regex: Remove text between parentheses

Try / \([\s\S]*?\)/g

Where

(space) matches the character (space) literally

\( matches the character ( literally

[\s\S] matches any character (\s matches any whitespace character and \S matches any non-whitespace character)

*? matches between zero and unlimited times

\) matches the character ) literally

g matches globally

Code Example:

_x000D_
_x000D_
var str = "Hello, this is Mike (example)";
str = str.replace(/ \([\s\S]*?\)/g, '');
console.log(str);
_x000D_
.as-console-wrapper {top: 0}
_x000D_
_x000D_
_x000D_

How to make CSS width to fill parent?

Use the styles

left: 0px;

or/and

right: 0px;

or/and

top: 0px;

or/and

bottom: 0px;

I think for most cases that will do the job

How to implement a FSM - Finite State Machine in Java

I design & implemented a simple finite state machine example with java.

IFiniteStateMachine: The public interface to manage the finite state machine
such as add new states to the finite state machine or transit to next states by
specific actions.

interface IFiniteStateMachine {
    void setStartState(IState startState);

    void setEndState(IState endState);

    void addState(IState startState, IState newState, Action action);

    void removeState(String targetStateDesc);

    IState getCurrentState();

    IState getStartState();

    IState getEndState();

    void transit(Action action);
}

IState: The public interface to get state related info
such as state name and mappings to connected states.

interface IState {
    // Returns the mapping for which one action will lead to another state
    Map<String, IState> getAdjacentStates();

    String getStateDesc();

    void addTransit(Action action, IState nextState);

    void removeTransit(String targetStateDesc);
}

Action: the class which will cause the transition of states.

public class Action {
    private String mActionName;

    public Action(String actionName) {
        mActionName = actionName;
    }

    String getActionName() {
        return mActionName;
    }

    @Override
    public String toString() {
        return mActionName;
    }

}

StateImpl: the implementation of IState. I applied data structure such as HashMap to keep Action-State mappings.

public class StateImpl implements IState {
    private HashMap<String, IState> mMapping = new HashMap<>();
    private String mStateName;

    public StateImpl(String stateName) {
        mStateName = stateName;
    }

    @Override
    public Map<String, IState> getAdjacentStates() {
        return mMapping;
    }

    @Override
    public String getStateDesc() {
        return mStateName;
    }

    @Override
    public void addTransit(Action action, IState state) {
        mMapping.put(action.toString(), state);
    }

    @Override
    public void removeTransit(String targetStateDesc) {
        // get action which directs to target state
        String targetAction = null;
        for (Map.Entry<String, IState> entry : mMapping.entrySet()) {
            IState state = entry.getValue();
            if (state.getStateDesc().equals(targetStateDesc)) {
                targetAction = entry.getKey();
            }
        }
        mMapping.remove(targetAction);
    }

}

FiniteStateMachineImpl: Implementation of IFiniteStateMachine. I use ArrayList to keep all the states.

public class FiniteStateMachineImpl implements IFiniteStateMachine {
    private IState mStartState;
    private IState mEndState;
    private IState mCurrentState;
    private ArrayList<IState> mAllStates = new ArrayList<>();
    private HashMap<String, ArrayList<IState>> mMapForAllStates = new HashMap<>();

    public FiniteStateMachineImpl(){}
    @Override
    public void setStartState(IState startState) {
        mStartState = startState;
        mCurrentState = startState;
        mAllStates.add(startState);
        // todo: might have some value
        mMapForAllStates.put(startState.getStateDesc(), new ArrayList<IState>());
    }

    @Override
    public void setEndState(IState endState) {
        mEndState = endState;
        mAllStates.add(endState);
        mMapForAllStates.put(endState.getStateDesc(), new ArrayList<IState>());
    }

    @Override
    public void addState(IState startState, IState newState, Action action) {
        // validate startState, newState and action

        // update mapping in finite state machine
        mAllStates.add(newState);
        final String startStateDesc = startState.getStateDesc();
        final String newStateDesc = newState.getStateDesc();
        mMapForAllStates.put(newStateDesc, new ArrayList<IState>());
        ArrayList<IState> adjacentStateList = null;
        if (mMapForAllStates.containsKey(startStateDesc)) {
            adjacentStateList = mMapForAllStates.get(startStateDesc);
            adjacentStateList.add(newState);
        } else {
            mAllStates.add(startState);
            adjacentStateList = new ArrayList<>();
            adjacentStateList.add(newState);
        }
        mMapForAllStates.put(startStateDesc, adjacentStateList);

        // update mapping in startState
        for (IState state : mAllStates) {
            boolean isStartState = state.getStateDesc().equals(startState.getStateDesc());
            if (isStartState) {
                startState.addTransit(action, newState);
            }
        }
    }

    @Override
    public void removeState(String targetStateDesc) {
        // validate state
        if (!mMapForAllStates.containsKey(targetStateDesc)) {
            throw new RuntimeException("Don't have state: " + targetStateDesc);
        } else {
            // remove from mapping
            mMapForAllStates.remove(targetStateDesc);
        }

        // update all state
        IState targetState = null;
        for (IState state : mAllStates) {
            if (state.getStateDesc().equals(targetStateDesc)) {
                targetState = state;
            } else {
                state.removeTransit(targetStateDesc);
            }
        }

        mAllStates.remove(targetState);

    }

    @Override
    public IState getCurrentState() {
        return mCurrentState;
    }

    @Override
    public void transit(Action action) {
        if (mCurrentState == null) {
            throw new RuntimeException("Please setup start state");
        }
        Map<String, IState> localMapping = mCurrentState.getAdjacentStates();
        if (localMapping.containsKey(action.toString())) {
            mCurrentState = localMapping.get(action.toString());
        } else {
            throw new RuntimeException("No action start from current state");
        }
    }

    @Override
    public IState getStartState() {
        return mStartState;
    }

    @Override
    public IState getEndState() {
        return mEndState;
    }
}

example:

public class example {

    public static void main(String[] args) {
        System.out.println("Finite state machine!!!");
        IState startState = new StateImpl("start");
        IState endState = new StateImpl("end");
        IFiniteStateMachine fsm = new FiniteStateMachineImpl();
        fsm.setStartState(startState);
        fsm.setEndState(endState);
        IState middle1 = new StateImpl("middle1");
        middle1.addTransit(new Action("path1"), endState);
        fsm.addState(startState, middle1, new Action("path1"));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.transit(new Action(("path1")));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.addState(middle1, endState, new Action("path1-end"));
        fsm.transit(new Action(("path1-end")));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.addState(endState, middle1, new Action("path1-end"));
    }

}

Full example on Github

XPath using starts-with function

Use:

/*/ITEM[starts-with(REVENUE_YEAR,'2552')]/REGION

Note: Unless your host language can't handle element instance as result, do not use text nodes specially in mixed content data model. Do not start expressions with // operator when the schema is well known.

php, mysql - Too many connections to database error

Please check if you open up a new connection with each of your requests (mysql_connect(...)). If you do so, make sure you close the connection afterwards (using mysql_close($link)).

Also, you should consider changing this behaviour as keeping one steady connection for each user may be a better way to accomplish your task.

If you didn't already, take a look at this obvious, but nonetheless useful information resource: http://php.net/manual/function.mysql-connect.php

JUnit test for System.out.println()

You cannot directly print by using system.out.println or using logger api while using JUnit. But if you want to check any values then you simply can use

Assert.assertEquals("value", str);

It will throw below assertion error:

java.lang.AssertionError: expected [21.92] but found [value]

Your value should be 21.92, Now if you will test using this value like below your test case will pass.

 Assert.assertEquals(21.92, str);

Flutter - Wrap text on overflow, like insert ellipsis or fade

SizedBox(
    width: 200.0,
    child: Text('PRODUCERS CAVITY FIGHTER 50X140g',
                overflow: TextOverflow.ellipsis,
                style: Theme.of(context).textTheme.body2))

Just wrap in inside a widget that can take a specific width for it to work or it will assume the width of the parent container.

Bootstrap: Collapse other sections when one is expanded

For Bootstrap v4.1

Add the data-parent attribute to the collapse elements instead on the button.

<div id="myGroup">
<button class="btn dropdown" data-toggle="collapse" data-target="#keys"><i class="icon-chevron-right"></i> Keys  <span class="badge badge-info pull-right">X</span></button>
<button class="btn dropdown" data-toggle="collapse" data-target="#attrs"><i class="icon-chevron-right"></i> Attributes</button>
<button class="btn dropdown" data-toggle="collapse" data-target="#edit"><i class="icon-chevron-right"></i> Edit Details</button>

<div class="accordion-group">
    <div class="collapse indent" id="keys"  data-parent="#myGroup">
        keys
    </div>

    <div class="collapse indent" id="attrs"  data-parent="#myGroup">
        attrs
    </div>

    <div class="collapse" id="edit"  data-parent="#myGroup">
        edit
    </div>
</div>

How do I wait for a promise to finish before returning the variable of a function?

You don't want to make the function wait, because JavaScript is intended to be non-blocking. Rather return the promise at the end of the function, then the calling function can use the promise to get the server response.

var promise = query.find(); 
return promise; 

//Or return query.find(); 

How do I get the number of elements in a list?

Besides len you can also use operator.length_hint (requires Python 3.4+). For a normal list both are equivalent, but length_hint makes it possible to get the length of a list-iterator, which could be useful in certain circumstances:

>>> from operator import length_hint
>>> l = ["apple", "orange", "banana"]
>>> len(l)
3
>>> length_hint(l)
3

>>> list_iterator = iter(l)
>>> len(list_iterator)
TypeError: object of type 'list_iterator' has no len()
>>> length_hint(list_iterator)
3

But length_hint is by definition only a "hint", so most of the time len is better.

I've seen several answers suggesting accessing __len__. This is all right when dealing with built-in classes like list, but it could lead to problems with custom classes, because len (and length_hint) implement some safety checks. For example, both do not allow negative lengths or lengths that exceed a certain value (the sys.maxsize value). So it's always safer to use the len function instead of the __len__ method!

How to calculate time difference in java?

public class timeDifference {

public static void main(String[] args) {

    try {

        Date startTime = Calendar.getInstance().getTime();
        Thread.sleep(10000);
        Date endTime = Calendar.getInstance().getTime();

        long difference = endTime.getTime() - startTime.getTime();

        long differenceSeconds = difference / 1000 % 60;
        long differenceMinutes = difference / (60 * 1000) % 60;
        long differenceHours = difference / (60 * 60 * 1000) % 24;
        long differenceDays = difference / (24 * 60 * 60 * 1000);

        System.out.println(differenceDays + " days, ");
        System.out.println(differenceHours + " hours, ");
        System.out.println(differenceMinutes + " minutes, ");
        System.out.println(differenceSeconds + " seconds.");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

How to get row index number in R?

rownames(dataframe)

This will give you the index of dataframe

How to convert a String to CharSequence?

You can use

CharSequence[] cs = String[] {"String to CharSequence"};

MySQL InnoDB not releasing disk space after deleting data rows from table

There are several ways to reclaim diskspace after deleting data from table for MySQL Inodb engine

If you don't use innodb_file_per_table from the beginning, dumping all data, delete all file, recreate database and import data again is only way ( check answers of FlipMcF above )

If you are using innodb_file_per_table, you may try

  1. If you can delete all data truncate command will delete data and reclaim diskspace for you.
  2. Alter table command will drop and recreate table so it can reclaim diskspace. Therefore after delete data, run alter table that change nothing to release hardisk ( ie: table TBL_A has charset uf8, after delete data run ALTER TABLE TBL_A charset utf8 -> this command change nothing from your table but It makes mysql recreate your table and regain diskspace
  3. Create TBL_B like TBL_A . Insert select data you want to keep from TBL_A into TBL_B. Drop TBL_A, and rename TBL_B to TBL_A. This way is very effective if TBL_A and data that needed to delete is big (delete command in MySQL innodb is very bad performance)

Convert JSON format to CSV format for MS Excel

I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3 into CSV and prompt you to download/open in Excel.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JSON to CSV</title>
    <script src="scripts/json.js" type="text/javascript"></script>
    <script type="text/javascript">
    var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }

    DownloadJSON2CSV(json3.d);

    function DownloadJSON2CSV(objArray)
    {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var index in array[i]) {
                line += array[i][index] + ',';
            }

            // Here is an example where you would wrap the values in double quotes
            // for (var index in array[i]) {
            //    line += '"' + array[i][index] + '",';
            // }

            line.slice(0,line.Length-1); 

            str += line + '\r\n';
        }
        window.open( "data:text/csv;charset=utf-8," + escape(str))
    }

    </script>

</head>
<body>
    <h1>This page does nothing....</h1>
</body>
</html>

Vim and Ctags tips and tricks

Another useful plugin for C development is cscope Just as Ctags lets you jump to definitions, Cscope jumps to the calling functions.

If you have cscope in your ~/bin/ directory, add the following to your .vimrc and use g^] to go to the calling function (see :help cscope).

if has("cscope")
    set csprg=~/bin/cscope
    set csto=0
    set cst
    set nocsverb
    " add any database in current directory
    if filereadable("cscope.out")
        cs add cscope.out
        " else add database pointed to by environment
    elseif $CSCOPE_DB != ""
        cs add $CSCOPE_DB
    endif
endif

Almost forgot... Just as ctags - you have to generate (and periodically update) the database. I use the following script

select_files > cscope.files
ctags -L cscope.files
ctags -e -L cscope.files
cscope -ub -i cscope.files

Where 'select_files' is another script that extracts the list of C and header files from the Makefile. This way I index only the files actually used by the project.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

Go to the file C:\wamp\apps\phpmyadmin3.2.0.1\config.inc.php

Find the line $cfg['Servers'][$i]['password']='' and change it to

$cfg['Servers'][$i]['password']='root'

where root is the name of the password you had set in this instance

Hope this helps somebody.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

You have to disable the sandbox for Groovy in your job configuration.

Currently this is not possible for multibranch projects where the groovy script comes from the scm. For more information see https://issues.jenkins-ci.org/browse/JENKINS-28178

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

Concat a string to SELECT * MySql

If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

JSON Stringify changes time of date because of UTC

Usually you want dates to be presented to each user in his own local time-

that is why we use GMT (UTC).

Use Date.parse(jsondatestring) to get the local time string,

unless you want your local time shown to each visitor.

In that case, use Anatoly's method.

How can I represent an 'Enum' in Python?

Use the following.

TYPE = {'EAN13':   u'EAN-13',
        'CODE39':  u'Code 39',
        'CODE128': u'Code 128',
        'i25':     u'Interleaved 2 of 5',}

>>> TYPE.items()
[('EAN13', u'EAN-13'), ('i25', u'Interleaved 2 of 5'), ('CODE39', u'Code 39'), ('CODE128', u'Code 128')]
>>> TYPE.keys()
['EAN13', 'i25', 'CODE39', 'CODE128']
>>> TYPE.values()
[u'EAN-13', u'Interleaved 2 of 5', u'Code 39', u'Code 128']

I used that for Django model choices, and it looks very pythonic. It is not really an Enum, but it does the job.

How can I update npm on Windows?

You can use Chocolatey which is a package manager for windows (like apt-get for Debian Linux).

Install fresh (you might need to uninstall previously installed versions)

> choco install nodejs

Update to the latest version

> choco update nodejs

and for npm

> choco update npm

How can I subset rows in a data frame in R based on a vector of values?

If you really just want to subset each data frame by an index that exists in both data frames, you can do this with the 'match' function, like so:

data_A[match(data_B$index, data_A$index, nomatch=0),]
data_B[match(data_A$index, data_B$index, nomatch=0),]

This is, though, the same as:

data_A[data_A$index %in% data_B$index,]
data_B[data_B$index %in% data_A$index,]

Here is a demo:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data sets.
data_A <- data.frame(index=sample(1:200, 90, rep=FALSE), value=runif(90))
data_B <- data.frame(index=sample(1:200, 120, rep=FALSE), value=runif(120))

# Subset data of each data frame by the index in the other.
t_A <- data_A[match(data_B$index, data_A$index, nomatch=0),]
t_B <- data_B[match(data_A$index, data_B$index, nomatch=0),]

# Make sure they match.
data.frame(t_A[order(t_A$index),], t_B[order(t_B$index),])[1:20,]

#    index     value index.1    value.1
# 27     3 0.7155661       3 0.65887761
# 10    12 0.6049333      12 0.14362694
# 88    14 0.7410786      14 0.42021589
# 56    15 0.4525708      15 0.78101754
# 38    18 0.2075451      18 0.70277874
# 24    23 0.4314737      23 0.78218212
# 34    32 0.1734423      32 0.85508236
# 22    38 0.7317925      38 0.56426384
# 84    39 0.3913593      39 0.09485786
# 5     40 0.7789147      40 0.31248966
# 74    43 0.7799849      43 0.10910096
# 71    45 0.2847905      45 0.26787813
# 57    46 0.1751268      46 0.17719454
# 25    48 0.1482116      48 0.99607737
# 81    53 0.6304141      53 0.26721208
# 60    58 0.8645449      58 0.96920881
# 30    59 0.6401010      59 0.67371223
# 75    61 0.8806190      61 0.69882454
# 63    64 0.3287773      64 0.36918946
# 19    70 0.9240745      70 0.11350771

How to loop through elements of forms with JavaScript?

You can iterate named fields somehow like this:

let jsonObject = {};
for(let field of form.elements) {
  if (field.name) {
      jsonObject[field.name] = field.value;
  }
}

Or, if you need only submiting fields:

function formDataToJSON(form) {
  let jsonObject = {};
  let formData = new FormData(form);
  for(let field of formData) {
      jsonObject[field[0]] = field[1];
  }
  return JSON.stringify(jsonObject);
}

How to automatically indent source code?

It may be worth noting that auto-indent does not work if there are syntax errors in the document. Get rid of the red squigglies, and THEN try CTRL+K, CTRL+D, whatever...

How do I get the domain originating the request in express.js?

In Express 4.x you can use req.hostname, which returns the domain name, without port. i.e.:

// Host: "example.com:3000"
req.hostname
// => "example.com"

See: http://expressjs.com/en/4x/api.html#req.hostname

How to insert a timestamp in Oracle?

insert
into tablename (timestamp_value)
values (TO_TIMESTAMP(:ts_val, 'YYYY-MM-DD HH24:MI:SS'));

if you want the current time stamp to be inserted then:

insert
into tablename (timestamp_value)
values (CURRENT_TIMESTAMP);

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

PostgreSQL ERROR: canceling statement due to conflict with recovery

Running queries on hot-standby server is somewhat tricky — it can fail, because during querying some needed rows might be updated or deleted on primary. As a primary does not know that a query is started on secondary it thinks it can clean up (vacuum) old versions of its rows. Then secondary has to replay this cleanup, and has to forcibly cancel all queries which can use these rows.

Longer queries will be canceled more often.

You can work around this by starting a repeatable read transaction on primary which does a dummy query and then sits idle while a real query is run on secondary. Its presence will prevent vacuuming of old row versions on primary.

More on this subject and other workarounds are explained in Hot Standby — Handling Query Conflicts section in documentation.

gem install: Failed to build gem native extension (can't find header files)

My initial solution was to resolve the above errors by installing ruby-devel, patch and rubygems.

My issue was a bit different as bcrypt 3.1.11 still had issues compiling and installing on Fedora 23. I needed additional packages. So after ensuring I had the above installed, I was still having issues:

gcc: error: conftest.c: No such file or directory

gcc: error: /usr/lib/rpm/redhat/redhat-hardened-cc1: No such file or directory

From here I had to do the following:

  • I ensured that I wasn't lacking any C compiler tools sudo dnf group install "C Development Tools and Libraries"

  • Then I ran sudo dnf install redhat-rpm-config to resolve the gcc issue listed above.

You can find a write up here on Fedore Project. You may also find answers to other needs as well.

2D Euclidean vector rotations

Sounds easier to do with the standard classes:

std::complex<double> vecA(0,1);
std::complex<double> i(0,1); // 90 degrees
std::complex<double> r45(sqrt(2.0),sqrt(2.0));
vecA *= i;
vecA *= r45;

Vector rotation is a subset of complex multiplication. To rotate over an angle alpha, you multiply by std::complex<double> { cos(alpha), sin(alpha) }

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

Passing string to a function in C - with or without pointers?

Assuming that you meant to write

char *functionname(char *string[256])

Here you are declaring a function that takes an array of 256 pointers to char as argument and returns a pointer to char. Here, on the other hand,

char functionname(char string[256])

You are declaring a function that takes an array of 256 chars as argument and returns a char.

In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.

Better way to cast object to int

You can first cast object to string and then cast the string to int; for example:

string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);

this worked for me.

How do I install Python 3 on an AWS EC2 instance?

Amazon Linux now supports python36.

python36-pip is not available. So need to follow a different route.

sudo yum install python36 python36-devel python36-libs python36-tools

# If you like to have pip3.6:
curl -O https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py

Java Scanner class reading strings

It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.

Here a small change that you can do:

int nnames;
    String names[];

    System.out.print("How many names are you going to save: ");
    Scanner in = new Scanner(System.in);
    nnames = Integer.parseInt(in.nextLine());
    names = new String[nnames];

    for (int i = 0; i < names.length; i++){
            System.out.print("Type a name: ");
            names[i] = in.nextLine();
    }

MySQL date formats - difficulty Inserting a date

Looks like you've not encapsulated your string properly. Try this:

INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y');

Alternatively, you can do the following but it is not recommended. Make sure that you use STR_TO-DATE it is because when you are developing web applications you have to explicitly convert String to Date which is annoying. Use first One.

INSERT INTO custorder VALUES ('Kevin','yes'), '2012-01-01';

I'm not confident that the above SQL is valid, however, and you may want to move the date part into the brackets. If you can provide the exact error you're getting, I might be able to more directly help with the issue.

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

I had also faced the same problem and spent 3 days to dig it out.

This happens because of your wrong TNS service entry.

First check whether you are able to connect to standby database from primary database using sql > sqlplus sys@orastand as sysdba (orastand is a standby database).

If you are not able to connect then it is a problem with the service. Correct the entry of service name in TNS file at primary end.

Check standby database the same way. Make the changes here too if required.

Make sure the log_archive_dest_2 parameter has the correct service name.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

nvarchar(max) vs NText

ntext will always store its data in a separate database page, while nvarchar(max) will try to store the data within the database record itself.

So nvarchar(max) is somewhat faster (if you have text that is smaller as 8 kB). I also noticed that the database size will grow slightly slower, this is also good.

Go nvarchar(max).

Android Studio emulator does not come with Play Store for API 23

Just want to add another solution for React Native users that just need the Expo app.

  1. Install the Expo app
  2. Open you project
  3. Click Device -> Open on Android - In this stage Expo will install the expo android app and you'll be able to open it.

How would one write object-oriented code in C?

There is an example of inheritance using C in Jim Larson's 1996 talk given at the Section 312 Programming Lunchtime Seminar here: High and Low-Level C.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Convert the batch file to an exe. Try Bat To Exe Converter or Online Bat To Exe Converter, and choose the option to run it as a ghost application, i.e. no window.

How to suppress "unused parameter" warnings in C?

I've seen this style being used:

if (when || who || format || data || len);

Check if a variable exists in a list in Bash

how about

echo $list | grep -w -q $x

you could either check the output or $? of above line to make the decision.

grep -w checks on whole word patterns. Adding -q prevents echoing the list.

How do I detect the Python version at runtime?

Just in case you want to see all of the gory details in human readable form, you can use:

import platform;

print(platform.sys.version);

Output for my system:

3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56) 
[GCC 7.2.0]

Something very detailed but machine parsable would be to get the version_info object from platform.sys, instead, and then use its properties to take a predetermined course of action. For example:

import platform;

print(platform.sys.version_info)

Output on my system:

sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)

Uncaught (in promise) TypeError: Failed to fetch and Cors error

you can use solutions without adding "Access-Control-Allow-Origin": "*", if your server is already using Proxy gateway this issue will not happen because the front and backend will be route in the same IP and port in client side but for development, you need one of this three solution if you don't need extra code 1- simulate the real environment by using a proxy server and configure the front and backend in the same port

2- if you using Chrome you can use the extension called Allow-Control-Allow-Origin: * it will help you to avoid this problem

3- you can use the code but some browsers versions may not support that so try to use one of the previous solutions

the best solution is using a proxy like ngnix its easy to configure and it will simulate the real situation of the production deployment

Global variables in header file

Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol ....link :http://csapp.cs.cmu.edu/public/ch7-preview.pdf

This type of code create problem while porting.

MySQL: How to copy rows, but change a few fields?

If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;

SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO

UPDATE #TEMP
SET Column = "Changed"
GO

INSERT INTO Table
SELECT *
FROM #Temp

Printing list elements on separated lines in Python

Another good option for handling this kind of option is the pprint module, which (among other things) pretty prints long lists with one element per line:

>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)
['',
 '/usr/lib/python27.zip',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7/site-packages',
 '/usr/lib/python2.7/site-packages/PIL',
 '/usr/lib/python2.7/site-packages/gst-0.10',
 '/usr/lib/python2.7/site-packages/gtk-2.0',
 '/usr/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info',
 '/usr/lib/python2.7/site-packages/webkit-1.0']
>>> 

How to change the spinner background in Android?

spinner code:

<TextView
    android:id="@+id/spinner"
    android:gravity="bottom"
    android:layout_marginTop="16dp"
    android:background="@drawable/spinner_selector"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:paddingLeft="16dp"
    android:textSize="16sp"
    android:text="TextView" />

spinner_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/spinner_enable" android:state_enabled="true" android:state_pressed="false"  /> <!-- enable -->
    <item android:drawable="@drawable/spinner_clicked" android:state_pressed="true"  android:state_enabled="true"  />
    <item android:drawable="@drawable/spinner_disable" android:state_enabled="false" /> <!-- disable -->
</selector>

spinner_disable.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#ddf" />
            <padding android:bottom="1dp" />
        </shape>
    </item>
    <item android:bottom="1dp">
        <shape android:shape="rectangle" >
            <solid android:color="#fff" />

            <padding
                android:left="0dp"
                android:right="0dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#fff" />
        </shape>
    </item>
    <item
        android:gravity="center_vertical|right"
        android:right="8dp">
        <layer-list>
            <item
                android:width="12dp"
                android:height="12dp"
                android:bottom="10dp"
                android:gravity="center">
                <rotate
                    android:fromDegrees="45"
                    android:toDegrees="45">
                    <shape android:shape="rectangle">
                        <solid android:color="#ddf" />
                        <stroke
                            android:width="1dp"
                            android:color="#aaaaaa" />
                    </shape>
                </rotate>
            </item>
            <item
                android:width="30dp"
                android:height="10dp"
                android:bottom="21dp"
                android:gravity="center">
                <shape android:shape="rectangle">
                    <solid android:color="@android:color/white" />
                </shape>
            </item>
        </layer-list>
    </item>
</layer-list>

spinner_clicked.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#00f" />
            <padding android:bottom="1dp" />
        </shape>
    </item>
    <item android:bottom="1dp">
        <shape android:shape="rectangle" >
            <solid android:color="#fff" />

            <padding
                android:left="0dp"
                android:right="0dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#fff" />
        </shape>
    </item>
    <item
        android:gravity="center_vertical|right"
        android:right="8dp">
        <layer-list>
            <item
                android:width="12dp"
                android:height="12dp"
                android:bottom="10dp"
                android:gravity="center">
                <rotate
                    android:fromDegrees="45"
                    android:toDegrees="45">
                    <shape android:shape="rectangle">
                        <solid android:color="#00f" />
                        <stroke
                            android:width="1dp"
                            android:color="#aaaaaa" />
                    </shape>
                </rotate>
            </item>
            <item
                android:width="30dp"
                android:height="10dp"
                android:bottom="21dp"
                android:gravity="center">
                <shape android:shape="rectangle">
                    <solid android:color="@android:color/white" />
                </shape>
            </item>
        </layer-list>
    </item>
</layer-list>

spinner_enable.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape android:shape="rectangle" >
        <solid android:color="#00f" />
        <padding android:bottom="1dp" />
    </shape>
</item>
<item android:bottom="1dp">
    <shape android:shape="rectangle" >
        <solid android:color="#BBDEFB" />

        <padding
            android:left="0dp"
            android:right="0dp" />
    </shape>
</item>
<item>
    <shape android:shape="rectangle" >
        <solid android:color="#BBDEFB" />
    </shape>
</item>
<item
    android:gravity="center_vertical|right"
    android:right="8dp">
    <layer-list>
        <item
            android:width="12dp"
            android:height="12dp"
            android:bottom="10dp"
            android:gravity="center">
            <rotate
                android:fromDegrees="45"
                android:toDegrees="45">
                <shape android:shape="rectangle">
                    <solid android:color="#00f" />
                    <stroke
                        android:width="1dp"
                        android:color="#aaaaaa" />
                </shape>
            </rotate>
        </item>
        <item
            android:width="30dp"
            android:height="10dp"
            android:bottom="21dp"
            android:gravity="center">
            <shape android:shape="rectangle">
                <solid android:color="#BBDEFB" />
            </shape>
        </item>
    </layer-list>
</item>
</layer-list>

it works fine without nine-patch pictures. api 21+ enter image description here

Changing the CommandTimeout in SQL Management studio

Right click in the query pane, select Query Options... and in the Execution->General section (the default when you first open it) there is an Execution time-out setting.

Turn off constraints temporarily (MS SQL)

Disabling and Enabling All Foreign Keys

CREATE PROCEDURE pr_Disable_Triggers_v2
    @disable BIT = 1
AS
    DECLARE @sql VARCHAR(500)
        ,   @tableName VARCHAR(128)
        ,   @tableSchema VARCHAR(128)

    -- List of all tables
    DECLARE triggerCursor CURSOR FOR
        SELECT  t.TABLE_NAME AS TableName
            ,   t.TABLE_SCHEMA AS TableSchema
        FROM    INFORMATION_SCHEMA.TABLES t
        ORDER BY t.TABLE_NAME, t.TABLE_SCHEMA

    OPEN    triggerCursor
    FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
    WHILE ( @@FETCH_STATUS = 0 )
    BEGIN

        SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
        IF @disable = 1
            SET @sql = @sql + ' DISABLE TRIGGER ALL'
        ELSE
            SET @sql = @sql + ' ENABLE TRIGGER ALL'

        PRINT 'Executing Statement - ' + @sql
        EXECUTE ( @sql )

        FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema

    END

    CLOSE triggerCursor
    DEALLOCATE triggerCursor

First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:

0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missing

Inside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.

see Disabling Constraints and Triggers from MSDN Magazine

Find index of last occurrence of a sub-string using T-SQL

DECLARE @FilePath VARCHAR(50) = 'My\Super\Long\String\With\Long\Words'
DECLARE @FindChar VARCHAR(1) = '\'

SELECT LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath)) AS LastOccuredAt

Checking if a list of objects contains a property with a specific value

You can use the Enumerable.Where extension method:

var matches = myList.Where(p => p.Name == nameToExtract);

Returns an IEnumerable<SampleClass>. Assuming you want a filtered List, simply call .ToList() on the above.


By the way, if I were writing the code above today, I'd do the equality check differently, given the complexities of Unicode string handling:

var matches = myList.Where(p => String.Equals(p.Name, nameToExtract, StringComparison.CurrentCulture));

See also

from unix timestamp to datetime

Import moment js:

var fulldate = new Date(1370001284000);
var converted_date = moment(fulldate).format(");

Angularjs $http post file and form data

I had similar problem when had to upload file and send user token info at the same time. transformRequest along with forming FormData helped:

        $http({
            method: 'POST',
            url: '/upload-file',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: {
                email: Utils.getUserInfo().email,
                token: Utils.getUserInfo().token,
                upload: $scope.file
            },
            transformRequest: function (data, headersGetter) {
                var formData = new FormData();
                angular.forEach(data, function (value, key) {
                    formData.append(key, value);
                });

                var headers = headersGetter();
                delete headers['Content-Type'];

                return formData;
            }
        })
        .success(function (data) {

        })
        .error(function (data, status) {

        });

For getting file $scope.file I used custom directive:

app.directive('file', function () {
    return {
        scope: {
            file: '='
        },
        link: function (scope, el, attrs) {
            el.bind('change', function (event) {
                var file = event.target.files[0];
                scope.file = file ? file : undefined;
                scope.$apply();
            });
        }
    };
});

Html:

<input type="file" file="file" required />

How do I rename the extension for a bunch of files?

One line, no loops:

ls -1 | xargs -L 1 -I {} bash -c 'mv $1 "${1%.*}.txt"' _ {}

Example:

$ ls
60acbc4d-3a75-4090-85ad-b7d027df8145.json  ac8453e2-0d82-4d43-b80e-205edb754700.json
$ ls -1 | xargs -L 1 -I {} bash -c 'mv $1 "${1%.*}.txt"' _ {}
$ ls
60acbc4d-3a75-4090-85ad-b7d027df8145.txt  ac8453e2-0d82-4d43-b80e-205edb754700.txt

How to initailize byte array of 100 bytes in java with all 0's

The default element value of any array of primitives is already zero: false for booleans.

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

For it is fixed by using below statement in app.web.scss
    $fa-font-path:   "../../node_modules/font-awesome/fonts/" !default;
    @import "../../node_modules/font-awesome/scss/font-awesome";

MySQL date format DD/MM/YYYY select query?

for my case this worked

str_to_date(date, '%e/%m/%Y' )

Oracle query to fetch column names

  1. SELECT * FROM <SCHEMA_NAME.TABLE_NAME> WHERE ROWNUM = 0; --> Note that, this is Query Result, a ResultSet. This is exportable to other formats. And, you can export the Query Result to Text format. Export looks like below when I did SELECT * FROM SATURN.SPRIDEN WHERE ROWNUM = 0; :

    "SPRTELE_PIDM" "SPRTELE_SEQNO" "SPRTELE_TELE_CODE" "SPRTELE_ACTIVITY_DATE" "SPRTELE_PHONE_AREA" "SPRTELE_PHONE_NUMBER" "SPRTELE_PHONE_EXT" "SPRTELE_STATUS_IND" "SPRTELE_ATYP_CODE" "SPRTELE_ADDR_SEQNO" "SPRTELE_PRIMARY_IND" "SPRTELE_UNLIST_IND" "SPRTELE_COMMENT" "SPRTELE_INTL_ACCESS" "SPRTELE_DATA_ORIGIN" "SPRTELE_USER_ID" "SPRTELE_CTRY_CODE_PHONE" "SPRTELE_SURROGATE_ID" "SPRTELE_VERSION" "SPRTELE_VPDI_CODE"

  2. DESCRIBE <TABLE_NAME> --> Note: This is script output.

How can I find the maximum value and its index in array in MATLAB?

You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable.

e.g. z is your array,

>> [x, y] = max(z)

x =

7

y =

4

Here, 7 is the largest number at the 4th position(index).