Programs & Examples On #Postsharp

PostSharp is a pattern-aware extension to C# and VB, reducing boilerplate code involved in implementing design patterns. It is based on aspect-oriented programming and static analysis.

Using stored procedure output parameters in C#

In your C# code, you are using transaction for the command. Just commit the transaction and after that access your parameter value, you will get the value. Worked for me. :)

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Nothing like these two lines appears in Mike Williams' tutorial:

    wait = true;
    setTimeout("wait = true", 2000);

Here's a Version 3 port:

http://acleach.me.uk/gmaps/v3/plotaddresses.htm

The relevant bit of code is

  // ====== Geocoding ======
  function getAddress(search, next) {
    geo.geocode({address:search}, function (results,status)
      { 
        // If that was successful
        if (status == google.maps.GeocoderStatus.OK) {
          // Lets assume that the first marker is the one we want
          var p = results[0].geometry.location;
          var lat=p.lat();
          var lng=p.lng();
          // Output the data
            var msg = 'address="' + search + '" lat=' +lat+ ' lng=' +lng+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          // Create a marker
          createMarker(search,lat,lng);
        }
        // ====== Decode the error status ======
        else {
          // === if we were sending the requests to fast, try this one again and increase the delay
          if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            nextAddress--;
            delay++;
          } else {
            var reason="Code "+status;
            var msg = 'address="' + search + '" error=' +reason+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          }   
        }
        next();
      }
    );
  }

Test if string is URL encoded in PHP

@user187291 code works and only fails when + is not encoded.

I know this is very old post. But this worked to me.

$is_encoded = preg_match('~%[0-9A-F]{2}~i', $string);
if($is_encoded) {
 $string  = urlencode(urldecode(str_replace(['+','='], ['%2B','%3D'], $string)));
} else {
  $string = urlencode($string);
}

How can I delete Docker's images?

Since Docker ver. 1.13.0 (January 2017) there's the system prune command:

$ docker system prune --help

Usage:  docker system prune [OPTIONS]

Remove unused data

Options:
-a, --all     Remove all unused images not just dangling ones
-f, --force   Do not prompt for confirmation
    --help    Print usage

Difference between scaling horizontally and vertically for databases

Traditional relational databases were designed as client/server database systems. They can be scaled horizontally but the process to do so tends to be complex and error prone. NewSQL databases like NuoDB are memory-centric distributed database systems designed to scale out horizontally while maintaining the SQL/ACID properties of traditional RDBMS.

For more information on NuoDB, read their technical white paper.

Update and left outer join statements

The Left join in this query is pointless:

UPDATE md SET md.status = '3' 
FROM pd_mounting_details AS md 
LEFT OUTER JOIN pd_order_ecolid AS oe ON md.order_data = oe.id

It would update all rows of pd_mounting_details, whether or not a matching row exists in pd_order_ecolid. If you wanted to only update matching rows, it should be an inner join.

If you want to apply some condition based on the join occurring or not, you need to add a WHERE clause and/or a CASE expression in your SET clause.

how to set auto increment column with sql developer

I found this post, which looks a bit old, but I figured I'd update everyone on my new findings.

I am using Oracle SQL Developer 4.0.2.15 on Windows. Our database is Oracle 10g (version 10.2.0.1) running on Windows.

To make a column auto-increment in Oracle -

  1. Open up the database connection in the Connections tab
  2. Expand the Tables section, and right click the table that has the column you want to change to auto-increment, and select Edit...
  3. Choose the Columns section, and select the column you want to auto-increment (Primary Key column)
  4. Next, click the "Identity Column" section below the list of columns, and change type from None to "Column Sequence"
  5. Leave the default settings (or change the names of the sequence and trigger if you'd prefer) and then click OK

Your id column (primary key) will now auto-increment, but the sequence will be starting at 1. If you need to increment the id to a certain point, you'll have to run a few alter statements against the sequence.
This post has some more details and how to overcome this.

I found the solution here

handle textview link click in my android app

Here is a more generic solution based on @Arun answer

public abstract class TextViewLinkHandler extends LinkMovementMethod {

    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_UP)
            return super.onTouchEvent(widget, buffer, event);

        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
        if (link.length != 0) {
            onLinkClick(link[0].getURL());
        }
        return true;
    }

    abstract public void onLinkClick(String url);
}

To use it just implement onLinkClick of TextViewLinkHandler class. For instance:

    textView.setMovementMethod(new TextViewLinkHandler() {
        @Override
        public void onLinkClick(String url) {
            Toast.makeText(textView.getContext(), url, Toast.LENGTH_SHORT).show();
        }
    });

Eclipse: Enable autocomplete / content assist

  1. window->preferences->java->Editor->Contest Assist
  2. Enter in Auto activation triggers for java:
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._
  3. Apply and Close

other method:
type initial letter then ctrl+spacebar for auto-complete options.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Simply :

$(".leaderMultiSelctdropdown").val()

how does Array.prototype.slice.call() work?

First, you should read how function invocation works in JavaScript. I suspect that alone is enough to answer your question. But here's a summary of what is happening:

Array.prototype.slice extracts the slice method from Array's prototype. But calling it directly won't work, as it's a method (not a function) and therefore requires a context (a calling object, this), otherwise it would throw Uncaught TypeError: Array.prototype.slice called on null or undefined.

The call() method allows you to specify a method's context, basically making these two calls equivalent:

someObject.slice(1, 2);
slice.call(someObject, 1, 2);

Except the former requires the slice method to exist in someObject's prototype chain (as it does for Array), whereas the latter allows the context (someObject) to be manually passed to the method.

Also, the latter is short for:

var slice = Array.prototype.slice;
slice.call(someObject, 1, 2);

Which is the same as:

Array.prototype.slice.call(someObject, 1, 2);

How to use vagrant in a proxy environment?

On a Windows host

open a CMD prompt;

set HTTP_PROXY=http://proxy.yourcorp.com:80
set HTTPS_PROXY=https://proxy.yourcorp.com:443

Substitute the address and port in the above snippets to whatever is appropriate for your situation. The above will remain set until you close the CMD prompt. If it works for you, consider adding them permanently to your environment variables so that you won't have to set them every time you open a new CMD prompt.

Listing only directories in UNIX

use this to get a list of directory

ls -d */ | sed -e "s/\///g"

jQuery - Disable Form Fields

The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true);

And to enable again you could do

$myForm.find(':input:disabled').prop('disabled',false);

How to group by week in MySQL?

Just ad this in the select :

DATE_FORMAT($yourDate, \'%X %V\') as week

And

group_by(week);

How to position two elements side by side using CSS

None of these solutions seem to work if you increase the amount of text so it is larger than the width of the parent container, the element to the right still gets moved below the one to the left instead of remaining next to it. To fix this, you can apply this style to the left element:

position: absolute;
width: 50px;

And apply this style to the right element:

margin-left: 50px;

Just make sure that the margin-left for the right element is greater than or equal to the width of the left element. No floating or other attributes are necessary. I would suggest wrapping these elements in a div with the style:

display: inline-block;

Applying this style may not be necessary depending on surrounding elements

Fiddle: http://jsfiddle.net/2b0bqqse/

You can see the text to the right is taller than the element to the left outlined in black. If you remove the absolute positioning and margin and instead use float as others have suggested, the text to the right will drop down below the element to the left

Fiddle: http://jsfiddle.net/qrx78u20/

Passing an array using an HTML form hidden element

You can do it like this:

<input type="hidden" name="result" value="<?php foreach($postvalue as $value) echo $postvalue.","; ?>">

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

You can add one Section(with zero rows) above, then set the above sectionFooterView as current section's headerView, footerView doesn't float. Hope it gives a help.

jquery clear input default value

Try that:

  var defaultEmailNews = "Email address";
  $('input[name=email]').focus(function() {
    if($(this).val() == defaultEmailNews) $(this).val("");
  });

  $('input[name=email]').focusout(function() {
    if($(this).val() == "") $(this).val(defaultEmailNews);
  });

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

How to validate phone number using PHP?

Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

You don't have permission to access / on this server

Create index.html or index.php file in root directory (in your case - /var/www/html, as @jabaldonedo mentioned)

git pull from master into the development branch

This Worked for me. For getting the latest code from master to my branch

git rebase origin/master

How to reset sequence in postgres and fill id column with new data?

To retain order of the rows:

UPDATE thetable SET rowid=col_serial FROM 
(SELECT rowid, row_number() OVER ( ORDER BY lngid) AS col_serial FROM thetable ORDER BY lngid) AS t1 
WHERE thetable.rowid=t1.rowid;

Clicking at coordinates without identifying element

I used the Actions Class like many listed above, but what I found helpful was if I need find a relative position from the element I used Firefox Add-On Measurit to get the relative coordinates. For example:

        IWebDriver driver = new FirefoxDriver();
        driver.Url = @"https://scm.commerceinterface.com/accounts/login/?next=/remittance_center/";
        var target = driver.FindElement(By.Id("loginAsEU"));
        Actions builder = new Actions(driver);            
        builder.MoveToElement(target , -375  , -436).Click().Build().Perform();

I got the -375, -436 from clicking on an element and then dragging backwards until I reached the point I needed to click. The coordinates that MeasureIT said I just subtracted. In my example above, the only element I had on the page that was clickable was the "loginAsEu" link. So I started from there.

Remove folder and its contents from git/GitHub's history

It appears that the up-to-date answer to this is to not use filter-branch directly (at least git itself does not recommend it anymore), and defer that work to an external tool. In particular, git-filter-repo is currently recommended. The author of that tool provides arguments on why using filter-branch directly can lead to issues.

Most of the multi-line scripts above to remove dir from the history could be re-written as:

git filter-repo --path dir --invert-paths

The tool is more powerful than just that, apparently. You can apply filters by author, email, refname and more (full manpage here). Furthermore, it is fast. Installation is easy - it is distributed in a variety of formats.

Rotating videos with FFmpeg

If you're getting a "Codec is experimental but experimental codecs are not enabled" error use this :

ffmpeg -i inputFile -vf "transpose=1" -c:a copy outputFile

Happened with me for some .mov file with aac audio.

c# foreach (property in object)... Is there a simple way of doing this?

I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.

   private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
    {
        List<string> returnValue = new List<string>();
        try
        {
            int index = userPrincipalName.IndexOf("@");
            string originatingServer = userPrincipalName.Remove(0, index + 1);
            string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
            DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
            var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
            objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
            SearchResultCollection properties = objSearcher.FindAll();

            ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
            foreach (string resProperty in resPropertyCollection)
            {
                returnValue.Add(resProperty);
            }
        }
        catch (Exception ex)
        {
            returnValue.Add(ex.Message);
            throw;
        }

        return returnValue;
    }

How to put a delay on AngularJS instant search?

I think the easiest way here is to preload the json or load it once on$dirty and then the filter search will take care of the rest. This'll save you the extra http calls and its much faster with preloaded data. Memory will hurt, but its worth it.

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

Calculate a MD5 hash from a string

Was trying to create a string representation of MD5 hash using LINQ, however, none of the answers were LINQ solutions, therefore adding this to the smorgasbord of available solutions.

string result;
using (MD5 hash = MD5.Create())
{
    result = String.Join
    (
        "",
        from ba in hash.ComputeHash
        (
            Encoding.UTF8.GetBytes(observedText)
        ) 
        select ba.ToString("x2")
    );
}

JavaScript - Get Portion of URL Path

If this is the current url use window.location.pathname otherwise use this regular expression:

var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

Difference between @click and v-on:click Vuejs

v-bind and v-on are two frequently used directives in vuejs html template. So they provided a shorthand notation for the both of them as follows:

You can replace v-on: with @

v-on:click='someFunction'

as:

@click='someFunction'

Another example:

v-on:keyup='someKeyUpFunction'

as:

@keyup='someKeyUpFunction'

Similarly, v-bind with :

v-bind:href='var1'

Can be written as:

:href='var1'

Hope it helps!

How do I make a C++ macro behave like a function?

There is a rather clever solution:

#define MACRO(X,Y)                         \
do {                                       \
  cout << "1st arg is:" << (X) << endl;    \
  cout << "2nd arg is:" << (Y) << endl;    \
  cout << "Sum is:" << ((X)+(Y)) << endl;  \
} while (0)

Now you have a single block-level statement, which must be followed by a semicolon. This behaves as expected and desired in all three examples.

NULL value for int in Update statement

By using NULL without any quotes.

UPDATE `tablename` SET `fieldName` = NULL;

Using the "With Clause" SQL Server 2008

Try the sp_foreachdb procedure.

Python strptime() and timezones?

Since strptime returns a datetime object which has tzinfo attribute, We can simply replace it with desired timezone.

>>> import datetime

>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'

How to overcome root domain CNAME restrictions?

I don't know how they are getting away with it, or what negative side effects their may be, but I'm using Hover.com to host some of my domains, and recently setup the apex of my domain as a CNAME there. Their DNS editing tool did not complain at all, and my domain happily resolves via the CNAME assigned.

Here is what Dig shows me for this domain (actual domain obfuscated as mydomain.com):

; <<>> DiG 9.8.3-P1 <<>> mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2056
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;mydomain.com.          IN  A

;; ANSWER SECTION:
mydomain.com.       394 IN  CNAME   myapp.parseapp.com.
myapp.parseapp.com. 300 IN  CNAME   parseapp.com.
parseapp.com.       60  IN  A   54.243.93.102

Creating a search form in PHP to search a database?

You're getting errors 'table liam does not exist' because the table's name is Liam which is not the same as liam. MySQL table names are case sensitive.

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

It's because there can only be one definition of A::a that all the translation units use.

If you performed static int a = 3; in a class in a header included in all a translation units then you'd get multiple definitions. Therefore, non out-of-line definition of a static is forcibly made a compiler error.

Using static inline or static const remedies this. static inline only concretises the symbol if it is used in the translation unit and ensures the linker only selects and leaves one copy if it's defined in multiple translation units due to it being in a comdat group. const at file scope makes the compiler never emit a symbol because it's always substituted immediately in the code unless extern is used, which is not permitted in a class.

One thing to note is static inline int b; is treated as a definition whereas static const int b or static const A b; are still treated as a declaration and must be defined out-of-line if you don't define it inside the class. Interestingly static constexpr A b; is treated as a definition, whereas static constexpr int b; is an error and must have an initialiser (this is because they now become definitions and like any const/constexpr definition at file scope, they require an initialiser which an int doesn't have but a class type does because it has an implicit = A() when it is a definition -- clang allows this but gcc requires you to explicitly initialise or it is an error. This is not a problem with inline instead). static const A b = A(); is not allowed and must be constexpr or inline in order to permit an initialiser for a static object with class type i.e to make a static member of class type more than a declaration. So yes in certain situations A a; is not the same as explicitly initialising A a = A(); (the former can be a declaration but if only a declaration is allowed for that type then the latter is an error. The latter can only be used on a definition. constexpr makes it a definition). If you use constexpr and specify a default constructor then the constructor will need to be constexpr

#include<iostream>

struct A
{
    int b =2;
    mutable int c = 3; //if this member is included in the class then const A will have a full .data symbol emitted for it on -O0 and so will B because it contains A.
    static const int a = 3;
};

struct B {
    A b;
    static constexpr A c; //needs to be constexpr or inline and doesn't emit a symbol for A a mutable member on any optimisation level
};

const A a;
const B b;

int main()
{
    std::cout << a.b << b.b.b;
    return 0;
}

A static member is an outright file scope declaration extern int A::a; (which can only be made in the class and out of line definitions must refer to a static member in a class and must be definitions and cannot contain extern) whereas a non-static member is part of the complete type definition of a class and have the same rules as file scope declarations without extern. They are implicitly definitions. So int i[]; int i[5]; is a redefinition whereas static int i[]; int A::i[5]; isn't but unlike 2 externs, the compiler will still detect a duplicate member if you do static int i[]; static int i[5]; in the class.

Java: Unresolved compilation problem

you just try to clean maven by command

mvn clean

and after that following command

mvn eclipse:clean eclipse:eclipse

and rebuild your project....

What is the difference between null=True and blank=True in Django?

It's crucial to understand that the options in a Django model field definition serve (at least) two purposes: defining the database tables, and defining the default format and validation of model forms. (I say "default" because the values can always be overridden by providing a custom form.) Some options affect the database, some options affect forms, and some affect both.

When it comes to null and blank, other answers have already made clear that the former affects the database table definition and the latter affects model validation. I think the distinction can be made even clearer by looking at use cases for all four possible configurations:

  • null=False, blank=False: This is the default configuration and means that the value is required in all circumstances.

  • null=True, blank=True: This means that the field is optional in all circumstances. (As noted below, though, this is not the recommended way to make string-based fields optional.)

  • null=False, blank=True: This means that the form doesn't require a value but the database does. There are a number of use cases for this:

    • The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If NULL was also allowed you would end up with two different ways to indicate a missing value.

    • Another common situation is that you want to calculate one field automatically based on the value of another (in your save() method, say). You don't want the user to provide the value in a form (hence blank=True), but you do want the database to enforce that a value is always provided (null=False).

    • Another use is when you want to indicate that a ManyToManyField is optional. Because this field is implemented as a separate table rather than a database column, null is meaningless. The value of blank will still affect forms, though, controlling whether or not validation will succeed when there are no relations.

  • null=True, blank=False: This means that the form requires a value but the database doesn't. This may be the most infrequently used configuration, but there are some use cases for it:

    • It's perfectly reasonable to require your users to always include a value even if it's not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data which doesn't need the same stringent validation that you want to require of a human editor.

    • Another use case that I've seen is when you have a ForeignKey for which you don't wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False), but if the thing it points to happens to be deleted, you don't want this object to be deleted too. In that case you can use null=True and on_delete=models.SET_NULL to implement a simple kind of soft deletion.

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Why doesn't indexOf work on an array IE8?

You can use this to replace the function if it doesn't exist:

<script>
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length >>> 0;

        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this && this[from] === elt)
                return from;
        }
        return -1;
    };
}
</script>

How to recover just deleted rows in mysql?

As Mitch mentioned, backing data up is the best method.

However, it maybe possible to extract the lost data partially depending on the situation or DB server used. For most part, you are out of luck if you don't have any backup.

What is console.log in jQuery?

it will print log messages in your developer console (firebug/webkit dev tools/ie dev tools)

How do I implement IEnumerable<T>

If you choose to use a generic collection, such as List<MyObject> instead of ArrayList, you'll find that the List<MyObject> will provide both generic and non-generic enumerators that you can use.

using System.Collections;

class MyObjects : IEnumerable<MyObject>
{
    List<MyObject> mylist = new List<MyObject>();

    public MyObject this[int index]  
    {  
        get { return mylist[index]; }  
        set { mylist.Insert(index, value); }  
    } 

    public IEnumerator<MyObject> GetEnumerator()
    {
        return mylist.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

Rails: How can I rename a database column in a Ruby on Rails migration?

$:  rails g migration RenameHashedPasswordColumn
invoke  active_record
      create    db/migrate/20160323054656_rename_hashed_password_column.rb

Open that migration file and modify that file as below(Do enter your original table_name)

class  RenameHashedPasswordColumn < ActiveRecord::Migration
  def change
    rename_column :table_name, :hased_password, :hashed_password
  end
end

How can I clear or empty a StringBuilder?

If performance is the main concern then the irony, in my opinion, is the Java constructs to format the text that goes into the buffer, will be far more time consuming on the CPU than the allocation/reallocation/garbage collection ... well, possibly not the GC (garbage collection) depending on how many builders you create and discard.

But simply appending a compound string ("Hello World of " + 6E9 + " earthlings.") to the buffer is likely to make the whole matter inconsequential.

And, really, if an instance of StringBuilder is involved, then the content is complex and/or longer than a simple String str = "Hi"; (never mind that Java probably uses a builder in the background anyway).

Personally, I try not to abuse the GC. So if it's something that's going to be used a lot in a rapid fire scenario - like, say, writing debug output messages - I just assume declare it elsewhere and zero it out for reuse.

class MyLogger {
    StringBuilder strBldr = new StringBuilder(256);

    public void logMsg( String stuff, SomeLogWriterClass log ) {

        // zero out strBldr's internal index count, not every
        // index in strBldr's internal buffer
        strBldr.setLength(0);

        // ... append status level
        strBldr.append("Info");

        // ... append ' ' followed by timestamp
        // assuming getTimestamp() returns a String
        strBldr.append(' ').append(getTimestamp());

        // ... append ':' followed by user message
        strBldr.append(':').append(msg);

        log.write(strBldr.toString());
    }
}

How to set a text box for inputing password in winforms?

I know the perfect answer:

  1. double click on The password TextBox.
  2. write your textbox name like textbox2.
  3. write PasswordChar = '*';.
  4. I prefer going to windows character map and find a perfect hide like ?.

    example:TextBox2.PasswordChar = '?';
    

How does PHP 'foreach' actually work?

PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables.

In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy of the array rather than the original one. This is demonstrated in the below example:

<?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '<pre>', print_r($numbers, true), '</pre>', '<hr />';
foreach($numbers as $index => $number){
    $numbers[$index] = $number + 1; # this is making changes to the origial array
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '<pre>', print_r($numbers, true), '</pre>'; # shows the original values (also includes the newly added values).

Besides this, php does allow to use iterated values as a reference to the original array value as well. This is demonstrated below:

<?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '<pre>', print_r($numbers, true), '</pre>';
foreach($numbers as $index => &$number){
    ++$number; # we are incrementing the original value
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '<pre>', print_r($numbers, true), '</pre>'; # we are again showing the original value

Note: It does not allow original array indexes to be used as references.

Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples

Can't find/install libXtst.so.6?

EDIT: As mentioned by Stephen Niedzielski in his comment, the issue seems to come from the 32-bit being of the JRE, which is de facto, looking for the 32-bit version of libXtst6. To install the required version of the library:

$ sudo apt-get install libxtst6:i386

Type:

$ sudo apt-get update
$ sudo apt-get install libxtst6

If this isn’t OK, type:

$ sudo updatedb
$ locate libXtst

it should return something like:

/usr/lib/x86_64-linux-gnu/libXtst.so.6       # Mine is OK
/usr/lib/x86_64-linux-gnu/libXtst.so.6.1.0

If you do not have libXtst.so.6 but do have libXtst.so.6.X.X create a symbolic link:

$ cd /usr/lib/x86_64-linux-gnu/
$ ln -s libXtst.so.6 libXtst.so.6.X.X

Hope this helps.

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

To update and answer the question without breaking mail servers. Later versions of CentOS 7 have MariaDB included as the base along with PostFix which relies on MariaDB. Removing using yum will also remove postfix and perl-DBD-MySQL. To get around this and keep postfix in place, first make a copy of /usr/lib64/libmysqlclient.so.18 (which is what postfix depends on) and then use:

rpm -qa | grep mariadb

then remove the mariadb packages using (changing to your versions):

rpm -e --nodeps "mariadb-libs-5.5.56-2.el7.x86_64"
rpm -e --nodeps "mariadb-server-5.5.56-2.el7.x86_64"
rpm -e --nodeps "mariadb-5.5.56-2.el7.x86_64"

Delete left over files and folders (which also removes any databases):

rm -f /var/log/mariadb
rm -f /var/log/mariadb/mariadb.log.rpmsave
rm -rf /var/lib/mysql
rm -rf /usr/lib64/mysql
rm -rf /usr/share/mysql

Put back the copy of /usr/lib64/libmysqlclient.so.18 you made at the start and you can restart postfix.

There is more detail at https://code.trev.id.au/centos-7-remove-mariadb-replace-mysql/ which describes how to replace mariaDB with MySQL

What is Express.js?

Express.js created by TJ Holowaychuk and now managed by the community. It is one of the most popular frameworks in the node.js. Express can also be used to develop various products such as web applications or RESTful API.For more information please read on the expressjs.com official site.

How do I install PyCrypto on Windows?

If you don't already have a C/C++ development environment installed that is compatible with the Visual Studio binaries distributed by Python.org, then you should stick to installing only pure Python packages or packages for which a Windows binary is available.

Fortunately, there are PyCrypto binaries available for Windows: http://www.voidspace.org.uk/python/modules.shtml#pycrypto

UPDATE:
As @Udi suggests in the comment below, the following command also installs pycrypto and can be used in virtualenv as well:

easy_install http://www.voidspace.org.uk/python/pycrypto-2.6.1/pycrypto-2.6.1.win32-py2.7.exe

Notice to choose the relevant link for your setup from this list

If you're looking for builds for Python 3.5, see PyCrypto on python 3.5

AngularJS 1.2 $injector:modulerr

I had the same problem and tried all possible solution. But finally I came to know from the documentation that ngRoute module is now separated. Have a look to this link

Solution: Add the cdn angular-route.js after angular.min.js script

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

What is a Python equivalent of PHP's var_dump()?

print

For your own classes, just def a __str__ method

SQL multiple column ordering

SELECT  *
FROM    mytable
ORDER BY
        column1 DESC, column2 ASC

What's the best UML diagramming tool?

For my simple & short UML working, I've used this tool:

StarUML - http://staruml.sourceforge.net/en/

Great free software for UML drawing.


Although the original Star UML is no longer maintained, there's now a fork called White Star UML, which is actively developed.

Variable is accessed within inner class. Needs to be declared final

The error says it all, change:

ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);

to

final ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);

How can I get log4j to delete old rotating log files?

Logs rotate for a reason, so that you only keep so many log files around. In log4j.xml you can add this to your node:

<param name="MaxBackupIndex" value="20"/>

The value tells log4j.xml to only keep 20 rotated log files around. You can limit this to 5 if you want or even 1. If your application isn't logging that much data, and you have 20 log files spanning the last 8 months, but you only need a weeks worth of logs, then I think you need to tweak your log4j.xml "MaxBackupIndex" and "MaxFileSize" params.

Alternatively, if you are using a properties file (instead of the xml) and wish to save 15 files (for example)

log4j.appender.[appenderName].MaxBackupIndex = 15

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

Box-Shadow on the left side of the element only

box-shadow: -15px 0px 17px -7px rgba(0,0,0,0.75);

The first px value is the "Horizontal Length" set to -15px to position the shadow towards the left, the next px value is set to 0 so the shadow top and bottom is centred to minimise the top and bottom shadow.

The third value(17px) is known as the blur radius. The higher the number, the more blurred the shadow will be. And then last px value -7px is The spread radius, a positive value increases the size of the shadow, a negative value decreases the size of the shadow, at -7px it keeps the shadow from appearing above and below the item.

reference: CSS Box Shadow Property

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

Bart Kiers, your regex has a couple issues. The best way to do that is this:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

Dynamic WHERE clause in LINQ

Just to share my idea for this case.

Another approach by solution is:


public IOrderedQueryable GetProductList(string productGroupName, string productTypeName, Dictionary> filterDictionary)
{
    return db.ProductDetail
        .where
        (
            p =>
            (
                (String.IsNullOrEmpty(productGroupName) || c.ProductGroupName.Contains(productGroupName))
                && (String.IsNullOrEmpty(productTypeName) || c.ProductTypeName.Contains(productTypeName))
                // Apply similar logic to filterDictionary parameter here !!!
            )
        );  
}

This approach is very flexible and allow with any parameter to be nullable.

Could not load file or assembly ... The parameter is incorrect

I just delete my application temp data from this path

C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files

Problem resolve

Codeigniter's `where` and `or_where`

$this->db->where('(a = 1 or a = 2)');

How to use ArrayAdapter<myClass>

Here's a quick and dirty example of how to use an ArrayAdapter if you don't want to bother yourself with extending the mother class:

class MyClass extends Activity {
    private ArrayAdapter<String> mAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mAdapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_dropdown_item_1line, android.R.id.text1);

        final ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(mAdapter);

        //Add Some Items in your list:
        for (int i = 1; i <= 10; i++) {
            mAdapter.add("Item " + i);
        }

        // And if you want selection feedback:
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do whatever you want with the selected item
                Log.d(TAG, mAdapter.getItem(position) + " has been selected!");
            }
        });
    }
}

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

this worked for me:

ProxyRequests     Off
ProxyPreserveHost On
RewriteEngine On

<Proxy http://localhost:8123>
Order deny,allow
Allow from all
</Proxy>

ProxyPass         /node  http://localhost:8123  
ProxyPassReverse  /node  http://localhost:8123

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Scroll / Jump to id without jQuery

below code might help you

var objControl=document.getElementById("divid");
objControl.scrollTop = objControl.offsetTop;

How to remove leading zeros from alphanumeric text?

You can use the StringUtils class from Apache Commons Lang like this:

StringUtils.stripStart(yourString,"0");

How to find the privileges and roles granted to a user in Oracle?

SELECT * 
FROM DBA_ROLE_PRIVS 
WHERE UPPER(GRANTEE) LIKE '%XYZ%';

Print a list of space-separated elements in Python 3

list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
    print(i, end=', ')
print(list[-1])

do for loops really take that much longer to run?

was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:

spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
    print(i, end=', ')
print('and ' + spam[-1])

Eclipse: stop code from running (java)

For newer versions of Eclipse:

  1. open the Debug perspective (Window > Open Perspective > Debug)

  2. select process in Devices list (bottom right)

  3. Hit Stop button (top right of Devices pane)

How to check if array element is null to avoid NullPointerException in Java

Well, first of all that code doesn't compile.

After removing the extra semicolon after i++, it compiles and runs fine for me.

How to create jobs in SQL Server Express edition

SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.

There are a few third-party extensions that provide that capability - check out e.g.:

How Do I Make Glyphicons Bigger? (Change Size?)

Increase the font-size of glyphicon to increase all icons size.

.glyphicon {
    font-size: 50px;
}

To target only one icon,

.glyphicon.glyphicon-globe {
    font-size: 75px;
}

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

In Python, what is the difference between ".append()" and "+= []"?

The append() method adds a single item to the existing list

some_list1 = []
some_list1.append("something")

So here the some_list1 will get modified.

Updated:

Whereas using + to combine the elements of lists (more than one element) in the existing list similar to the extend (as corrected by Flux).

some_list2 = []
some_list2 += ["something"]

So here the some_list2 and ["something"] are the two lists that are combined.

How does the bitwise complement operator (~ tilde) work?

As others mentioned ~ just flipped bits (changes one to zero and zero to one) and since two's complement is used you get the result you saw.

One thing to add is why two's complement is used, this is so that the operations on negative numbers will be the same as on positive numbers. Think of -3 as the number to which 3 should be added in order to get zero and you'll see that this number is 1101, remember that binary addition is just like elementary school (decimal) addition only you carry one when you get to two rather than 10.

 1101 +
 0011 // 3
    =
10000
    =
 0000 // lose carry bit because integers have a constant number of bits.

Therefore 1101 is -3, flip the bits you get 0010 which is two.

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.

AFAIK, these are your options:

  1. Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters

  2. There also executable wrappers - see How can I convert my Java program to an .exe file?

See also: Convert Java to EXE: Why, When, When Not and How

How can I introduce multiple conditions in LIKE operator?

I also had the same requirement where I didn't have choice to pass like operator multiple times by either doing an OR or writing union query.

This worked for me in Oracle 11g:

REGEXP_LIKE (column, 'ABC.*|XYZ.*|PQR.*'); 

implements Closeable or implements AutoCloseable

Here is the small example

public class TryWithResource {

    public static void main(String[] args) {
        try (TestMe r = new TestMe()) {
            r.generalTest();
        } catch(Exception e) {
            System.out.println("From Exception Block");
        } finally {
            System.out.println("From Final Block");
        }
    }
}



public class TestMe implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println(" From Close -  AutoCloseable  ");
    }

    public void generalTest() {
        System.out.println(" GeneralTest ");
    }
}

Here is the output:

GeneralTest 
From Close -  AutoCloseable  
From Final Block

SQL: IF clause within WHERE clause

WHERE (IsNumeric(@OrderNumber) <> 1 OR OrderNumber = @OrderNumber) 
             AND (IsNumber(@OrderNumber) = 1 OR OrderNumber LIKE '%' 
                                              + @OrderNumber + '%')

How many characters can a Java String have?

Integer.MAX_VALUE is max size of string + depends of your memory size but the Problem on sphere's online judge you don't have to use those functions

How to copy text programmatically in my Android app?

Use ClipboardManager#setPrimaryClip method:

import android.content.ClipboardManager;

// ...

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);

ClipboardManager API reference

Read response headers from API response - Angular 5 + TypeScript

You can get headers using below code

let main_headers = {}
this.http.post(url,
  {email: this.username, password: this.password},
  {'headers' : new HttpHeaders ({'Content-Type' : 'application/json'}), 'responseType': 'text', observe:'response'})
  .subscribe(response => {
    const keys = response.headers.keys();
    let headers = keys.map(key => {
      `${key}: ${response.headers.get(key)}`
        main_headers[key] = response.headers.get(key)
       }
      );
  });

later we can get the required header form the json object.

header_list['X-Token']

How can I download a specific Maven artifact in one command line?

The command:

mvn install:install-file 

Typically installs the artifact in your local repository, so you shouldn't need to download it. However, if you want to share your artifact with others, you will need to deploy the artifact to a central repository see the deploy plugin for more details.

Additionally adding a dependency to your POM will automatically fetch any third-party artifacts you need when you build your project. I.e. This will download the artifact from the central repository.

Get Base64 encode file-data from Input Form

My solution was use readAsBinaryString() and btoa() on its result.

uploadFileToServer(event) {
    var file = event.srcElement.files[0];
    console.log(file);
    var reader = new FileReader();
    reader.readAsBinaryString(file);

    reader.onload = function() {
        console.log(btoa(reader.result));
    };
    reader.onerror = function() {
        console.log('there are some problems');
    };
}

Kill all processes for a given user

Just (temporarily) killed my Macbook with

killall -u pu -m .

where pu is my userid. Watch the dot at the end of the command.

Also try

pkill -u pu

or

ps -o pid -u pu | xargs kill -1

Making a <button> that's a link in HTML

_x000D_
_x000D_
<a id="reset-authenticator" asp-page="./ResetAuthenticator"><input type="button" class="btn btn-primary" value="Reset app" /></a>
_x000D_
_x000D_
_x000D_

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

What is the purpose of a plus symbol before a variable?

The + operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d is a non-zero number.

Reference here. And, as pointed out in comments, here.

C fopen vs open

Unless you're part of the 0.1% of applications where using open is an actual performance benefit, there really is no good reason not to use fopen. As far as fdopen is concerned, if you aren't playing with file descriptors, you don't need that call.

Stick with fopen and its family of methods (fwrite, fread, fprintf, et al) and you'll be very satisfied. Just as importantly, other programmers will be satisfied with your code.

Vim: How to insert in visual block mode?

You might also have a use case where you want to delete a block of text and replace it .

Like this

Hello World
Hello World

You can visual block select before "W" and hit Shift+i - Type "Cool" - Hit ESC and then delete "World" by visual block selection .

Alternatively, the cooler way to do it is to just visual block select "World" in both lines. Type c for change. Now you are in the insert mode. Insert the stuff you want and hit ESC. Both gets reflected with lesser keystrokes.

Hello Cool 
Hello Cool

How do I concatenate multiple C++ strings on one line?

#include <sstream>
#include <string>

std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();

Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm

What's the Use of '\r' escape sequence?

The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.

How to delete a certain row from mysql table with same column values?

There are already answers for Deleting row by LIMIT. Ideally you should have primary key in your table. But if there is not.

I will give other ways:

  1. By creating Unique index

I see id_users and id_product should be unique in your example.

ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)

These will delete duplicate rows with same data.

But if you still get an error, even if you use IGNORE clause, try this:

ALTER TABLE orders ENGINE MyISAM;
ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)
ALTER TABLE orders ENGINE InnoDB; 
  1. By creating table again

If there are multiple rows who have duplicate values, then you can also recreate table

RENAME TABLE `orders` TO `orders2`;

CREATE TABLE `orders` 
SELECT * FROM `orders2` GROUP BY id_users, id_product;

add maven repository to build.gradle

You have to add repositories to your build file. For maven repositories you have to prefix repository name with maven{}

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

Adding Lombok plugin to IntelliJ project

You need to Enable Annotation Processing on IntelliJ IDEA

> Settings > Build, Execution, Deployment > Compiler > Annotation Processors

enter image description here

Determine version of Entity Framework I am using?

There are two versions: 1 and 4. EFv4 is part of .net 4.0, and EFv1 is part of .net 3.5 SP1.

Yes, the config setting above points to EFv4 / .net 4.0.

EDIT If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows runtime version v4.0.30319 with the Version property showing 4.0.0.0. The EntityFramework.dll can be viewed in this fashion also. Only the Version will be 4.1.0.0 and the Runtime version will be v4.0.30319 which specifies it is a .NET 4 component. Alternatively, you can open the file location as listed in the Path property and right-click the component in question, choose properties, then choose the details tab and view the product version.

Finding the number of days between two dates

$diff = strtotime('2019-11-25') - strtotime('2019-11-10');
echo abs(round($diff / 86400));

How do I bind onchange event of a TextBox using JQuery?

I 2nd Chad Grant's answer and also submit this blog article [removed dead link] for your viewing pleasure.

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Vue.js: Conditional class style binding

the problem is blade, try this

<i class="fa" v-bind:class="['{{content['cravings']}}' ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i>

Printing *s as triangles in Java?

This is the least complex program, which takes only 1 for loop to print the triangle. This works only for the center triangle, but small tweaking would make it work for other's as well -

import java.io.DataInputStream;

public class Triangle {
    public static void main(String a[]) throws Exception{
        DataInputStream in = new DataInputStream(System.in);

        int n = Integer.parseInt(in.readLine());
        String b = new String(new char[n]).replaceAll("\0", " ");
        String s = "*";
        for(int i=1; i<=n; i++){
            System.out.print(b);
            System.out.println(s);
            s += "**";
            b = b.substring(0, n-i);
            System.out.println();
        }
    }
}

Accessing session from TWIG template

Setup twig

$twig = new Twig_Environment(...);    
$twig->addGlobal('session', $_SESSION);

Then within your template access session values for example

$_SESSION['username'] in php file Will be equivalent to {{ session.username }} in your twig template

Browse for a directory in C#

Please don't try and roll your own with a TreeView/DirectoryInfo class. For one thing there are many nice features you get for free (icons/right-click/networks) by using SHBrowseForFolder. For another there are a edge cases/catches you will likely not be aware of.

How to catch and print the full exception traceback without halting/exiting the program?

To get the precise stack trace, as a string, that would have been raised if no try/except were there to step over it, simply place this in the except block that catches the offending exception.

desired_trace = traceback.format_exc(sys.exc_info())

Here's how to use it (assuming flaky_func is defined, and log calls your favorite logging system):

import traceback
import sys

try:
    flaky_func()
except KeyboardInterrupt:
    raise
except Exception:
    desired_trace = traceback.format_exc(sys.exc_info())
    log(desired_trace)

It's a good idea to catch and re-raise KeyboardInterrupts, so that you can still kill the program using Ctrl-C. Logging is outside the scope of the question, but a good option is logging. Documentation for the sys and traceback modules.

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

In your particular case the issue seem to be with accessing the site from non-canonical url (www.site.com vs. site.com).

Instead of fixing CORS issue (which may require writing proxy to server fonts with proper CORS headers depending on service provider) you can normalize your Urls to always server content on canonical Url and simply redirect if one requests page without "www.".

Alternatively you can upload fonts to different server/CDN that is known to have CORS headers configured or you can easily do so.

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

How do I ignore ampersands in a SQL script running from SQL Plus?

If you sometimes use substitution variables you might not want to turn define off. In these cases you could convert the ampersand from its numeric equivalent as in || Chr(38) || or append it as a single character as in || '&' ||.

Communication between multiple docker-compose projects

version: '2'
services:
  bot:
    build: .
    volumes:
      - '.:/home/node'
      - /home/node/node_modules
    networks:
      - my-rede
    mem_limit: 100m
    memswap_limit: 100m
    cpu_quota: 25000
    container_name: 236948199393329152_585042339404185600_bot
    command: node index.js
    environment:
      NODE_ENV: production
networks:
  my-rede:
    external:
      name: name_rede_externa

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

Delaying AngularJS route change until model loaded to prevent flicker

You can use $routeProvider resolve property to delay route change until data is loaded.

angular.module('app', ['ngRoute']).
  config(['$routeProvider', function($routeProvider, EntitiesCtrlResolve, EntityCtrlResolve) {
    $routeProvider.
      when('/entities', {
        templateUrl: 'entities.html', 
        controller: 'EntitiesCtrl', 
        resolve: EntitiesCtrlResolve
      }).
      when('/entity/:entityId', {
        templateUrl: 'entity.html', 
        controller: 'EntityCtrl', 
        resolve: EntityCtrlResolve
      }).
      otherwise({redirectTo: '/entities'});
}]);

Notice that the resolve property is defined on route.

EntitiesCtrlResolve and EntityCtrlResolve is constant objects defined in same file as EntitiesCtrl and EntityCtrl controllers.

// EntitiesCtrl.js

angular.module('app').constant('EntitiesCtrlResolve', {
  Entities: function(EntitiesService) {
    return EntitiesService.getAll();
  }
});

angular.module('app').controller('EntitiesCtrl', function(Entities) {
  $scope.entities = Entities;

  // some code..
});

// EntityCtrl.js

angular.module('app').constant('EntityCtrlResolve', {
  Entity: function($route, EntitiesService) {
    return EntitiesService.getById($route.current.params.projectId);
  }
});

angular.module('app').controller('EntityCtrl', function(Entity) {
  $scope.entity = Entity;

  // some code..
});

problem with php mail 'From' header

I solved this by adding email accounts in Cpanel and also adding that same email to the header from field like this

$header = 'From: XXXXXXXX <[email protected]>' . "\r\n";

Convert URL to File or Blob for FileReader.readAsDataURL

I know this is an expansion off of @tibor-udvari's answer, but for a nicer copy and paste.

async function createFile(url, type){
  if (typeof window === 'undefined') return // make sure we are in the browser
  const response = await fetch(url)
  const data = await response.blob()
  const metadata = {
    type: type || 'video/quicktime'
  }
  return new File([data], url, metadata)
}

LDAP root query syntax to search more than one specific OU

The answer is NO you can't. Why?

Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:

  1. The node where the search should begin, which is a Distinguish Name (DN)
  2. The attributes you want to be brought back
  3. The depth of the search (base, one-level, subtree)
  4. The filter

You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value.

So the filter you give does not mean anything.

On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.

As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.

It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:

(&(objectCategory=person)(|(ou=staff)(ou=vendors)))

Swipe ListView item From right to left show delete button

I used to have the same problem finding a good library to do that. Eventually, I created a library which can do that: SwipeRevealLayout

In gradle file:

dependencies {
    compile 'com.chauthai.swipereveallayout:swipe-reveal-layout:1.4.0'
}

In your xml file:

<com.chauthai.swipereveallayout.SwipeRevealLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:mode="same_level"
    app:dragEdge="left">

    <!-- Your secondary layout here -->
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />

    <!-- Your main layout here -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.chauthai.swipereveallayout.SwipeRevealLayout>

Then in your adapter file:

public class Adapter extends RecyclerView.Adapter {
  // This object helps you save/restore the open/close state of each view
  private final ViewBinderHelper viewBinderHelper = new ViewBinderHelper();

  @Override
  public void onBindViewHolder(ViewHolder holder, int position) {
    // get your data object first.
    YourDataObject dataObject = mDataSet.get(position); 

    // Save/restore the open/close state.
    // You need to provide a String id which uniquely defines the data object.
    viewBinderHelper.bind(holder.swipeRevealLayout, dataObject.getId()); 

    // do your regular binding stuff here
  }
}

Why is visible="false" not working for a plain html table?

You probably are looking for style="display:none;" which will totally hide your element, whereas the visibility hides it but keeps the screen place it would take...

UPDATE: visible is not a valid property in HTML, that's why it didn't work... See my suggestion above to correctly hide your html element

Searching a list of objects in Python

You should add a __eq__ and a __hash__ method to your Data class, it could check if the __dict__ attributes are equal (same properties) and then if their values are equal, too.

If you did that, you can use

test = Data()
test.n = 5

found = test in myList

The in keyword checks if test is in myList.

If you only want to a a n property in Data you could use:

class Data(object):
    __slots__ = ['n']
    def __init__(self, n):
        self.n = n
    def __eq__(self, other):
        if not isinstance(other, Data):
            return False
        if self.n != other.n:
            return False
        return True
    def __hash__(self):
        return self.n

    myList = [ Data(1), Data(2), Data(3) ]
    Data(2) in myList  #==> True
    Data(5) in myList  #==> False

open existing java project in eclipse

  1. File -> Import -> Existing Project into Workspace
  2. Browse for that directory.

Alternative: Check out the code in SVN to some folder

  1. Create a new folder in windows
  2. In eclipse File -> switchWorkspace -> newFolderName
  3. close the welcome window in eclipse
  4. In eclipse File -> Import -> Existing project into workspce-> select root dir -> browse and show the svn checkout folder

How to mount host volumes into docker containers in Dockerfile during build

It's ugly, but I achieved a semblance of this like so:

Dockerfile:

FROM foo
COPY ./m2/ /root/.m2
RUN stuff

imageBuild.sh:

docker build . -t barImage
container="$(docker run -d barImage)"
rm -rf ./m2
docker cp "$container:/root/.m2" ./m2
docker rm -f "$container"

I have a java build that downloads the universe into /root/.m2, and did so every single time. imageBuild.sh copies the contents of that folder onto the host after the build, and Dockerfile copies them back into the image for the next build.

This is something like how a volume would work (i.e. it persists between builds).

How to synchronize a static variable among threads running different instances of a class in Java?

There are several ways to synchronize access to a static variable.

  1. Use a synchronized static method. This synchronizes on the class object.

    public class Test {
        private static int count = 0;
    
        public static synchronized void incrementCount() {
            count++;
        }
    } 
    
  2. Explicitly synchronize on the class object.

    public class Test {
        private static int count = 0;
    
        public void incrementCount() {
            synchronized (Test.class) {
                count++;
            }
        }
    } 
    
  3. Synchronize on some other static object.

    public class Test {
        private static int count = 0;
        private static final Object countLock = new Object();
    
        public void incrementCount() {
            synchronized (countLock) {
                count++;
            }
        }
    } 
    

Method 3 is the best in many cases because the lock object is not exposed outside of your class.

TypeError: Cannot read property "0" from undefined

The while increments the i. So you get:

data[1][0]
data[2][0]
data[3][0]
...

It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

I used another repository for oracle java.

sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update

sudo apt install  oracle-java11-installer

Setting TIME_WAIT TCP

Usually, only the endpoint that issues an 'active close' should go into TIME_WAIT state. So, if possible, have your clients issue the active close which will leave the TIME_WAIT on the client and NOT on the server.

See here: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html and http://www.isi.edu/touch/pubs/infocomm99/infocomm99-web/ for details (the later also explains why it's not always possible due to protocol design that doesn't take TIME_WAIT into consideration).

Convert LocalDate to LocalDateTime or java.sql.Timestamp

function call asStartOfDay() on java.time.LocalDate object returns a java.time.LocalDateTime object

How to append to the end of an empty list?

I personally prefer the + operator than append:

for i in range(0, n):

    list1 += [[i]]

But this is creating a new list every time, so might not be the best if performance is critical.

Read text from response

I've just tried that myself, and it gave me a 200 OK response, but no content - the content length was 0. Are you sure it's giving you content? Anyway, I'll assume that you've really got content.

Getting actual text back relies on knowing the encoding, which can be tricky. It should be in the Content-Type header, but then you've got to parse it etc.

However, if this is actually XML (e.g. from "http://google.com/xrds/xrds.xml"), it's a lot easier. Just load the XML into memory, e.g. via LINQ to XML. For example:

using System;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Web;

class Test
{
    static void Main()
    {
        string url = "http://google.com/xrds/xrds.xml";
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);

        XDocument doc;
        using (WebResponse response = request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                doc = XDocument.Load(stream);
            }
        }
        // Now do whatever you want with doc here
        Console.WriteLine(doc);
    }   
}

If the content is XML, getting the result into an XML object model (whether it's XDocument, XmlDocument or XmlReader) is likely to be more valuable than having the plain text.

How to access Anaconda command prompt in Windows 10 (64-bit)

I added "\Anaconda3_64\" and "\Anaconda3_64\Scripts\" to the PATH variable. Then I can use conda from powershell or command prompt.

Dealing with float precision in Javascript

> var x = 0.1
> var y = 0.2
> var cf = 10
> x * y
0.020000000000000004
> (x * cf) * (y * cf) / (cf * cf)
0.02

Quick solution:

var _cf = (function() {
  function _shift(x) {
    var parts = x.toString().split('.');
    return (parts.length < 2) ? 1 : Math.pow(10, parts[1].length);
  }
  return function() { 
    return Array.prototype.reduce.call(arguments, function (prev, next) { return prev === undefined || next === undefined ? undefined : Math.max(prev, _shift (next)); }, -Infinity);
  };
})();

Math.a = function () {
  var f = _cf.apply(null, arguments); if(f === undefined) return undefined;
  function cb(x, y, i, o) { return x + f * y; }
  return Array.prototype.reduce.call(arguments, cb, 0) / f;
};

Math.s = function (l,r) { var f = _cf(l,r); return (l * f - r * f) / f; };

Math.m = function () {
  var f = _cf.apply(null, arguments);
  function cb(x, y, i, o) { return (x*f) * (y*f) / (f * f); }
  return Array.prototype.reduce.call(arguments, cb, 1);
};

Math.d = function (l,r) { var f = _cf(l,r); return (l * f) / (r * f); };

> Math.m(0.1, 0.2)
0.02

You can check the full explanation here.

Can I set a breakpoint on 'memory access' in GDB?

I just tried the following:

 $ cat gdbtest.c
 int abc = 43;

 int main()
 {
   abc = 10;
 }
 $ gcc -g -o gdbtest gdbtest.c
 $ gdb gdbtest
 ...
 (gdb) watch abc
 Hardware watchpoint 1: abc
 (gdb) r
 Starting program: /home/mweerden/gdbtest 
 ...

 Old value = 43
 New value = 10
 main () at gdbtest.c:6
 6       }
 (gdb) quit

So it seems possible, but you do appear to need some hardware support.

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

How to set radio button checked as default in radiogroup?

you should check the radiobutton in the radiogroup like this:

radiogroup.check(IdOfYourButton)

Of course you first have to set an Id to your radiobuttons

EDIT: i forgot, radioButton.getId() works as well, thx Ramesh

EDIT2:

android:checkedButton="@+id/my_radiobtn"

works in radiogroup xml

What are the main differences between JWT and OAuth authentication?

TL;DR If you have very simple scenarios, like a single client application, a single API then it might not pay off to go OAuth 2.0, on the other hand, lots of different clients (browser-based, native mobile, server-side, etc) then sticking to OAuth 2.0 rules might make it more manageable than trying to roll your own system.


As stated in another answer, JWT (Learn JSON Web Tokens) is just a token format, it defines a compact and self-contained mechanism for transmitting data between parties in a way that can be verified and trusted because it is digitally signed. Additionally, the encoding rules of a JWT also make these tokens very easy to use within the context of HTTP.

Being self-contained (the actual token contains information about a given subject) they are also a good choice for implementing stateless authentication mechanisms (aka Look mum, no sessions!). When going this route and the only thing a party must present to be granted access to a protected resource is the token itself, the token in question can be called a bearer token.

In practice, what you're doing can already be classified as based on bearer tokens. However, do consider that you're not using bearer tokens as specified by the OAuth 2.0 related specs (see RFC 6750). That would imply, relying on the Authorization HTTP header and using the Bearer authentication scheme.

Regarding the use of the JWT to prevent CSRF without knowing exact details it's difficult to ascertain the validity of that practice, but to be honest it does not seem correct and/or worthwhile. The following article (Cookies vs Tokens: The Definitive Guide) may be a useful read on this subject, particularly the XSS and XSRF Protection section.

One final piece of advice, even if you don't need to go full OAuth 2.0, I would strongly recommend on passing your access token within the Authorization header instead of going with custom headers. If they are really bearer tokens, follow the rules of RFC 6750. If not, you can always create a custom authentication scheme and still use that header.

Authorization headers are recognized and specially treated by HTTP proxies and servers. Thus, the usage of such headers for sending access tokens to resource servers reduces the likelihood of leakage or unintended storage of authenticated requests in general, and especially Authorization headers.

(source: RFC 6819, section 5.4.1)

What is ToString("N0") format?

It is a sort of format specifier for formatting numeric results. There are additional specifiers on the link.

What N does is that it separates numbers into thousand decimal places according to your CultureInfo and represents only 2 decimal digits in floating part as is N2 by rounding right-most digit if necessary.

N0 does not represent any decimal place but rounding is applied to it.

Let's exemplify.

using System;
using System.Globalization;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x = 567892.98789;
            CultureInfo someCulture = new CultureInfo("da-DK", false);

            // 10 means left-padded = right-alignment
            Console.WriteLine(String.Format(someCulture, "{0:N} denmark", x));
            Console.WriteLine("{0,10:N} us", x); 

            // watch out rounding 567,893
            Console.WriteLine(String.Format(someCulture, "{0,10:N0}", x)); 
            Console.WriteLine("{0,10:N0}", x);

            Console.WriteLine(String.Format(someCulture, "{0,10:N5}", x));
            Console.WriteLine("{0,10:N5}", x);


            Console.ReadKey();

        }
    }
}

It yields,

567.892,99 denmark
567,892.99 us
   567.893
   567,893
567.892,98789
567,892.98789

conflicting types error when compiling c program using gcc

If you don't declare a function and it only appears after being called, it is automatically assumed to be int, so in your case, you didn't declare

void my_print (char *);
void my_print2 (char *);

before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *); and int my_print2 (char *); and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types.

As Brian suggested, declare those two methods before main.

How to redirect cin and cout to files?

Just write

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;
}

Could not commit JPA transaction: Transaction marked as rollbackOnly

For those who can't (or don't want to) setup a debugger to track down the original exception which was causing the rollback-flag to get set, you can just add a bunch of debug statements throughout your code to find the lines of code which trigger the rollback-only flag:

logger.debug("Is rollbackOnly: " + TransactionAspectSupport.currentTransactionStatus().isRollbackOnly());

Adding this throughout the code allowed me to narrow down the root cause, by numbering the debug statements and looking to see where the above method goes from returning "false" to "true".

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Convert String into a Class Object

You can use the statement :-

Class c = s.getClass();

To get the class instance.

How to remove all namespaces from XML with C#?

You can do that using Linq:

public static string RemoveAllNamespaces(string xmlDocument)
{
    var xml = XElement.Parse(xmlDocument);
    xml.Descendants().Select(o => o.Name = o.Name.LocalName).ToArray();
    return xml.ToString();
}

PHP isset() with multiple parameters

The parameters of isset() should be separated by a comma sign (,) and not a dot sign (.). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.

So the original code evaluates the variables as a unified string value:

isset($_POST['search_term'] . $_POST['postcode']) // Incorrect

While the correct form evaluates them separately as variables:

isset($_POST['search_term'], $_POST['postcode']) // Correct

What do .c and .h file extensions mean to C?

They're not really library files. They're just source files. Like Stefano said, the .c file is the C source file which actually uses/defines the actual source of what it merely outlined in the .h file, the header file. The header file usually outlines all of the function prototypes and structures that will be used in the actual source file. Think of it like a reference/appendix. This is evident upon looking at the header file, as you will see :) So then when you want to use something that was written in these source files, you #include the header file, which contains the information that the compiler will need to know.

How to use `subprocess` command with pipes

You can try the pipe functionality in sh.py:

import sh
print sh.grep(sh.ps("-ax"), "process_name")

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

It turns out that this is because ASP.Net was not completely installed with IIS even though I checked that box in the "Add Feature" dialog. To fix this, I simply ran the following command at the command prompt

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

If I had been on a 32 bit system, it would have looked like the following:

%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i

Remeber to run the command prompt as administrator (CTRL+SHIFT+ENTER)

Set active tab style with AngularJS

Here's another version of XMLillies w/ domi's LI change that uses a search string instead of a path level. I think this is a little more obvious what's happening for my use case.

statsApp.directive('activeTab', function ($location) {
  return {
    link: function postLink(scope, element, attrs) {
      scope.$on("$routeChangeSuccess", function (event, current, previous) {
        if (attrs.href!=undefined) { // this directive is called twice for some reason
          // The activeTab attribute should contain a path search string to match on.
          // I.e. <li><a href="#/nested/section1/partial" activeTab="/section1">First Partial</a></li>
          if ($location.path().indexOf(attrs.activeTab) >= 0) {
            element.parent().addClass("active");//parent to get the <li>
          } else {
            element.parent().removeClass("active");
          }
        }
      });
    }
  };
});

HTML now looks like:

<ul class="nav nav-tabs">
  <li><a href="#/news" active-tab="/news">News</a></li>
  <li><a href="#/some/nested/photos/rawr" active-tab="/photos">Photos</a></li>
  <li><a href="#/contact" active-tab="/contact">Contact</a></li>
</ul>

Is it possible to delete an object's property in PHP?

This code is working fine for me in a loop

$remove = array(
    "market_value",
    "sector_id"
);

foreach($remove as $key){
    unset($obj_name->$key);
}

getFilesDir() vs Environment.getDataDirectory()

From the HERE and HERE

public File getFilesDir ()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

public static File getExternalStorageDirectory ()

Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().

Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.

On devices with multiple users (as described by UserManager), each user has their own isolated external storage. Applications only have access to the external storage for the user they're running as.

If you want to get your application path use getFilesDir() which will give you path /data/data/your package/files

You can get the path using the Environment var of your data/package using the

getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath(); which will return the path from the root directory of your external storage as /storage/sdcard/Android/data/your pacakge/files/data

To access the external resources you have to provide the permission of WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in your manifest.

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

Check out the Best Documentation to get the paths of direcorty

How to implement a secure REST API with node.js

If you want to have a completely locked down area of your webapplication which can only be accessed by administrators from your company, then SSL authorization maybe for you. It will insure that no one can make a connection to the server instance unless they have an authorized certificate installed in their browser. Last week I wrote an article on how to setup the server: Article

This is one of the most secure setups you will find as there are no username/passwords involved so no one can gain access unless one of your users hands the key files to a potential hacker.

How to store Configuration file and read it using React

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

How to redirect 404 errors to a page in ExpressJS?

I found this example quite helpful:

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

So it is actually this part:

// "app.router" positions our routes
// above the middleware defined below,
// this means that Express will attempt
// to match & call routes _before_ continuing
// on, at which point we assume it's a 404 because
// no route has handled the request.

app.use(app.router);

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next){
  res.status(404);

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });
    return;
  }

  // respond with json
  if (req.accepts('json')) {
    res.send({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});

How to get text from each cell of an HTML table?

Here's a C# example I just cooked up, loosely based on the answer using CSS selectors, hopefully of use to others for seeing how to setup a ReadOnlyCollection of table rows and iterate over it in MS land at least. I'm looking through a collection of table rows to find a row with an OriginatorsRef (just a string) and a TD with an image that contains a title attribute with Overdue by in it:

    public ReadOnlyCollection<IWebElement> GetTableRows()
    {
        this.iwebElement = GetElement();
        return this.iwebElement.FindElements(By.CssSelector("tbody tr"));
    }

And within my main code:

        ...
        ReadOnlyCollection<IWebElement> TableRows;
        TableRows = f.Grid_Fault.GetTableRows();

        foreach (IWebElement row in TableRows)
        {
            if (row.Text.Contains(CustomTestContext.Current.OriginatorsRef) &&
              row.FindElements(By.CssSelector("td img[title*='Overdue by']")).Count > 0)
                return true;
        }

Object array initialization without default constructor

You can use in-place operator new. This would be a bit horrible, and I'd recommend keeping in a factory.

Car* createCars(unsigned number)
{
    if (number == 0 )
        return 0;
    Car* cars = reinterpret_cast<Car*>(new char[sizeof(Car)* number]);
    for(unsigned carId = 0;
        carId != number;
        ++carId)
    {
        new(cars+carId) Car(carId);
    }
    return cars;
}

And define a corresponding destroy so as to match the new used in this.

How to draw in JPanel? (Swing/graphics Java)

Here is a simple example. I suppose it will be easy to understand:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;


public Graph() {
    f.setTitle("Simple Drawing");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new GPanel();
    f.add(jp);
    f.setVisible(true);
}

public static void main(String[] args) {
    Graph g1 = new Graph();
    g1.setVisible(true);
}

class GPanel extends JPanel {
    public GPanel() {
        f.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        //rectangle originates at 10,10 and ends at 240,240
        g.drawRect(10, 10, 240, 240);
        //filled Rectangle with rounded corners.    
        g.fillRoundRect(50, 50, 100, 100, 80, 80);
    }
}

}

And the output looks like this:

Output

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

How do I make a self extract and running installer

I have created step by step instructions on how to do this as I also was very confused about how to get this working.

How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch

Here are the steps.

Step 1 - Setup your installation folder

To make this easy create a folder c:\Install. This is where we will copy all the required files.

Step 2 - 7Zip your installers

  1. Go to the folder that has your .msi and your setup.exe
  2. Select both the .msi and the setup.exe
  3. Right-Click and choose 7Zip --> "Add to Archive"
  4. Name your archive "Installer.7z" (or a name of your choice)
  5. Click Ok
  6. You should now have "Installer.7z".
  7. Copy this .7z file to your c:\Install directory

Step 3 - Get the 7z-Extra sfx extension module

You need to download 7zSD.sfx

  1. Download one of the LZMA packages from here
  2. Extract the package and find 7zSD.sfx in the bin folder.
  3. Copy the file "7zSD.sfx" to c:\Install

Step 4 - Setup your config.txt

I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.

  1. Using windows explorer go to c:\Install
  2. right-click and choose "New Text File" and name it config.txt
  3. right-click and choose "Edit with NotePad++
  4. Click the "Encoding Menu" and choose "Encode in UTF-8"
  5. Enter something like this:

    ;!@Install@!UTF-8!
    Title="SOFTWARE v1.0.0.0"
    BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"
    RunProgram="setup.exe"
    ;!@InstallEnd@!
    

Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.

CheckPoint

You should now have a folder "c:\Install" with the following 3 files:

  1. Installer.7z
  2. 7zSD.sfx
  3. config.txt

Step 5 - Create the archive

These instructions I found on the web but nowhere did it explain any of the 4 steps above.

  1. Open a cmd window, Window + R --> cmd --> press enter
  2. In the command window type the following

    cd \
    cd Install
    copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
    
  3. Look in c:\Install and you will now see you have a MyInstaller.exe

  4. You are finished

Run the installer

Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.

P.S. Note on Automation

Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.

copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe

Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

If you want examples of Algorithms/Group of Statements with Time complexity as given in the question, here is a small list -

O(1) time

  • Accessing Array Index (int a = ARR[5];)
  • Inserting a node in Linked List
  • Pushing and Poping on Stack
  • Insertion and Removal from Queue
  • Finding out the parent or left/right child of a node in a tree stored in Array
  • Jumping to Next/Previous element in Doubly Linked List

O(n) time

In a nutshell, all Brute Force Algorithms, or Noob ones which require linearity, are based on O(n) time complexity

  • Traversing an array
  • Traversing a linked list
  • Linear Search
  • Deletion of a specific element in a Linked List (Not sorted)
  • Comparing two strings
  • Checking for Palindrome
  • Counting/Bucket Sort and here too you can find a million more such examples....

O(log n) time

  • Binary Search
  • Finding largest/smallest number in a binary search tree
  • Certain Divide and Conquer Algorithms based on Linear functionality
  • Calculating Fibonacci Numbers - Best Method The basic premise here is NOT using the complete data, and reducing the problem size with every iteration

O(n log n) time

The factor of 'log n' is introduced by bringing into consideration Divide and Conquer. Some of these algorithms are the best optimized ones and used frequently.

  • Merge Sort
  • Heap Sort
  • Quick Sort
  • Certain Divide and Conquer Algorithms based on optimizing O(n^2) algorithms

O(n^2) time

These ones are supposed to be the less efficient algorithms if their O(nlogn) counterparts are present. The general application may be Brute Force here.

  • Bubble Sort
  • Insertion Sort
  • Selection Sort
  • Traversing a simple 2D array

TypeError: object of type 'int' has no len() error assistance needed

Well, maybe an int does not posses the len attribute in Python like your error suggests?

Try:

len(str(numbers))

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

Is it possible to read the value of a annotation in java?

I've never done it, but it looks like Reflection provides this. Field is an AnnotatedElement and so it has getAnnotation. This page has an example (copied below); quite straightforward if you know the class of the annotation and if the annotation policy retains the annotation at runtime. Naturally if the retention policy doesn't keep the annotation at runtime, you won't be able to query it at runtime.

An answer that's since been deleted (?) provided a useful link to an annotations tutorial that you may find helpful; I've copied the link here so people can use it.

Example from this page:

import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

class Meta {
  @MyAnno(str = "Two Parameters", val = 19)
  public static void myMeth(String str, int i) {
    Meta ob = new Meta();

    try {
      Class c = ob.getClass();

      Method m = c.getMethod("myMeth", String.class, int.class);

      MyAnno anno = m.getAnnotation(MyAnno.class);

      System.out.println(anno.str() + " " + anno.val());
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMeth("test", 10);
  }
}

How to download a branch with git?

you can use :

git clone <url> --branch <branch>

to clone/download only the contents of the branch.

This was helpful to me especially, since the contents of my branch were entirely different from the master branch (though this is not usually the case). Hence, the suggestions listed by others above didn't help me and I would end up getting a copy of the master even after I checked out the branch and did a git pull.

This command would directly give you the contents of the branch. It worked for me.

ASP.NET: Session.SessionID changes between requests

My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue

<sessionState cookieless="true"  />

Here's a REALLY old article about it: Cookieless ASP.NET

Capture iframe load complete event

Neither of the above answers worked for me, however this did

UPDATE:

As @doppleganger pointed out below, load is gone as of jQuery 3.0, so here's an updated version that uses on. Please note this will actually work on jQuery 1.7+, so you can implement it this way even if you're not on jQuery 3.0 yet.

$('iframe').on('load', function() {
    // do stuff 
});

.Net: How do I find the .NET version?

Just type the following in the command line:

dir /b /ad /o-n %systemroot%\Microsoft.NET\Framework\v?.*

Your dotnet version will be shown as the highest number.

JSON.net: how to deserialize without using the default constructor?

A bit late and not exactly suited here, but I'm gonna add my solution here, because my question had been closed as a duplicate of this one, and because this solution is completely different.

I needed a general way to instruct Json.NET to prefer the most specific constructor for a user defined struct type, so I can omit the JsonConstructor attributes which would add a dependency to the project where each such struct is defined.

I've reverse engineered a bit and implemented a custom contract resolver where I've overridden the CreateObjectContract method to add my custom creation logic.

public class CustomContractResolver : DefaultContractResolver {

    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        var c = base.CreateObjectContract(objectType);
        if (!IsCustomStruct(objectType)) return c;

        IList<ConstructorInfo> list = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).OrderBy(e => e.GetParameters().Length).ToList();
        var mostSpecific = list.LastOrDefault();
        if (mostSpecific != null)
        {
            c.OverrideCreator = CreateParameterizedConstructor(mostSpecific);
            c.CreatorParameters.AddRange(CreateConstructorParameters(mostSpecific, c.Properties));
        }

        return c;
    }

    protected virtual bool IsCustomStruct(Type objectType)
    {
        return objectType.IsValueType && !objectType.IsPrimitive && !objectType.IsEnum && !objectType.Namespace.IsNullOrEmpty() && !objectType.Namespace.StartsWith("System.");
    }

    private ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
    {
        method.ThrowIfNull("method");
        var c = method as ConstructorInfo;
        if (c != null)
            return a => c.Invoke(a);
        return a => method.Invoke(null, a);
    }
}

I'm using it like this.

public struct Test {
  public readonly int A;
  public readonly string B;

  public Test(int a, string b) {
    A = a;
    B = b;
  }
}

var json = JsonConvert.SerializeObject(new Test(1, "Test"), new JsonSerializerSettings {
  ContractResolver = new CustomContractResolver()
});
var t = JsonConvert.DeserializeObject<Test>(json);
t.A.ShouldEqual(1);
t.B.ShouldEqual("Test");

jquery change class name

You can do This : $("#td_id").removeClass('Old_class'); $("#td_id").addClass('New_class'); Or You can do This

$("#td_id").removeClass('Old_class').addClass('New_class');

Java, How to get number of messages in a topic in apache kafka

It is not java, but may be useful

./bin/kafka-run-class.sh kafka.tools.GetOffsetShell 
  --broker-list <broker>:  <port> 
  --topic <topic-name> --time -1 --offsets 1 
  | awk -F  ":" '{sum += $3} END {print sum}'

How can I enable CORS on Django REST Framework

pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
    ...
)

CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
    'http://localhost:3030',
]

more details: https://github.com/ottoyiu/django-cors-headers/#configuration

read the official documentation can resolve almost all problem

How do I create dynamic properties in C#?

I'm not sure you really want to do what you say you want to do, but it's not for me to reason why!

You cannot add properties to a class after it has been JITed.

The closest you could get would be to dynamically create a subtype with Reflection.Emit and copy the existing fields over, but you'd have to update all references to the the object yourself.

You also wouldn't be able to access those properties at compile time.

Something like:

public class Dynamic
{
    public Dynamic Add<T>(string key, T value)
    {
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly"), AssemblyBuilderAccess.Run);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Dynamic.dll");
        TypeBuilder typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString());
        typeBuilder.SetParent(this.GetType());
        PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(key, PropertyAttributes.None, typeof(T), Type.EmptyTypes);

        MethodBuilder getMethodBuilder = typeBuilder.DefineMethod("get_" + key, MethodAttributes.Public, CallingConventions.HasThis, typeof(T), Type.EmptyTypes);
        ILGenerator getter = getMethodBuilder.GetILGenerator();
        getter.Emit(OpCodes.Ldarg_0);
        getter.Emit(OpCodes.Ldstr, key);
        getter.Emit(OpCodes.Callvirt, typeof(Dynamic).GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(typeof(T)));
        getter.Emit(OpCodes.Ret);
        propertyBuilder.SetGetMethod(getMethodBuilder);

        Type type = typeBuilder.CreateType();

        Dynamic child = (Dynamic)Activator.CreateInstance(type);
        child.dictionary = this.dictionary;
        dictionary.Add(key, value);
        return child;
    }

    protected T Get<T>(string key)
    {
        return (T)dictionary[key];
    }

    private Dictionary<string, object> dictionary = new Dictionary<string,object>();
}

I don't have VS installed on this machine so let me know if there are any massive bugs (well... other than the massive performance problems, but I didn't write the specification!)

Now you can use it:

Dynamic d = new Dynamic();
d = d.Add("MyProperty", 42);
Console.WriteLine(d.GetType().GetProperty("MyProperty").GetValue(d, null));

You could also use it like a normal property in a language that supports late binding (for example, VB.NET)

How can I get a Dialog style activity window to fill the screen?

You may add this values to your style android:windowMinWidthMajor and android:windowMinWidthMinor

<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
    ...
    <item name="android:windowMinWidthMajor">97%</item>
    <item name="android:windowMinWidthMinor">97%</item>
</style>

404 Not Found The requested URL was not found on this server

If your .htaccess file is ok and the problem persist try to make the AllowOverride directive enabled in your httpd.conf. If the AllowOverride directive is set to None in your Apache httpd.config file, then .htaccess files are completely ignored. Example of enabled AllowOverride directive in httpd.config:

 <Directory />
    Options FollowSymLinks
    **AllowOverride All**
 </Directory>

Therefor restart your server.

How to group time by hour or by 10 minutes

select dateadd(minute, datediff(minute, 0, Date), 0),
       sum(SnapShotValue)
FROM [FRIIB].[dbo].[ArchiveAnalog]
group by dateadd(minute, datediff(minute, 0, Date), 0)

How to get Bitmap from an Uri?

Here's the correct way of doing it:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri imageUri = data.getData();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}

If you need to load very large images, the following code will load it in in tiles (avoiding large memory allocations):

BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(myStream, false);  
Bitmap region = decoder.decodeRegion(new Rect(10, 10, 50, 50), null);

See the answer here

Transform DateTime into simple Date in Ruby on Rails

Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.

self.date || self.exif_date_time_original.to_s

How to revert a merge commit that's already pushed to remote branch?

The correctly marked answer worked for me but I had to spend some time to determine whats going on.. So I decided to add an answer with simple straightforward steps for cases like mine..

Lets say we got branches A and B.. You merged branch A into branch B and pushed branch B to itself so now the merge is part of it.. But you want to go back to the last commit before the merge.. What do you do?

  1. Go to your git root folder (the project folder usually) and use git log
  2. You will see the history of recent commits - the commits have commit/author/date properties while the merges also have a merge property - so you see them like this:

    commit: <commitHash> Merge: <parentHashA> <parentHashB> Author: <author> Date: <date>

  3. Use git log <parentHashA> and git log <parentHashB> - you will see the commit histories of those parent branches - the first commits in the list are the latest ones

  4. Take the <commitHash> of the commit you want, go to your git root folder and use git checkout -b <newBranchName> <commitHash> - that will create a new branch starting from that last commit you've chosen before the merge.. Voila, ready!

How to remove files and directories quickly via terminal (bash shell)

rm -rf some_dir

-r "recursive" -f "force" (suppress confirmation messages)

Be careful!

WPF Check box: Check changed handling

A simple and proper way I've found to Handle Checked/Unchecked events using MVVM pattern is the Following, with Caliburn.Micro :

 <CheckBox IsChecked="{Binding IsCheckedBooleanProperty}" Content="{DynamicResource DisplayContent}" cal:Message.Attach="[Event Checked] = [Action CheckBoxClicked()]; [Event Unchecked] = [Action CheckBoxClicked()]" />

And implement a Method CheckBoxClicked() in the ViewModel, to do stuff you want.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

I have found when I am using a manifest that the listing of jars for the classpath need to have a space after the listing of each jar e.g. "required_lib/sun/pop3.jar required_lib/sun/smtp.jar ". Even if it is the last in the list.

Pandas aggregate count distinct

'nunique' is an option for .agg() since pandas 0.20.0, so:

df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})

How to add a downloaded .box file to Vagrant?

First rename the Vagrantfile then

vagrant box add new-box name-of-the-box.box
vagrant init new-box
vagrant up

Just to check status

vagrant status

that's all

Skip Git commit hooks

Maybe (from git commit man page):

git commit --no-verify

-n  
--no-verify

This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).

As commented by Blaise, -n can have a different role for certain commands.
For instance, git push -n is actually a dry-run push.
Only git push --no-verify would skip the hook.


Note: Git 2.14.x/2.15 improves the --no-verify behavior:

See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster -- in commit c3e034f, 23 Aug 2017)

commit: skip discarding the index if there is no pre-commit hook

"git commit" used to discard the index and re-read from the filesystem just in case the pre-commit hook has updated it in the middle; this has been optimized out when we know we do not run the pre-commit hook.


Davi Lima points out in the comments the git cherry-pick does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue, after a merge conflict resolution.

PG::ConnectionBad - could not connect to server: Connection refused

I had the same problem in production (development everything worked), in my case the DB server is not on the same machine as the app, so finally what worked is just to migrate by writing:

bundle exec rake db:migrate RAILS_ENV=production

and then restart the server and everything worked.

With android studio no jvm found, JAVA_HOME has been set

It says that it should be a 64-bit JDK. I have a feeling that you installed (at a previous time) a 32-bit version of Java. The path for all 32-bit applications in Windows 7 and Vista is:

C:\Program Files (x86)\

You were setting the JAVA_HOME variable to the 32-bit version of Java. Set your JAVA_HOME variable to the following:

C:\Program Files\Java\jdk1.7.0_45

If that does not work, check that the JDK version is 1.7.0_45. If not, change the JAVA_HOME variable to (with JAVAVERSION as the Java version number:

C:\Program Files\Java\jdkJAVAVERSION

Any way to clear python's IDLE window?

None of these solutions worked for me on Windows 7 and within IDLE. Wound up using PowerShell, running Python within it and exiting to call "cls" in PowerShell to clear the window.

CONS: Assumes Python is already in the PATH variable. Also, this does clear your Python variables (though so does restarting the shell).

PROS: Retains any window customization you've made (color, font-size).

Use SELECT inside an UPDATE query

I know this topic is old, but I thought I could add something to it.

I could not make an Update with Select query work using SQL in MS Access 2010. I used Tomalak's suggestion to make this work. I had a screenshot, but am apparently too much of a newb on this site to be able to post it.

I was able to do this using the Query Design tool, but even as I was looking at a confirmed successful update query, Access was not able to show me the SQL that made it happen. So I could not make this work with SQL code alone.

I created and saved my select query as a separate query. In the Query Design tool, I added the table I'm trying to update the the select query I had saved (I put the unique key in the select query so it had a link between them). Just as Tomalak had suggested, I changed the Query Type to Update. I then just had to choose the fields (and designate the table) I was trying to update. In the "Update To" fields, I typed in the name of the fields from the select query I had brought in.

This format was successful and updated the original table.

How do I create a ListView with rounded corners in Android?

This was incredibly handy to me. I would like to suggest another workaround to perfectly highlight the rounded corners if you are using your own CustomAdapter.

Defining XML Files

First of all, go inside your drawable folder and create 4 different shapes:

  • shape_top

    <gradient
        android:startColor="#ffffff"
        android:endColor="#ffffff"
        android:angle="270"/>
    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
    

  • shape_normal

    <gradient
        android:startColor="#ffffff"
        android:endColor="#ffffff"
        android:angle="270"/>
    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
    

  • shape_bottom

    <gradient
        android:startColor="#ffffff"
        android:endColor="#ffffff"
        android:angle="270"/>
    <corners
        android:bottomRightRadius="10dp"
        android:bottomRightRadius="10dp"/>
    

  • shape_rounded

    <gradient
        android:startColor="#ffffff"
        android:endColor="#ffffff"
        android:angle="270"/>
    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"
        android:bottomRightRadius="10dp"
        android:bottomRightRadius="10dp"/>
    

Now, create a different row layout for each shape, i.e. for shape_top :

  • You can also do this programatically changing the background.

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:fontFamily="sans-serif-light"
        android:text="TextView"
        android:textSize="22dp" />
    
    <TextView
        android:id="@+id/txtValue1"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:textSize="22dp"
        android:layout_gravity="right|center"
        android:gravity="center|right"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="35dp"
        android:text="Fix"
        android:scaleType="fitEnd" />
    

And define a selector for each shaped-list, i.e. for shape_top:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Selected Item -->

    <item android:state_selected="true"
        android:drawable="@drawable/shape_top" />
    <item android:state_activated="true"
        android:drawable="@drawable/shape_top" />

    <!-- Default Item -->
    <item android:state_selected="false"
        android:drawable="@android:color/transparent" />
</selector>

Change your CustomAdapter

Finally, define the layout options inside your CustomAdapter:

if(position==0)
{
 convertView = mInflater.inflate(R.layout.list_layout_top, null);
}
else
{
 convertView = mInflater.inflate(R.layout.list_layout_normal, null);
}

if(position==getCount()-1)
{
convertView = mInflater.inflate(R.layout.list_layout_bottom, null);
}

if(getCount()==1)
{
convertView = mInflater.inflate(R.layout.list_layout_unique, null);
}

And that's done!

How to list all Git tags?

And here is how you find the remote tags:

git ls-remote --tags origin

Start new Activity and finish current one in Android?

Use finish like this:

Intent i = new Intent(Main_Menu.this, NextActivity.class);
finish();  //Kill the activity from which you will go to next activity 
startActivity(i);

FLAG_ACTIVITY_NO_HISTORY you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.

To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY

copying all contents of folder to another folder using batch file?

if you want remove the message that tells if the destination is a file or folder you just add a slash:

xcopy /s c:\Folder1 d:\Folder2\

Vertically align text to top within a UILabel

This is an old solution, use the autolayout on iOS >= 6

My solution:

  1. Split lines by myself (ignoring label wrap settings)
  2. Draw lines by myself (ignoring label alignment)

@interface UITopAlignedLabel : UILabel

@end

@implementation UITopAlignedLabel

#pragma mark Instance methods

- (NSArray*)splitTextToLines:(NSUInteger)maxLines {
    float width = self.frame.size.width;

    NSArray* words = [self.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSMutableArray* lines = [NSMutableArray array];

    NSMutableString* buffer = [NSMutableString string];    
    NSMutableString* currentLine = [NSMutableString string];

    for (NSString* word in words) {
        if ([buffer length] > 0) {
            [buffer appendString:@" "];
        }

        [buffer appendString:word];

        if (maxLines > 0 && [lines count] == maxLines - 1) {
            [currentLine setString:buffer];
            continue;
        }

        float bufferWidth = [buffer sizeWithFont:self.font].width;

        if (bufferWidth < width) {
            [currentLine setString:buffer];
        }
        else {
            [lines addObject:[NSString stringWithString:currentLine]];

            [buffer setString:word];
            [currentLine setString:buffer];
        }
    }

    if ([currentLine length] > 0) {
        [lines addObject:[NSString stringWithString:currentLine]];
    }

    return lines;
}

- (void)drawRect:(CGRect)rect {
    if ([self.text length] == 0) {
        return;
    }

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, self.textColor.CGColor);
    CGContextSetShadowWithColor(context, self.shadowOffset, 0.0f, self.shadowColor.CGColor);

    NSArray* lines = [self splitTextToLines:self.numberOfLines];
    NSUInteger numLines = [lines count];

    CGSize size = self.frame.size;
    CGPoint origin = CGPointMake(0.0f, 0.0f);

    for (NSUInteger i = 0; i < numLines; i++) {
        NSString* line = [lines objectAtIndex:i];

        if (i == numLines - 1) {
            [line drawAtPoint:origin forWidth:size.width withFont:self.font lineBreakMode:UILineBreakModeTailTruncation];            
        }
        else {
            [line drawAtPoint:origin forWidth:size.width withFont:self.font lineBreakMode:UILineBreakModeClip];
        }

        origin.y += self.font.lineHeight;

        if (origin.y >= size.height) {
            return;
        }
    }
}

@end