Programs & Examples On #Rssi

RSSI stands for Received signal strength indication

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

What if you do this (as was suggested earlier):

new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000

Re-render React component when prop changes

You could use KEY unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

Even better use implicit remoting to use a module from another Machine!

$s = New-PSSession Server-Name
Invoke-Command -Session $s -ScriptBlock {Import-Module ActiveDirectory}
Import-PSSession -Session $s -Module ActiveDirectory -Prefix REM

This will allow you to use the module off a remote PC for as long as the PSSession is connected.

More Information: https://technet.microsoft.com/en-us/library/ff720181.aspx

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Could not resolve Spring property placeholder

I still believe its to do with the props file not being located by spring. Do a quick test by passing the params as jvm params. i.e -Didm.url=....

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Call JavaScript function from C#

This may be helpful to you:

<script type="text/javascript">
    function Showalert() {
        alert('Profile not parsed!!');
        window.parent.parent.parent.location.reload();
    }
    function ImportingDone() {
        alert('Importing done successfull.!');
        window.parent.parent.parent.location.reload();
    }
</script>

if (SelectedRowCount == 0)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
    ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}

mongodb count num of distinct values per field/key

To find distinct in field_1 in collection but we want some WHERE condition too than we can do like following :

db.your_collection_name.distinct('field_1', {WHERE condition here and it should return a document})

So, find number distinct names from a collection where age > 25 will be like :

db.your_collection_name.distinct('names', {'age': {"$gt": 25}})

Hope it helps!

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

Changing Java Date one hour back

Get the time in milliseconds, minus your minutes in milliseconds and convert it to Date. Here you need to objectify one!!!

    int minutes = 60;
    long currentDateTime = System.currentTimeMillis();
    Date currentDate = new Date(currentDateTime - minutes*60*1000);
    System.out.println(currentDate);

How can I unstage my files again after making a local commit?

Use:

git reset HEAD^

That does a "mixed" reset by default, which will do what you asked; put foo.java in unstaged, removing the most recent commit.

How to respond to clicks on a checkbox in an AngularJS directive?

I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:

<input type="checkbox" ng-model="entity.isChecked">

Whenever the user checks or unchecks the checkbox the entity.isChecked value will change too.

If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.

When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners array. The listeners in this array get called after the model value has been set, avoiding this problem).

<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">

... and in the controller ...

var model = {};
$scope.model = model;

// This property is bound to the checkbox in the table header
model.allItemsSelected = false;

// Fired when an entity in the table is checked
$scope.selectEntity = function () {
    // If any entity is not checked, then uncheck the "allItemsSelected" checkbox
    for (var i = 0; i < model.entities.length; i++) {
        if (!model.entities[i].isChecked) {
            model.allItemsSelected = false;
            return;
        }
    }

    // ... otherwise ensure that the "allItemsSelected" checkbox is checked
    model.allItemsSelected = true;
};

Similarly, the "Check All" checkbox in the header:

<th>
    <input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>

... and ...

// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
    // Loop through all the entities and set their isChecked property
    for (var i = 0; i < model.entities.length; i++) {
        model.entities[i].isChecked = model.allItemsSelected;
    }
};

CSS

What is the best way to... add a CSS class to the <tr> containing the entity to reflect its selected state?

If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr> element to dynamically add or remove the class whenever the entity property changes:

<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">

See the full Plunker here.

How to change the default GCC compiler in Ubuntu?

Now, there is gcc-4.9 available for Ubuntu/precise.

Create a group of compiler alternatives where the distro compiler has a higher priority:

root$ VER=4.6 ; PRIO=60
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

root$ VER=4.9 ; PRIO=40
root$ update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
root$ update-alternatives --install /usr/bin/cpp cpp-bin /usr/bin/cpp-$VER $PRIO

NOTE: g++ version is changed automatically with a gcc version switch. cpp-bin has to be done separately as there exists a "cpp" master alternative.

List available compiler alternatives:

root$ update-alternatives --list gcc
root$ update-alternatives --list cpp-bin

To select manually version 4.9 of gcc, g++ and cpp, do:

root$ update-alternatives --config gcc
root$ update-alternatives --config cpp-bin

Check compiler versions:

root$ for i in gcc g++ cpp ; do $i --version ; done

Restore distro compiler settings (here: back to v4.6):

root$ update-alternatives --auto gcc
root$ update-alternatives --auto cpp-bin

Android: Expand/collapse animation

@Tom Esterez's answer, but updated to use view.measure() properly per Android getMeasuredHeight returns wrong values !

    // http://easings.net/
    Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f);

    public static Animation expand(final View view) {
        int matchParentMeasureSpec = View.MeasureSpec.makeMeasureSpec(((View) view.getParent()).getWidth(), View.MeasureSpec.EXACTLY);
        int wrapContentMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(matchParentMeasureSpec, wrapContentMeasureSpec);
        final int targetHeight = view.getMeasuredHeight();

        // Older versions of android (pre API 21) cancel animations for views with a height of 0 so use 1 instead.
        view.getLayoutParams().height = 1;
        view.setVisibility(View.VISIBLE);

        Animation animation = new Animation() {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {

               view.getLayoutParams().height = interpolatedTime == 1
                    ? ViewGroup.LayoutParams.WRAP_CONTENT
                    : (int) (targetHeight * interpolatedTime);

            view.requestLayout();
        }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        animation.setInterpolator(easeInOutQuart);
        animation.setDuration(computeDurationFromHeight(view));
        view.startAnimation(animation);

        return animation;
    }

    public static Animation collapse(final View view) {
        final int initialHeight = view.getMeasuredHeight();

        Animation a = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1) {
                    view.setVisibility(View.GONE);
                } else {
                    view.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
                    view.requestLayout();
                }
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        a.setInterpolator(easeInOutQuart);

        int durationMillis = computeDurationFromHeight(view);
        a.setDuration(durationMillis);

        view.startAnimation(a);

        return a;
    }

    private static int computeDurationFromHeight(View view) {
        // 1dp/ms * multiplier
        return (int) (view.getMeasuredHeight() / view.getContext().getResources().getDisplayMetrics().density);
    }

Responsive Google Map?

My Responsive [Solution] Google Map in Foundation 4 Modal


JS

Create an external JavaScript file (i.e. mymap.js) with the following code

google.maps.visualRefresh = true; //Optional

var respMap;

function mymapini() {
    var mapPos = new google.maps.LatLng(-0.172175,1.5); //Set the coordinates
    var mapOpts = {
    zoom: 10, //You can change this according your needs
    disableDefaultUI: true, //Disabling UI Controls (Optional)
    center: mapPos, //Center the map according coordinates
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    respMap = new google.maps.Map(document.getElementById('mymap'),
      mapOpts);

    var mapMarker = new google.maps.Marker({
          position: mapPos,
          map: respMap,
          title: 'You can put any title'
      });

    //This centers automatically to the marker even if you resize your window
    google.maps.event.addListener(respMap, 'idle', function() {
    window.setTimeout(function() {
      respMap.panTo(mapPos.getPosition());
    }, 250);    
  });
}

google.maps.event.addDomListener(window, 'load', mymapini);

$("#modalOpen").click(function(){ //Use it like <a href="#" id="modalOpen"...
    $("#myModal").show(); //ID from the Modal <div id="myModal">...
    google.maps.event.trigger(respMap, 'resize');
});

HTML

Add the following code before the tag:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="js/mymap.js"></script>

Add this to the modal code:

<div id="mymap"></div>

CSS

Add this to your stylesheet:

#mymap { margin: 0; padding: 0; width:100%; height: 400px;}

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];

it will create json object. no need to parse.

jsonStringQuotes = "'" + jsonStringNoQuotes + "'";

will return '[object]'

thats why it(below) is causing error

var myData = JSON.parse(jsonStringQuotes);

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

How do I get elapsed time in milliseconds in Ruby?

As stated already, you can operate on Time objects as if they were numeric (or floating point) values. These operations result in second resolution which can easily be converted.

For example:

def time_diff_milli(start, finish)
   (finish - start) * 1000.0
end

t1 = Time.now
# arbitrary elapsed time
t2 = Time.now

msecs = time_diff_milli t1, t2

You will need to decide whether to truncate that or not.

How to perform a sum of an int[] array

Once is out (March 2014) you'll be able to use streams:

int sum = IntStream.of(a).sum();

or even

int sum = IntStream.of(a).parallel().sum();

Download image from the site in .NET/C#

There is no need to involve any image classes, you can simply call WebClient.DownloadFile:

string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}

Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:

private static void DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Moved || 
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

In brief, it makes a request for the file, verifies that the response code is one of OK, Moved or Redirect and also that the ContentType is an image. If those conditions are true, the file is downloaded.

Directory index forbidden by Options directive

Another issue that you might run into if you're running RHEL (I ran into it) is that there is a default welcome page configured with the httpd package that will override your settings, even if you put Options Indexes. The file is in /etc/httpd/conf.d/welcome.conf. See the following link for more info: http://wpapi.com/solved-issue-directory-index-forbidden-by-options-directive/

Width of input type=text element

I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.

How to run a C# console application with the console hidden

If you wrote the console application you can make it hidden by default.

Create a new console app then then change the "Output Type" type to "Windows Application" (done in the project properties)

Difference between HashMap, LinkedHashMap and TreeMap

All three represent mapping from unique keys to values, and therefore implement the Map interface.

  1. HashMap is a map based on hashing of the keys. It supports O(1) get/put operations. Keys must have consistent implementations of hashCode() and equals() for this to work.

  2. LinkedHashMap is very similar to HashMap, but it adds awareness to the order at which items are added (or accessed), so the iteration order is the same as insertion order (or access order, depending on construction parameters).

  3. TreeMap is a tree based mapping. Its put/get operations take O(log n) time. It requires items to have some comparison mechanism, either with Comparable or Comparator. The iteration order is determined by this mechanism.

How to make shadow on border-bottom?

use box-shadow with no horizontal offset.

http://www.css3.info/preview/box-shadow/

eg.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 10px 5px #888888;_x000D_
  -moz-box-shadow: 0 10px 5px #888888;_x000D_
  box-shadow: 0 10px 5px #888888;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

There will be a slight shadow on the sides with a large blur radius (5px in above example)

jQuery: find element by text

Best way in my opinion.

$.fn.findByContentText = function (text) {
    return $(this).contents().filter(function () {
        return $(this).text().trim() == text.trim();
    });
};

docker error - 'name is already in use by container'

Simple Solution: Goto your docker folder in the system and delete .raw file or docker archive with large size.

Convert NSDate to NSString

Hope to add more value by providing the normal formatter including the year, month and day with the time. You can use this formatter for more than just a year

[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"]; 

How do I jump to a closing bracket in Visual Studio Code?

Extension TabOut was the option i was looking for.

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

To recap some of these answers now on 2018, where ES6 is the standard.

Starting with the object:

let const={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
  • Just blindly getting the values on an array, do not care of the keys:

_x000D_
_x000D_
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};_x000D_
console.log(Object.values(obj));_x000D_
//[9,8,7,6,5,4,3,2,1,0,5]
_x000D_
_x000D_
_x000D_

  • Simple getting the pairs on an array:

_x000D_
_x000D_
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};_x000D_
console.log(Object.entries(obj));_x000D_
//[["1",9],["2",8],["3",7],["4",6],["5",5],["6",4],["7",3],["8",2],["9",1],["10",0],["12",5]]
_x000D_
_x000D_
_x000D_

  • Same as previous, but with numeric keys on each pair:

_x000D_
_x000D_
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};_x000D_
console.log(Object.entries(obj).map(([k,v])=>[+k,v]));_x000D_
//[[1,9],[2,8],[3,7],[4,6],[5,5],[6,4],[7,3],[8,2],[9,1],[10,0],[12,5]]
_x000D_
_x000D_
_x000D_

  • Using the object property as key for a new array (could create sparse arrays):

_x000D_
_x000D_
const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};_x000D_
console.log(Object.entries(obj).reduce((ini,[k,v])=>(ini[k]=v,ini),[]));_x000D_
//[undefined,9,8,7,6,5,4,3,2,1,0,undefined,5]
_x000D_
_x000D_
_x000D_

This last method, it could also reorganize the array order depending the value of keys. Sometimes this could be the desired behaviour (sometimes don't). But the advantage now is that the values are indexed on the correct array slot, essential and trivial to do searches on it.

  • Map instead of Array

Finally (not part of the original question, but for completeness), if you need to easy search using the key or the value, but you don't want sparse arrays, no duplicates and no reordering without the need to convert to numeric keys (even can access very complex keys), then array (or object) is not what you need. I will recommend Map instead:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

let r=new Map(Object.entries(obj));
r.get("4"); //6
r.has(8); //true

In C++ check if std::vector<string> contains a certain value

it's in <algorithm> and called std::find.

How do you detect Credit card type based on number?

Try this.For swift.

func checkCardValidation(number : String) -> Bool
{
    let reversedInts = number.characters.reversed().map { Int(String($0)) }
        return reversedInts.enumerated().reduce(0, {(sum, val) in
            let odd = val.offset % 2 == 1
            return sum + (odd ? (val.element! == 9 ? 9 : (val.element! * 2) % 9) : val.element!)
        }) % 10 == 0
}

Use.

if (self.checkCardValidation(number: "yourNumber") == true) {
     print("Card Number valid")
}else{
     print("Card Number not valid")
}

NoClassDefFoundError - Eclipse and Android

I didn't have to put the jar-library in assets or lib(s), but only tick the box for this jar in Properties -> Java Build Path -> "Order and Export" (it was listed before, but not selected)

How to reload a div without reloading the entire page?

$("#div_element").load('script.php');

demo: http://sandbox.phpcode.eu/g/2ecbe/3

whole code:

<div id="submit">ajax</div> 
<div id="div_element"></div> 
<script> 
$('#submit').click(function(event){ 
   $("#div_element").load('script.php?html=some_arguments');  

}); 
</script> 

Spring @Transactional read-only propagation

First of all, since Spring doesn't do persistence itself, it cannot specify what readOnly should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.

If you specify readOnly as true, the flush mode will be set as FlushMode.NEVER in the current Hibernate Session preventing the session from committing the transaction.

Furthermore, setReadOnly(true) will be called on the JDBC Connection, which is also a hint to the underlying database. If your database supports it (most likely it does), this has basically the same effect as FlushMode.NEVER, but it's stronger since you cannot even flush manually.

Now let's see how transaction propagation works.

If you don't explicitly set readOnly to true, you will have read/write transactions. Depending on the transaction attributes (like REQUIRES_NEW), sometimes your transaction is suspended at some point, a new one is started and eventually committed, and after that the first transaction is resumed.

OK, we're almost there. Let's see what brings readOnly into this scenario.

If a method in a read/write transaction calls a method that requires a readOnly transaction, the first one should be suspended, because otherwise a flush/commit would happen at the end of the second method.

Conversely, if you call a method from within a readOnly transaction that requires read/write, again, the first one will be suspended, since it cannot be flushed/committed, and the second method needs that.

In the readOnly-to-readOnly, and the read/write-to-read/write cases the outer transaction doesn't need to be suspended (unless you specify propagation otherwise, obviously).

Fragment onResume() & onPause() is not called on backstack

Here's my more robust version of Gor's answer (using fragments.size()is unreliable due to size not being decremented after fragment is popped)

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (getFragmentManager() != null) {

                Fragment topFrag = NavigationHelper.getCurrentTopFragment(getFragmentManager());

                if (topFrag != null) {
                    if (topFrag instanceof YourFragment) {
                        //This fragment is being shown. 
                    } else {
                        //Navigating away from this fragment. 
                    }
                }
            }
        }
    });

And the 'getCurrentTopFragment' method:

public static Fragment getCurrentTopFragment(FragmentManager fm) {
    int stackCount = fm.getBackStackEntryCount();

    if (stackCount > 0) {
        FragmentManager.BackStackEntry backEntry = fm.getBackStackEntryAt(stackCount-1);
        return  fm.findFragmentByTag(backEntry.getName());
    } else {
        List<Fragment> fragments = fm.getFragments();
        if (fragments != null && fragments.size()>0) {
            for (Fragment f: fragments) {
                if (f != null && !f.isHidden()) {
                    return f;
                }
            }
        }
    }
    return null;
}

Google Map API v3 — set bounds and center

Use below one,

map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

Break or return from Java 8 stream forEach?

You can use java8 + rxjava.

//import java.util.stream.IntStream;
//import rx.Observable;

    IntStream intStream  = IntStream.range(1,10000000);
    Observable.from(() -> intStream.iterator())
            .takeWhile(n -> n < 10)
            .forEach(n-> System.out.println(n));

Searching in a ArrayList with custom objects for certain strings

Probably something like:

ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points

//Traversal
for(DataPoint myPoint : myList) {
    if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
        //Process data do whatever you want
        System.out.println("Found it!");
     }
}

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

How to get a URL parameter in Express?

Express 4.x

To get a URL parameter's value, use req.params

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.params.tagId);
});

// GET /p/5
// tagId is set to 5

If you want to get a query parameter ?tagId=5, then use req.query

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query.tagId);
});

// GET /p?tagId=5
// tagId is set to 5

Express 3.x

URL parameter

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.param("tagId"));
});

// GET /p/5
// tagId is set to 5

Query parameter

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query("tagId"));
});

// GET /p?tagId=5
// tagId is set to 5

CSS background opacity with rgba not working in IE 8

To use rgba background in IE there is a fallback.

We have to use filter property. that uses ARGB

    background:none;
    -ms-filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#33ffffff,endColorstr=#33ffffff);
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#33ffffff,endColorstr=#33ffffff);
    zoom: 1;

this is fallback for rgba(255, 255, 255, 0.2)

Change #33ffffff according to yours.

How to calculate ARGB for RGBA

How to check if a string starts with one of several prefixes?

Do you mean this:

if (newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || ...)

Or you could use regular expression:

if (newStr4.matches("(Mon|Tues|Wed|Thurs|Fri).*"))

C compiler for Windows?

GCC works fine. Note that MSVC is not necessarily a valid solution because it does not support C99.

Replace comma with newline in sed on MacOS?

FWIW, the following line works in windows and replaces semicolons in my path variables with a newline. I'm using the tools installed under my git bin directory.

echo %path% | sed -e $'s/;/\\n/g' | less

Show an image preview before upload

_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
    var files = evt.target.files;_x000D_
_x000D_
    // Loop through the FileList and render image files as thumbnails._x000D_
    for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
      // Only process image files._x000D_
      if (!f.type.match('image.*')) {_x000D_
        continue;_x000D_
      }_x000D_
_x000D_
      var reader = new FileReader();_x000D_
_x000D_
      // Closure to capture the file information._x000D_
      reader.onload = (function(theFile) {_x000D_
        return function(e) {_x000D_
          // Render thumbnail._x000D_
          var span = document.createElement('span');_x000D_
          span.innerHTML = _x000D_
          [_x000D_
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
            e.target.result,_x000D_
            '" title="', escape(theFile.name), _x000D_
            '"/>'_x000D_
          ].join('');_x000D_
          _x000D_
          document.getElementById('list').insertBefore(span, null);_x000D_
        };_x000D_
      })(f);_x000D_
_x000D_
      // Read in the image file as a data URL._x000D_
      reader.readAsDataURL(f);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
_x000D_
_x000D_

Remove x-axis label/text in chart.js

UPDATE chart.js 2.1 and above

var chart = new Chart(ctx, {
    ...
    options:{
        scales:{
            xAxes: [{
                display: false //this will remove all the x-axis grid lines
            }]
        }
    }
});


var chart = new Chart(ctx, {
    ...
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    display: false //this will remove only the label
                }
            }]
        }
    }
});

Reference: chart.js documentation

Old answer (written when the current version was 1.0 beta) just for reference below:

To avoid displaying labels in chart.js you have to set scaleShowLabels : false and also avoid to pass the labels:

<script>
    var options = {
        ...
        scaleShowLabels : false
    };
    var lineChartData = {
        //COMMENT THIS LINE TO AVOID DISPLAYING THE LABELS
        //labels : ["1","2","3","4","5","6","7"],
        ... 
    }
    ...
</script>

How to implement infinity in Java?

Only Double and Float type support POSITIVE_INFINITY constant.

Find nearest value in numpy array

All the answers are beneficial to gather the information to write efficient code. However, I have written a small Python script to optimize for various cases. It will be the best case if the provided array is sorted. If one searches the index of the nearest point of a specified value, then bisect module is the most time efficient. When one search the indices correspond to an array, the numpy searchsorted is most efficient.

import numpy as np
import bisect
xarr = np.random.rand(int(1e7))

srt_ind = xarr.argsort()
xar = xarr.copy()[srt_ind]
xlist = xar.tolist()
bisect.bisect_left(xlist, 0.3)

In [63]: %time bisect.bisect_left(xlist, 0.3) CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 22.2 µs

np.searchsorted(xar, 0.3, side="left")

In [64]: %time np.searchsorted(xar, 0.3, side="left") CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 98.9 µs

randpts = np.random.rand(1000)
np.searchsorted(xar, randpts, side="left")

%time np.searchsorted(xar, randpts, side="left") CPU times: user 4 ms, sys: 0 ns, total: 4 ms Wall time: 1.2 ms

If we follow the multiplicative rule, then numpy should take ~100 ms which implies ~83X faster.

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

The same thing happened to me. Here is what I did in order to get it successfully installed. I downloaded KB2999226 update from Microsofts website here: https://www.microsoft.com/en-us/download/details.aspx?id=49093

After installing this package, I started the installation process again. That worked for me.

Post form data using HttpWebRequest

You are encoding the form incorrectly. You should only encode the values:

StringBuilder postData = new StringBuilder();
postData.Append("username=" + HttpUtility.UrlEncode(uname) + "&");
postData.Append("password=" + HttpUtility.UrlEncode(pword) + "&");
postData.Append("url_success=" + HttpUtility.UrlEncode(urlSuccess) + "&");
postData.Append("url_failed=" + HttpUtility.UrlEncode(urlFailed));

edit

I was incorrect. According to RFC1866 section 8.2.1 both names and values should be encoded.

But for the given example, the names do not have any characters that needs to be encoded, so in this case my code example is correct ;)

The code in the question is still incorrect as it would encode the equal sign which is the reason to why the web server cannot decode it.

A more proper way would have been:

StringBuilder postData = new StringBuilder();
postData.AppendUrlEncoded("username", uname);
postData.AppendUrlEncoded("password", pword);
postData.AppendUrlEncoded("url_success", urlSuccess);
postData.AppendUrlEncoded("url_failed", urlFailed);

//in an extension class
public static void AppendUrlEncoded(this StringBuilder sb, string name, string value)
{
    if (sb.Length != 0)
        sb.Append("&");
    sb.Append(HttpUtility.UrlEncode(name));
    sb.Append("=");
    sb.Append(HttpUtility.UrlEncode(value));
}

How to cut an entire line in vim and paste it?

  1. Go to the line, and first press esc, and then Shift + v.

(This would have highlighted the line)

  1. press d

(The line is now deleted)

  1. Go to the location, where you wanted to paste the line, and hit p.

In a nutshell,

Esc -> Shift + v -> d -> p

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Eclipse 3.5 Unable to install plugins

I was getting the error while trying to connect for updates. Just did as in the above answer -

Window-> Preferences-> General-> Network

There the default provider was set as Native. I changed it to direct as my laptop didn't need to connect to any proxy.

Applied and it is working fine.

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.

class NormalizeData:

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

    def execute(self):
        if isinstance(self.element, dict):
            self.__iterate()
        else:
            return

    def __iterate(self):
        for key in self.element:
            if isinstance(self.element[key], <ClassName>):
                self.element[key] = str(self.element[key])

            node = NormalizeData(self.element[key])
            node.execute()

datatable jquery - table header width not aligned with body width

$('.DataTables_sort_wrapper').trigger("click");

nuget 'packages' element is not declared warning

This works and remains even after adding a new package:

Add the following !DOCTYPE above the <packages> element:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE packages [
  <!ELEMENT packages (package*)>
  <!ELEMENT package EMPTY>
  <!ATTLIST package
  id CDATA #REQUIRED
  version CDATA #REQUIRED
  targetFramework CDATA #REQUIRED
  developmentDependency CDATA #IMPLIED>
]>

printf formatting (%d versus %u)

%u prints unsigned integer

%d prints signed integer

to get a pointer address use %p

Other List of Formatting Escapes:

Here are the full list of formatting escapes. I am just giving a screen shot from this page

enter image description here

MySQL select rows where left join is null

You could use the following query:

SELECT  table1.id 
FROM    table1 
        LEFT JOIN table2 
            ON table1.id IN (table2.user_one, table2.user_two)
WHERE   table2.user_one IS NULL;

Although, depending on your indexes on table2 you may find that two joins performs better:

SELECT  table1.id 
FROM    table1 
        LEFT JOIN table2 AS t1
            ON table1.id = t1.user_one
        LEFT JOIN table2 AS t2
            ON table1.id = t2.user_two
WHERE   t1.user_one IS NULL
AND     t2.user_two IS NULL;

How to remove lines in a Matplotlib plot

This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D objects hanging around.

WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters.

Okay, here we go. Each matplotlib object (Figure, Axes, etc) provides access to its child artists via various attributes. The following example is getting quite long, but should be illuminating.

We start out by creating a Figure object, then add an Axes object to that figure. Note that ax and fig.axes[0] are the same object (same id()).

>>> #Create a figure
>>> fig = plt.figure()
>>> fig.axes
[]

>>> #Add an axes object
>>> ax = fig.add_subplot(1,1,1)

>>> #The object in ax is the same as the object in fig.axes[0], which is 
>>> #   a list of axes objects attached to fig 
>>> print ax
Axes(0.125,0.1;0.775x0.8)
>>> print fig.axes[0]
Axes(0.125,0.1;0.775x0.8)  #Same as "print ax"
>>> id(ax), id(fig.axes[0])
(212603664, 212603664) #Same ids => same objects

This also extends to lines in an axes object:

>>> #Add a line to ax
>>> lines = ax.plot(np.arange(1000))

>>> #Lines and ax.lines contain the same line2D instances 
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]
>>> print ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>]

>>> print lines[0]
Line2D(_line0)
>>> print ax.lines[0]
Line2D(_line0)

>>> #Same ID => same object
>>> id(lines[0]), id(ax.lines[0])
(216550352, 216550352)

If you were to call plt.show() using what was done above, you would see a figure containing a set of axes and a single line:

A figure containing a set of axes and a single line

Now, while we have seen that the contents of lines and ax.lines is the same, it is very important to note that the object referenced by the lines variable is not the same as the object reverenced by ax.lines as can be seen by the following:

>>> id(lines), id(ax.lines)
(212754584, 211335288)

As a consequence, removing an element from lines does nothing to the current plot, but removing an element from ax.lines removes that line from the current plot. So:

>>> #THIS DOES NOTHING:
>>> lines.pop(0)

>>> #THIS REMOVES THE FIRST LINE:
>>> ax.lines.pop(0)

So, if you were to run the second line of code, you would remove the Line2D object contained in ax.lines[0] from the current plot and it would be gone. Note that this can also be done via ax.lines.remove() meaning that you can save a Line2D instance in a variable, then pass it to ax.lines.remove() to delete that line, like so:

>>> #Create a new line
>>> lines.append(ax.plot(np.arange(1000)/2.0))
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and two lines

>>> #Remove that new line
>>> ax.lines.remove(lines[0])
>>> ax.lines
[<matplotlib.lines.Line2D object at 0xce84dx3>]

A figure containing a set of axes and only the second line

All of the above works for fig.axes just as well as it works for ax.lines

Now, the real problem here. If we store the reference contained in ax.lines[0] into a weakref.ref object, then attempt to delete it, we will notice that it doesn't get garbage collected:

>>> #Create weak reference to Line2D object
>>> from weakref import ref
>>> wr = ref(ax.lines[0])
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

>>> #Delete the line from the axes
>>> ax.lines.remove(wr())
>>> ax.lines
[]

>>> #Test weakref again
>>> print wr
<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
>>> print wr()
<matplotlib.lines.Line2D at 0xb757fd0>

The reference is still live! Why? This is because there is still another reference to the Line2D object that the reference in wr points to. Remember how lines didn't have the same ID as ax.lines but contained the same elements? Well, that's the problem.

>>> #Print out lines
>>> print lines
[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]

To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.

>>> #Reinitialize lines to empty list
>>> lines = []
>>> print lines
[]
>>> print wr
<weakref at 0xb758af8; dead>

So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn't, you are likely leaving a reference hanging out somewhere.

Running Selenium WebDriver python bindings in chrome

Mac OSX only

An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:

brew install chromedriver

That should put the chromedriver in your path and you should be all set.

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

difference between new String[]{} and new String[] in java

String array=new String[]; and String array=new String[]{}; both are invalid statement in java.

It will gives you an error that you are trying to assign String array to String datatype. More specifically error is like this Type mismatch: cannot convert from String[] to String

When to use RabbitMQ over Kafka?

RabbitMQ is a solid, general-purpose message broker that supports several protocols such as AMQP, MQTT, STOMP, etc. It can handle high throughput. A common use case for RabbitMQ is to handle background jobs or long-running task, such as file scanning, image scaling or PDF conversion. RabbitMQ is also used between microservices, where it serves as a means of communicating between applications, avoiding bottlenecks passing messages.

Kafka is a message bus optimized for high-throughput ingestion data streams and replay. Use Kafka when you have the need to move a large amount of data, process data in real-time or analyze data over a time period. In other words, where data need to be collected, stored, and handled. An example is when you want to track user activity on a webshop and generate suggested items to buy. Another example is data analysis for tracking, ingestion, logging or security.

Kafka can be seen as a durable message broker where applications can process and re-process streamed data on disk. Kafka has a very simple routing approach. RabbitMQ has better options if you need to route your messages in complex ways to your consumers. Use Kafka if you need to support batch consumers that could be offline or consumers that want messages at low latency. 

In order to understand how to read data from Kafka, we first need to understand its consumers and consumer groups. Partitions allow you to parallelize a topic by splitting the data across multiple nodes. Each record in a partition is assigned and identified by its unique offset. This offset points to the record in a partition. In the latest version of Kafka, Kafka maintains a numerical offset for each record in a partition. A consumer in Kafka can either automatically commit offsets periodically, or it can choose to control this committed position manually. RabbitMQ will keep all states about consumed/acknowledged/unacknowledged messages. I find Kafka more complex to understand than the case of RabbitMQ, where the message is simply removed from the queue once it's acked.

RabbitMQ's queues are fastest when they're empty, while Kafka retains large amounts of data with very little overhead - Kafka is designed for holding and distributing large volumes of messages. (If you plan to have very long queues in RabbitMQ you could have a look at lazy queues.)

Kafka is built from the ground up with horizontal scaling (scale by adding more machines) in mind, while RabbitMQ is mostly designed for vertical scaling (scale by adding more power).

RabbitMQ has a built-in user-friendly interface that lets you monitor and handle your RabbitMQ server from a web browser. Among other things, queues, connections, channels, exchanges, users and user permissions can be handled - created, deleted and listed in the browser and you can monitor message rates and send/receive messages manually. Kafka has a number of open-source tools, and also some commercial once, offering the administration and monitoring functionalities. I would say that it's easier/gets faster to get a good understanding of RabbitMQ.

In general, if you want a simple/traditional pub-sub message broker, the obvious choice is RabbitMQ, as it will most probably scale more than you will ever need it to scale. I would have chosen RabbitMQ if my requirements were simple enough to deal with system communication through channels/queues, and where retention and streaming is not a requirement.

There are two main situations where I would choose RabbitMQ; For long-running tasks, when I need to run reliable background jobs. And for communication and integration within, and between applications, i.e as middleman between microservices; where a system simply needs to notify another part of the system to start to work on a task, like ordering handling in a webshop (order placed, update order status, send order, payment, etc.).

In general, if you want a framework for storing, reading (re-reading), and analyzing streaming data, use Apache Kafka. It’s ideal for systems that are audited or those that need to store messages permanently. These can also be broken down into two main use cases for analyzing data (tracking, ingestion, logging, security etc.) or real-time processing.

More reading, use cases and some comparison data can be found here: https://www.cloudamqp.com/blog/2019-12-12-when-to-use-rabbitmq-or-apache-kafka.html

Also recommending the industry paper: "Kafka versus RabbitMQ: A comparative study of two industry reference publish/subscribe implementations": http://dl.acm.org/citation.cfm?id=3093908

I do work at a company providing both Apache Kafka and RabbitMQ as a Service.

Java generics - why is "extends T" allowed but not "implements T"?

Here is a more involved example of where extends is allowed and possibly what you want:

public class A<T1 extends Comparable<T1>>

What is the difference between Release and Debug modes in Visual Studio?

Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.

As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

Best practices for copying files with Maven

Well, maven is not supposed to be good in doing fine granular tasks, it is not a scripting language like bash or ant, it is rather declarative - you say - i need a war, or an ear, and you get it. However if you need to customize how the war or ear should look like inside, you have a problem. It is just not procedural like ant, but declarative. This have some pros in the beginning, and could have a lot of cons at the end.

I guess the initial concept was to have fine plugins, that "just work" but the reality is different if you do non-standard stuff.

If you however put enough effort in your poms and few custom plugins, you'll get a much better build environment as with ant for example (depends on you project of course, but it gets more and more true for bigger projects).

Compare given date with today

$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');

var_dump(strtotime($today) > strtotime($expiry)); //false or true

converting multiple columns from character to numeric format in r

like this?

DF <- data.frame("a" = as.character(0:5),
             "b" = paste(0:5, ".1", sep = ""),
             "c" = paste(10:15),
             stringsAsFactors = FALSE)

DF <- apply(DF, 2, as.numeric)

If there are "real" characters in dataframe like 'a' 'b' 'c', i would recommend answer from davsjob.

ITextSharp insert text to an existing pdf

In addition to the excellent answers above, the following shows how to add text to each page of a multi-page document:

 using (var reader = new PdfReader(@"C:\Input.pdf"))
 {
    using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write))
    {
       var document = new Document(reader.GetPageSizeWithRotation(1));
       var writer = PdfWriter.GetInstance(document, fileStream);

       document.Open();

       for (var i = 1; i <= reader.NumberOfPages; i++)
       {
          document.NewPage();

          var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
          var importedPage = writer.GetImportedPage(reader, i);

          var contentByte = writer.DirectContent;
          contentByte.BeginText();
          contentByte.SetFontAndSize(baseFont, 12);

          var multiLineString = "Hello,\r\nWorld!".Split('\n');

          foreach (var line in multiLineString)
          {
             contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
          }

          contentByte.EndText();
          contentByte.AddTemplate(importedPage, 0, 0);
       }

       document.Close();
       writer.Close();
    }
 }

Error 0x80005000 and DirectoryServices

Just FYI, I had the same error and was using the correct credentials but my LDAP url was wrong :(

I got the exact same error message and code

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

The data members and function members that operate on the instance of the type are called instance members. The int’s ToString method (for example) are examples of instance members. By default, members are instance members. Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static. The Test.Main and Console.WriteLine methods are static methods. The Console class is actually a static class, which means all its members are static. You never actually create instances of a Console—one console is shared across the whole application.

List files in local git repo?

git ls-tree --full-tree -r HEAD and git ls-files return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]. For example:

git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64    glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841    glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b    glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35    glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0    glyphicons-halflings-regular.woff2

In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97 is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>... of course.

How to select and change value of table cell with jQuery?

You can do this :

<table id="table_header">
<tr>
   <td contenteditable="true">a</td>
   <td contenteditable="true">b</td>
   <td contenteditable="true">c</td>
</tr>
</table>

How do you detect/avoid Memory leaks in your (Unmanaged) code?

If your C/C++ code is portable to *nix, few things are better than Valgrind.

Reset ID autoincrement ? phpmyadmin

You can also do this in phpMyAdmin without writing SQL.

  • Click on a database name in the left column.
  • Click on a table name in the left column.
  • Click the "Operations" tab at the top.
  • Under "Table options" there should be a field for AUTO_INCREMENT (only on tables that have an auto-increment field).
  • Input desired value and click the "Go" button below.

Note: You'll see that phpMyAdmin is issuing the same SQL that is mentioned in the other answers.

git: fatal unable to auto-detect email address

Problem solved after I run those commands with sudo

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

There is boolean data type in SQL Server. Its values can be TRUE, FALSE or UNKNOWN. However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. =, <>, <, >=) or logical operators (e.g. AND, OR, IN, EXISTS). Boolean expressions are only allowed in a handful of places including the WHERE clause, HAVING clause, the WHEN clause of a CASE expression or the predicate of an IF or WHILE flow control statement.

For all other usages, including the data type of a column in a table, boolean is not allowed. For those other usages, the BIT data type is preferred. It behaves like a narrowed-down INTEGER which allows only the values 0, 1 and NULL, unless further restricted with a NOT NULL column constraint or a CHECK constraint.

To use a BIT column in a boolean expression it needs to be compared using a comparison operator such as =, <> or IS NULL. e.g.

SELECT
    a.answer_body
FROM answers AS a
WHERE a.is_accepted = 0;

From a formatting perspective, a bit value is typically displayed as 0 or 1 in client software. When a more user-friendly format is required, and it can't be handled at an application tier in front of the database, it can be converted "just-in-time" using a CASE expression e.g.

SELECT
    a.answer_body,
    CASE a.is_accepted WHEN 1 THEN 'TRUE' ELSE 'FALSE' END AS is_accepted
FROM answers AS a;

Storing boolean values as a character data type like char(1) or varchar(5) is also possible, but that is much less clear, has more storage/network overhead, and requires CHECK constraints on each column to restrict illegal values.

For reference, the schema of answers table would be similar to:

CREATE TABLE answers (
    ...,
    answer_body nvarchar(MAX) NOT NULL,
    is_accepted bit NOT NULL DEFAULT (0)
);

How to manage exceptions thrown in filters in Spring?

You can use the following method inside the catch block:

response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token")

Notice that you can use any HttpStatus code and a custom message.

Java how to sort a Linked List?

If you'd like to know how to sort a linked list without using standard Java libraries, I'd suggest looking at different algorithms yourself. Examples here show how to implement an insertion sort, another StackOverflow post shows a merge sort, and ehow even gives some examples on how to create a custom compare function in case you want to further customize your sort.

Understanding the difference between Object.create() and new SomeFunction()

This:

var foo = new Foo();

and

var foo = Object.create(Foo.prototype);

are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as

function Foo() {
    alert("This constructor does not run with Object.create");
}

Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.

Remove menubar from Electron app

Use this:

mainWindow = new BrowserWindow({width: 640, height: 360})
mainWindow.setMenuBarVisibility(false)

Reference: https://github.com/electron/electron/issues/1415

I tried mainWindow.setMenu(null), but it didn't work.

Add new element to an existing object

Just do myFunction.foo = "bar" and it will add it. myFunction is the name of the object in this case.

Oracle find a constraint

select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/

Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.

The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:

SQL> create table t23 (id number not null primary key)
  2  /

Table created.

SQL> select constraint_name, constraint_type
  2  from user_constraints
  3  where table_name = 'T23'
  4  /

CONSTRAINT_NAME                C
------------------------------ -
SYS_C00935190                  C
SYS_C00935191                  P

SQL>

'C' for check, 'P' for primary.

Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191.

To be honest most people don't bother naming NOT NULL constraints.

How to trigger the onclick event of a marker on a Google Maps V3?

I've found out the solution! Thanks to Firebug ;)

//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event

//V2 version is:
GEvent.trigger(markers[i], 'click');

//V3 version is:
google.maps.event.trigger(markers[i], 'click');

What's the difference between django OneToOneField and ForeignKey?

The best and the most effective way to learn new things is to see and study real world practical examples. Suppose for a moment that you want to build a blog in django where reporters can write and publish news articles. The owner of the online newspaper wants to allow each of his reporters to publish as many articles as they want, but does not want different reporters to work on the same article. This means that when readers go and read an article they will se only one author in the article.

For example: Article by John, Article by Harry, Article by Rick. You can not have Article by Harry & Rick because the boss does not want two or more authors to work on the same article.

How can we solve this 'problem' with the help of django? The key to the solution of this problem is the django ForeignKey.

The following is the full code which can be used to implement the idea of our boss.

from django.db import models

# Create your models here.

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.first_name


class Article(models.Model):
    title = models.CharField(max_length=100)
    reporter = models.ForeignKey(Reporter)

    def __unicode__(self):
        return self.title

Run python manage.py syncdb to execute the sql code and build the tables for your app in your database. Then use python manage.py shell to open a python shell.

Create the Reporter object R1.

In [49]: from thepub.models import Reporter, Article

In [50]: R1 = Reporter(first_name='Rick')

In [51]: R1.save()

Create the Article object A1.

In [5]: A1 = Article.objects.create(title='TDD In Django', reporter=R1)

In [6]: A1.save()

Then use the following piece of code to get the name of the reporter.

In [8]: A1.reporter.first_name
Out[8]: 'Rick'

Now create the Reporter object R2 by running the following python code.

In [9]: R2 = Reporter.objects.create(first_name='Harry')

In [10]: R2.save()

Now try to add R2 to the Article object A1.

In [13]: A1.reporter.add(R2)

It does not work and you will get an AttributeError saying 'Reporter' object has no attribute 'add'.

As you can see an Article object can not be related to more than one Reporter object.

What about R1? Can we attach more than one Article objects to it?

In [14]: A2 = Article.objects.create(title='Python News', reporter=R1)

In [15]: R1.article_set.all()
Out[15]: [<Article: Python News>, <Article: TDD In Django>]

This practical example shows us that django ForeignKey is used to define many-to-one relationships.

OneToOneField is used to create one-to-one relationships.

We can use reporter = models.OneToOneField(Reporter) in the above models.py file but it is not going to be useful in our example as an author will not be able to post more than one article.

Each time you want to post a new article you will have to create a new Reporter object. This is time consuming, isn't it?

I highly recommend to try the example with the OneToOneField and realize the difference. I am pretty sure that after this example you will completly know the difference between django OneToOneField and django ForeignKey.

On design patterns: When should I use the singleton?

Managing a connection (or a pool of connections) to a database.

I would use it also to retrieve and store informations on external configuration files.

Is Ruby pass by reference or by value?

Two references refer to same object as long as there is no reassignment. 

Any updates in the same object won't make the references to new memory since it still is in same memory. Here are few examples :

    a = "first string"
    b = a



    b.upcase! 
    => FIRST STRING
    a
    => FIRST STRING

    b = "second string"


a
    => FIRST STRING
    hash = {first_sub_hash: {first_key: "first_value"}}
first_sub_hash = hash[:first_sub_hash]
first_sub_hash[:second_key] = "second_value"

    hash
    => {first_sub_hash: {first_key: "first_value", second_key: "second_value"}}

    def change(first_sub_hash)
    first_sub_hash[:third_key] = "third_value"
    end

    change(first_sub_hash)

    hash
    =>  {first_sub_hash: {first_key: "first_value", second_key: "second_value", third_key: "third_value"}}

What is the difference between "screen" and "only screen" in media queries?

The following is from Adobe docs.


The media queries specification also provides the keyword only, which is intended to hide media queries from older browsers. Like not, the keyword must come at the beginning of the declaration. For example:

media="only screen and (min-width: 401px) and (max-width: 600px)"

Browsers that don't recognize media queries expect a comma-separated list of media types, and the specification says they should truncate each value immediately before the first nonalphanumeric character that isn't a hyphen. So, an old browser should interpret the preceding example as this:

media="only"

Because there is no such media type as only, the stylesheet is ignored. Similarly, an old browser should interpret

media="screen and (min-width: 401px) and (max-width: 600px)"

as

media="screen"

In other words, it should apply the style rules to all screen devices, even though it doesn't know what the media queries mean.

Unfortunately, IE 6–8 failed to implement the specification correctly.

Instead of applying the styles to all screen devices, it ignores the style sheet altogether.

In spite of this behavior, it's still recommended to prefix media queries with only if you want to hide the styles from other, less common browsers.


So, using

media="only screen and (min-width: 401px)"

and

media="screen and (min-width: 401px)"

will have the same effect in IE6-8: both will prevent those styles from being used. They will, however, still be downloaded.

Also, in browsers that support CSS3 media queries, both versions will load the styles if the viewport width is larger than 401px and the media type is screen.

I'm not entirely sure which browsers that don't support CSS3 media queries would need the only version

media="only screen and (min-width: 401px)" 

as opposed to

media="screen and (min-width: 401px)"

to make sure it is not interpreted as

media="screen"

It would be a good test for someone with access to a device lab.

Extract images from PDF without resampling, in python?

Try below code. it will extract all image from pdf.

    import sys
    import PyPDF2
    from PIL import Image
    pdf=sys.argv[1]
    print(pdf)
    input1 = PyPDF2.PdfFileReader(open(pdf, "rb"))
    for x in range(0,input1.numPages):
        xObject=input1.getPage(x)
        xObject = xObject['/Resources']['/XObject'].getObject()
        for obj in xObject:
            if xObject[obj]['/Subtype'] == '/Image':
                size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
                print(size)
                data = xObject[obj]._data
                #print(data)
                print(xObject[obj]['/Filter'])
                if xObject[obj]['/Filter'][0] == '/DCTDecode':
                    img_name=str(x)+".jpg"
                    print(img_name)
                    img = open(img_name, "wb")
                    img.write(data)
                    img.close()
        print(str(x)+" is done")

How to set standard encoding in Visual Studio

Do you want the files to save as UTF-8 because you are using special characters that would be lost in ASCII encoding? If that's the case, then there is a VS2008 global setting in Tools > Options > Environment > Documents, named Save documents as Unicode when data cannot be saved in codepage. When this is enabled, VS2008 will save as Unicode if certain characters cannot be represented in the otherwise-default codepage.

Also, which files are not being saved as UTF-8? All of my .cs, .csproj, .sln, .config, .as*x, etc, all save as UTF-8 (with signature, the byte order marks), by default.

How to increase buffer size in Oracle SQL Developer to view all records?

https://forums.oracle.com/forums/thread.jspa?threadID=447344

The pertinent section reads:

There's no setting to fetch all records. You wouldn't like SQL Developer to fetch for minutes on big tables anyway. If, for 1 specific table, you want to fetch all records, you can do Control-End in the results pane to go to the last record. You could time the fetching time yourself, but that will vary on the network speed and congestion, the program (SQL*Plus will be quicker than SQL Dev because it's more simple), etc.

There is also a button on the toolbar which is a "Fetch All" button.

FWIW Be careful retrieving all records, for a very large recordset it could cause you to have all sorts of memory issues etc.

As far as I know, SQL Developer uses JDBC behind the scenes to fetch the records and the limit is set by the JDBC setMaxRows() procedure, if you could alter this (it would prob be unsupported) then you might be able to change the SQL Developer behaviour.

convert big endian to little endian in C [without using provided func]

here's a way using the SSSE3 instruction pshufb using its Intel intrinsic, assuming you have a multiple of 4 ints:

unsigned int *bswap(unsigned int *destination, unsigned int *source, int length) {
    int i;
    __m128i mask = _mm_set_epi8(12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3);
    for (i = 0; i < length; i += 4) {
        _mm_storeu_si128((__m128i *)&destination[i],
        _mm_shuffle_epi8(_mm_loadu_si128((__m128i *)&source[i]), mask));
    }
    return destination;
}

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If you have a mixture of formats in your date, don't forget to set infer_datetime_format=True to make life easier.

df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)

Source: pd.to_datetime

or if you want a customized approach:

def autoconvert_datetime(value):
    formats = ['%m/%d/%Y', '%m-%d-%y']  # formats to try
    result_format = '%d-%m-%Y'  # output format
    for dt_format in formats:
        try:
            dt_obj = datetime.strptime(value, dt_format)
            return dt_obj.strftime(result_format)
        except Exception as e:  # throws exception when format doesn't match
            pass
    return value  # let it be if it doesn't match

df['date'] = df['date'].apply(autoconvert_datetime)

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

Javascript: Call a function after specific time period

ECMAScript 6 introduced arrow functions so now the setTimeout() or setInterval() don't have to look like this:

setTimeout(function() { FetchData(); }, 1000)

Instead, you can use annonymous arrow function which looks cleaner, and less confusing:

setTimeout(() => {FetchData();}, 1000)

concatenate char array in C

You can concatenate strings by using the sprintf() function. In your case, for example:

char file[80];
sprintf(file,"%s%s",name,extension);

And you'll end having the concatenated string in "file".

HTTP Error 500.30 - ANCM In-Process Start Failure

In ASP.NET Core 2.2, a new Server/ hosting pattern was released with IIS called IIS InProcess hosting. To enable inprocess hosting, the csproj element AspNetCoreHostingModel is added to set the hostingModel to inprocess in the web.config file. Also, the web.config points to a new module called AspNetCoreModuleV2 which is required for inprocess hosting.

If the target machine you are deploying to doesn't have ANCMV2, you can't use IIS InProcess hosting. If so, the right behavior is to either install the dotnet hosting bundle to the target machine or downgrade to the AspNetCoreModule.

Source: jkotalik (Github)

Try changing the section in csproj (edit with a text editor)

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  </PropertyGroup>

to the following ...

 <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
    <AspNetCoreModuleName>AspNetCoreModule</AspNetCoreModuleName>
 </PropertyGroup>

Source (Github)

Git workflow and rebase vs merge questions

DO NOT use git push origin --mirror UNDER ALMOST ANY CIRCUMSTANCE.

It does not ask if you're sure you want to do this, and you'd better be sure, because it will erase all of your remote branches that are not on your local box.

http://twitter.com/dysinger/status/1273652486

Extracting Ajax return data in jQuery

Change the .find to .filter...

How do I append text to a file?

Follow up to accepted answer.

You need something other than CTRL-D to designate the end if using this in a script. Try this instead:

cat << EOF >> filename
This is text entered via the keyboard or via a script.
EOF

This will append text to the stated file (not including "EOF").

It utilizes a here document (or heredoc).

However if you need sudo to append to the stated file, you will run into trouble utilizing a heredoc due to I/O redirection if you're typing directly on the command line.

This variation will work when you are typing directly on the command line:

sudo sh -c 'cat << EOF >> filename
This is text entered via the keyboard.
EOF'

Or you can use tee instead to avoid the command line sudo issue seen when using the heredoc with cat:

tee -a filename << EOF
This is text entered via the keyboard or via a script.
EOF

Compile Views in ASP.NET MVC

I frankly would recommend the RazorGenerator nuget package. That way your views have a .designer.cs file generated when you save them and on top of getting compile time errors for you views, they are also precompiled into the assembly (= faster warmup) and Resharper provides some additional help as well.

To use this include the RazorGenerator nuget package in you ASP.NET MVC project and install the "Razor Generator" extension under item under Tools ? Extensions and Updates.

We use this and the overhead per compile with this approach is much less. On top of this I would probably recommend .NET Demon by RedGate which further reduces compile time impact substantially.

Hope this helps.

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Check this:

// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;

// Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false;

// Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false;

// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;

// Display the form as a modal dialog box.
form1.ShowDialog();

get the data of uploaded file in javascript

FileReaderJS can read the files for you. You get the file content inside onLoad(e) event handler as e.target.result.

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

First set delegate in viewDidLoad:

self.navigationController.interactivePopGestureRecognizer.delegate = self;

And then disable gesture when pushing:

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [super pushViewController:viewController animated:animated];
    self.interactivePopGestureRecognizer.enabled = NO;
}

And enable in viewDidDisappear:

self.navigationController.interactivePopGestureRecognizer.enabled = YES;

Also, add UINavigationControllerDelegate to your view controller.

Eclipse Error: "Failed to connect to remote VM"

I get this error for Weblogic after i installed Quicktime and removing QTJava.zip from classpath solves the problem.

https://blogs.oracle.com/adfjdev/entry/java_jre7_lib_ext_qtjava

How to write a test which expects an Error to be thrown in Jasmine?

I replace Jasmine's toThrow matcher with the following, which lets you match on the exception's name property or its message property. For me this makes tests easier to write and less brittle, as I can do the following:

throw {
   name: "NoActionProvided",
   message: "Please specify an 'action' property when configuring the action map."
}

and then test with the following:

expect (function () {
   .. do something
}).toThrow ("NoActionProvided");

This lets me tweak the exception message later without breaking tests, when the important thing is that it threw the expected type of exception.

This is the replacement for toThrow that allows this:

jasmine.Matchers.prototype.toThrow = function(expected) {
  var result = false;
  var exception;
  if (typeof this.actual != 'function') {
    throw new Error('Actual is not a function');
  }
  try {
    this.actual();
  } catch (e) {
    exception = e;
  }
  if (exception) {
      result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected) || this.env.equals_(exception.name, expected));
  }

  var not = this.isNot ? "not " : "";

  this.message = function() {
    if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
      return ["Expected function " + not + "to throw", expected ? expected.name || expected.message || expected : " an exception", ", but it threw", exception.name || exception.message || exception].join(' ');
    } else {
      return "Expected function to throw an exception.";
    }
  };

  return result;
};

Does svn have a `revert-all` command?

To revert modified files:

sudo svn revert
svn status|grep "^ *M" | sed -e 's/^ *M *//'

Return multiple values to a method caller

Ways to do it:

1) KeyValuePair (Best Performance - 0.32 ns):

    KeyValuePair<int, int> Location(int p_1, int p_2, int p_3, int p_4)
    {                 
         return new KeyValuePair<int,int>(p_2 - p_1, p_4-p_3);
    }

2) Tuple - 5.40 ns:

    Tuple<int, int> Location(int p_1, int p_2, int p_3, int p_4)
    {
          return new Tuple<int, int>(p_2 - p_1, p_4-p_3);
    }

3) out (1.64 ns) or ref 4) Create your own custom class/struct

ns -> nanoseconds

Reference: multiple-return-values.

Show image using file_get_contents

You can do that, or you can use the readfile function, which outputs it for you:

header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();

Edit: Derp, fixed obvious glaring typo.

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

How can I group data with an Angular filter?

First do a loop using a filter that will return only unique teams, and then a nested loop that returns all players per current team:

http://jsfiddle.net/plantface/L6cQN/

html:

<div ng-app ng-controller="Main">
    <div ng-repeat="playerPerTeam in playersToFilter() | filter:filterTeams">
        <b>{{playerPerTeam.team}}</b>
        <li ng-repeat="player in players | filter:{team: playerPerTeam.team}">{{player.name}}</li>        
    </div>
</div>

script:

function Main($scope) {
    $scope.players = [{name: 'Gene', team: 'team alpha'},
                    {name: 'George', team: 'team beta'},
                    {name: 'Steve', team: 'team gamma'},
                    {name: 'Paula', team: 'team beta'},
                    {name: 'Scruath of the 5th sector', team: 'team gamma'}];

    var indexedTeams = [];

    // this will reset the list of indexed teams each time the list is rendered again
    $scope.playersToFilter = function() {
        indexedTeams = [];
        return $scope.players;
    }

    $scope.filterTeams = function(player) {
        var teamIsNew = indexedTeams.indexOf(player.team) == -1;
        if (teamIsNew) {
            indexedTeams.push(player.team);
        }
        return teamIsNew;
    }
}

Google Chrome default opening position and size

You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.

removing new line character from incoming stream using sed

To remove newlines, use tr:

tr -d '\n'

If you want to replace each newline with a single space:

tr '\n' ' '

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$\!ba;s/\n/ /g'  # Suitable for csh only!!

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

How to print a dictionary line by line in Python?

You could use the json module for this. The dumps function in this module converts a JSON object into a properly formatted string which you can then print.

import json

cars = {'A':{'speed':70, 'color':2},
        'B':{'speed':60, 'color':3}}

print(json.dumps(cars, indent = 4))

The output looks like

{
    "A": {
        "color": 2,
        "speed": 70
    },
    "B": {
        "color": 3,
        "speed": 60
    }
}

The documentation also specifies a bunch of useful options for this method.

How do I use su to execute the rest of the bash script as that user?

Much simpler: use sudo to run a shell and use a heredoc to feed it commands.

#!/usr/bin/env bash
whoami
sudo -i -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami

(answer originally on SuperUser)

jQuery select child element by class with unknown path

Try this

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

How can I build a recursive function in python?

I'm wondering whether you meant "recursive". Here is a simple example of a recursive function to compute the factorial function:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

The two key elements of a recursive algorithm are:

  • The termination condition: n == 0
  • The reduction step where the function calls itself with a smaller number each time: factorial(n - 1)

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

You have to retrieve it from the HOST header.

var host = req.get('host');

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.


If this is for supporting cross-origin requests, you would instead use the Origin header.

var origin = req.get('origin');

Note that some cross-origin requests require validation through a "preflight" request:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});

If you're looking for the client's IP, you can retrieve that with:

var userIP = req.socket.remoteAddress;

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

First step: go to /etc/phpmyadmin/config.inc.php then uncomment lines where you find AllowNoPassword . Second step: login to your mysql default account

mysql -u root -p
use mysql;
update user set plugin="" where user='root';
flush privilege;

and that's all!

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

To keep the accordion nature intact when wanting to also use 'hide' and 'show' functions like .collapse( 'hide' ), you must initialize the collapsible panels with the parent property set in the object with toggle: false before making any calls to 'hide' or 'show'

// initialize collapsible panels
$('#accordion .collapse').collapse({
  toggle: false,
  parent: '#accordion'
});

// show panel one (will collapse others in accordion)
$( '#collapseOne' ).collapse( 'show' );

// show panel two (will collapse others in accordion)
$( '#collapseTwo' ).collapse( 'show' );

// hide panel two (will not collapse/expand others in accordion)
$( '#collapseTwo' ).collapse( 'hide' );

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I used String encodedUrl = new URI(null, url, null).toASCIIString(); to encode urls. To add parameters after the existing ones in the url I use UriComponentsBuilder

Font Awesome 5 font-family issue

I had tried all above the solutions for Font Awesome 5 but it wasn't working for me. :(

Finally, I got a solution!

Just use font-family: "Font Awesome 5 Pro"; in your CSS instead of using font-family: "Font Awesome 5 Free OR Solids OR Brands";

Get path to execution directory of Windows Forms application

Private Sub Main_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    Dim args() As String = Environment.GetCommandLineArgs()
    If args.Length > 0 Then
        TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
        Process.Start(TextBox1.Text)   
    End If
End Sub

The requested resource does not support HTTP method 'GET'

Please use the attributes from the System.Web.Http namespace on your WebAPI actions:

    [System.Web.Http.AcceptVerbs("GET", "POST")]
    [System.Web.Http.HttpGet]
    public string Auth(string username, string password)
    {...}

The reason why it doesn't work is because you were using the attributes that are from the MVC namespace System.Web.Mvc. The classes in the System.Web.Http namespace are for WebAPI.

SQL Error: ORA-00922: missing or invalid option

there's nothing wrong with using CHAR like that.. I think your problem is that you have a space in your tablename. It should be: charteredflight or chartered_flight..

If Radio Button is selected, perform validation on Checkboxes

You need to use == or === for comparison. = assigns a new value.

Besides that, using == is pointless when dealing with booleans only. Just use if(foo) instead of if(foo == true).

Resetting MySQL Root Password with XAMPP on Localhost

2020 Sep

  1. launch xamp control panel

  2. press admin in mysql row

  3. in opened phpmyadmin press house icon on top left corner

  4. in the top middle you will see user accounts tab and tap it

  5. see in 'new' panel under the table to add a new user for your dbs and set access permissions

Responsive table handling in Twitter Bootstrap

There are many different things you can do when dealing with responsive tables.

I personally like this approach by Chris Coyier:

You can find many other alternatives here:

If you can leverage Bootstrap and get something quickly, you can simply use the class names ".hidden-phone" and ".hidden-tablet" to hide some rows but this approach might to be the best in many cases. More info (see "Responsive utility classes"):

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

Setting the default page for ASP.NET (Visual Studio) server configuration

If you are running against IIS rather than the VS webdev server, ensure that Index.aspx is one of your default files and that directory browsing is turned off.

Find the number of downloads for a particular app in apple appstore

found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:

d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)

Import file size limit in PHPMyAdmin

For uploading large files through PHPMyAdmin, follow these steps:

Step 1: Open your php.ini file.

Step 2: Upgrading Memory Limit:

memory_limit = 750M

Step 3: Upgrading Maximum size to post:

post_max_size = 750M

Step 4: Upgrading Maximum file-size to upload:

upload_max_filesize = 1000M

Step 5: Upgrading Maximum Execution Time:

max_execution_time = 5000

Step 6: Upgrading Maximum Input Time:

max_input_time = 3000

Step 7: Restart your xampp control panel.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How to put a new line into a wpf TextBlock control?

you must use

 < SomeObject xml:space="preserve" > once upon a time ...
      this line will be below the first one < /SomeObject>

Or if you prefer :

 <SomeObject xml:space="preserve" />  once upon a time... &#10; this line below < / SomeObject>

watch out : if you both use &10 AND you go to the next line in your text, you'll have TWO empty lines.

here for details : http://msdn.microsoft.com/en-us/library/ms788746.aspx

How to find the Vagrant IP?

In the terminal type:

ip addr show

Encode URL in JavaScript?

I would suggest to use qs npm package

qs.stringify({a:"1=2", b:"Test 1"}); // gets a=1%3D2&b=Test+1

it is easier to use with JS object and it gives you proper URL encoding for all parameters

If you are using jQuery I would go for $.param method. It URL encodes an object mapping fields to values, which is easier to read than calling an escape method on each value.

$.param({a:"1=2", b:"Test 1"}) // gets a=1%3D2&b=Test+1

How to set UTF-8 encoding for a PHP file

HTML file:

<head>

<meta charset="utf-8">

</head>

PHP file :

<?php header('Content-type: text/plain; charset=utf-8'); ?>

SQL Server - boolean literal?

You can use the values 'TRUE' and 'FALSE'. From https://docs.microsoft.com/en-us/sql/t-sql/data-types/bit-transact-sql:

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

How can I override the OnBeforeUnload dialog and replace it with my own?

You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.

function onunload = (){
    window.open('logout.php');
}

This code called when user leave the page or close the active window and user logged out by 'logout.php'. The new window close immediately when logout php consist of code:

window.close();

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

How to execute mongo commands through shell scripts?

mongo db_name --eval "db.user_info.find().forEach(function(o) {print(o._id);})"

jQuery UI tabs. How to select a tab based on its id not based on index

It may have side effects if there are other listeners, and it doesn't feel as nice as interacting through the plugins API -- but it gives a less verbose code if you just "click" the tab, rather than count it's index and set it active afterwards, and it's pretty intuitive what's going on. Also it wont fail if the ui-guys decide to rename the option again.

$('#tabs').tabs(); 
$('#tabs a[href="#tabtwo"]').click();

It's intriguing, though, that the ui tabs code has a meta-function (_getIndex) with the comment:

"meta-function to give users option to provide a href string instead of a numerical index"

but does not use it when setting the active option, only when calling enable, disable and load.

JQuery: How to get selected radio button value?

You should really be using checkboxes if there will be an instance where something isn't selected.

according to the W3C

If no radio button in a set sharing the same control name is initially "on", user agent behavior for choosing which control is initially "on" is undefined. Note. Since existing implementations handle this case differently, the current specification differs from RFC 1866 ([RFC1866] section 8.1.2.4), which states:

At all times, exactly one of the radio buttons in a set is checked. If none of the elements of a set of radio buttons specifies `CHECKED', then the user agent must check the first radio button of the set initially.

Since user agent behavior differs, authors should ensure that in each set of radio buttons that one is initially "on".

A method to count occurrences in a list

Your outer loop is looping over all the words in the list. It's unnecessary and will cause you problems. Remove it and it should work properly.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

SVN 405 Method Not Allowed

My guess is that the folder you are trying to add already exists in SVN. You can confirm by checking out the files to a different folder and see if trunk already has the required folder.

Error importing SQL dump into MySQL: Unknown database / Can't create database

It sounds like your database dump includes the information for creating the database. So don't give the MySQL command line a database name. It will create the new database and switch to it to do the import.

How to auto adjust the div size for all mobile / tablet display formats?

Simple:

<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0" />

Cheers!

Time in milliseconds in C

Modern processors are too fast to register the running time. Hence it may return zero. In this case, the time you started and ended is too small and therefore both the times are the same after round of.

How to provide a mysql database connection in single file in nodejs

You could create a db wrapper then require it. node's require returns the same instance of a module every time, so you can perform your connection and return a handler. From the Node.js docs:

every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

You could create db.js:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'root',
    password : '',
    database : 'chat'
});

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

Then in your app.js, you would simply require it.

var express = require('express');
var app = express();
var db = require('./db');

app.get('/save',function(req,res){
    var post  = {from:'me', to:'you', msg:'hi'};
    db.query('INSERT INTO messages SET ?', post, function(err, result) {
      if (err) throw err;
    });
});

server.listen(3000);

This approach allows you to abstract any connection details, wrap anything else you want to expose and require db throughout your application while maintaining one connection to your db thanks to how node require works :)

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

Read file content from S3 bucket with boto3

If you already know the filename, you can use the boto3 builtin download_fileobj

import boto3

from io import BytesIO

session = boto3.Session()
s3_client = session.client("s3")

f = BytesIO()
s3_client.download_fileobj(bucket_name, filename, f)
f.seek(0)
print(f.getvalue())

Center icon in a div - horizontally and vertically

Since they are already inline-block child elements, you can set text-align:center on the parent without having to set a width or margin:0px auto on the child. Meaning it will work for dynamically generated content with varying widths.

.img_container, .img_container2 {
    text-align: center;
}

This will center the child within both div containers.

UPDATE:

For vertical centering, you can use the calc() function assuming the height of the icon is known.

.img_container > i, .img_container2 > i {
    position:relative;
    top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}

jsFiddle demo - it works.

For what it's worth - you can also use vertical-align:middle assuming display:table-cell is set on the parent.

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

try :

mvn install:install-file -DgroupId=jdk.tools -DartifactId=jdk.tools -Dversion=1.6 -Dpackaging=jar -Dfile="C:\Program Files\Java\jdk\lib\tools.jar"

also check : http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html

Declaring variable workbook / Worksheet vba

Use Sheets rather than Sheet and activate them sequentially:

Sub kl()
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ActiveWorkbook
    Set ws = Sheets("Sheet1")
    wb.Activate
    ws.Select
End Sub

Remove last character from string. Swift language

Use the function advance(startIndex, endIndex):

var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))

How do I calculate someone's age based on a DateTime type birthday?

var birthDate = ... // DOB
var resultDate = DateTime.Now - birthDate;

Using resultDate you can apply TimeSpan properties whatever you want to display it.

Visual Studio 2015 is very slow

In my case both 2015 express web and 2015 Community had memory leaks (up to 1.5 GB) froze and crashed every 5 minutes. But only in projects with Node js. what solved this issue for me was disabling the intellisense: tools--> options--> text editor-->Node.js--> intellisense-->intellisense level=No intellisense.

And somehow intellisense still works))

Swift 3 - Comparing Date objects

Another way to do it:

    switch date1.compare(date2) {
        case .orderedAscending:
            break

        case .orderedDescending:
            break;

        case .orderedSame:
            break
    }

How to add an object to an ArrayList in Java

change Date to Object which is between parenthesis

How can I generate a list of consecutive numbers?

Depending on how you want the result, you can also print each number in a for loop:

def numbers():
    for i in range(int(input('How far do you wanna go? '))+1):
        print(i)

So if the user input was 7 for example:

How far do you wanna go? 7
0
1
2
3
4
5
6
7

You can also delete the '+1' in the for loop and place it on the print statement, which will change it to starting at 1 instead of 0.

Unable to preventDefault inside passive event listener

I am getting this issue when using owl carousal and scrolling the images.

So get solved just adding below CSS in your page.

.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}

or

.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}

How to delete the last row of data of a pandas dataframe

Surprised nobody brought this one up:

# To remove last n rows
df.head(-n)

# To remove first n rows
df.tail(-n)

Running a speed test on a DataFrame of 1000 rows shows that slicing and head/tail are ~6 times faster than using drop:

>>> %timeit df[:-1]
125 µs ± 132 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.head(-1)
129 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.drop(df.tail(1).index)
751 µs ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Center align with table-cell

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.

DEMO

here's the gist of the demo

.container{

  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;

}

html

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>

enter image description here

Check if value exists in enum in TypeScript

If you want to use the variable as enum, just add the function:

Enum EVehicle {
    Car = 'car',
    Bike = 'bike',
    Truck = 'truck'
}

const getVehicleAsEnum = (vehicleStr:string) => vehicleStr === 'car' ? EVehicle.Car : vehicleStr === 'bike' ? EVehicle.Bike : vehicleStr === 'truck' ? EVehicle.Truck : undefined

And then test:

const vehicleEnum = getVecicleAsEnum(str)
if(vehicleEnum) {
   // do something
}

jquery find class and get the value

Class selectors are prefixed with a dot. Your .find() is missing that so jQuery thinks you're looking for <myClass> elements.

var myVar = $("#start").find('.myClass').val();

UIAlertController custom font, size, color

Swift 5.0

let titleAttrString = NSMutableAttributedString(string: "This is a title", attributes: [NSAttributedString.Key.font: UIFont(name: "CustomFontName", size: 17) as Any])
let messageAttrString = NSMutableAttributedString(string: "This is a message", attributes: [NSAttributedString.Key.font: UIFont(name: "CustomFontName", size: 13) as Any])

alertController.setValue(titleAttrString, forKey: "attributedTitle")
alertController.setValue(messageAttrString, forKey: "attributedMessage")

Good Hash Function for Strings

// djb2 hash function
unsigned long hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

source Logic behind djb2 hash function - SO

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

if you want to use "System.Data.Objects.EntityFunctions"

use "System.Data.Entity.DbFunctions" in EF 6.1+

What's the difference between an id and a class?

Class is for applying your style to a group of elements. ID styles apply to just the element with that ID (there should only be one). Usually you use classes, but if there's a one-off you can use IDs (or just stick the style straight into the element).

How do you change the value inside of a textfield flutter?

_mytexteditingcontroller.value = new TextEditingController.fromValue(new TextEditingValue(text: "My String")).value;

This seems to work if anyone has a better way please feel free to let me know.

rails simple_form - hidden field - create?

Shortest Yet !!!

=f.hidden_field :title, :value => "some value"

Shorter, DRYer and perhaps more obvious.

Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...

=f.hidden_field :title, value: "some value"

How to create a connection string in asp.net c#

Demo :

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

Based on your question:

<connectionStrings>
    <add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>

Refer links:

http://www.connectionstrings.com/store-connection-string-in-webconfig/

Retrive connection string from web.config file:

write the below code in your file where you want;

string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;

SqlConnection con = new SqlConnection(connstring);

or you can go in your way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);

Note:

The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)

Generate signed apk android studio

I had the same problem. I populated the field with /home/tim/android.jks file from tutorial thinking that file would be created. and when i would click enter it would say cant find the file. but when i would try to create the file, it would not let me create the jks file. I closed out of android studio and ran it again and it worked fine. I had to hit the ... to correctly add my file. generate signed apk wizard-->new key store-->hit ... choose key store file. enter filename I was thinking i was going to have to use openjdk and create my own keyfile, but it is built into android studio

How do I split an int into its digits?

    int power(int n, int b) {
    int number;
    number = pow(n, b);
    return number;
}


void NumberOfDigits() {
    int n, a;
    printf("Eneter number \n");
    scanf_s("%d", &n);
    int i = 0;
    do{
        i++;
    } while (n / pow(10, i) > 1);
    printf("Number of digits is: \t %d \n", i);

    for (int j = i-1; j >= 0; j--) {
        a = n / power(10, j) % 10;
        printf("%d \n", a);
    }
}

int main(void) {
    NumberOfDigits();
}

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.

For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other scenarios, forward is efficient to use since as it is faster than sendRedirect

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

You need to delete your old db folder and recreate new one. It will resolve your issue.

How do I sort a Set to a List in Java?

I am using this code, which I find more practical than the accepted answer above:

List<Thing> thingList = new ArrayList<>(thingSet);
thingList.sort((thing1, thing2) -> thing1.getName().compareToIgnoreCase(thing2.getName()));

Check if string contains only whitespace

I used following:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')

Convert array of indices to 1-hot encoded numpy array

Using a Neuraxle pipeline step:

  1. Set up your example
import numpy as np
a = np.array([1,0,3])
b = np.array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
  1. Do the actual conversion
from neuraxle.steps.numpy import OneHotEncoder
encoder = OneHotEncoder(nb_columns=4)
b_pred = encoder.transform(a)
  1. Assert it works
assert b_pred == b

Link to documentation: neuraxle.steps.numpy.OneHotEncoder

Which HTML elements can receive focus?

Maybe this one can help:

_x000D_
_x000D_
function focus(el){_x000D_
 el.focus();_x000D_
 return el==document.activeElement;_x000D_
}
_x000D_
_x000D_
_x000D_

return value: true = success, false = failed

Reff: https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus

ReferenceError: Invalid left-hand side in assignment

You have to use == to compare (or even ===, if you want to compare types). A single = is for assignment.

if (one == 'rock' && two == 'rock') {
    console.log('Tie! Try again!');
}

Text in HTML Field to disappear when clicked?

Use the placeholder attribute. The text disappears when the user starts typing. This is an example of a project I am working on:

<div class="" id="search-form">
    <input type="text" name="" value="" class="form-control" placeholder="Search..." >
</div>

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Numpy: Creating a complex array from 2 real ones?

import numpy as np

n = 51 #number of data points
# Suppose the real and imaginary parts are created independently
real_part = np.random.normal(size=n)
imag_part = np.random.normal(size=n)

# Create a complex array - the imaginary part will be equal to zero
z = np.array(real_part, dtype=complex)
# Now define the imaginary part:
z.imag = imag_part
print(z)

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.

How to fetch JSON file in Angular 2

If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory

return this.http.get('<json file path inside assets folder>.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}

Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.

Change image source with JavaScript

I know this question is old, but for the one's what are new, here is what you can do:

HTML

<img id="demo" src="myImage.png">

<button onclick="myFunction()">Click Me!</button>

JAVASCRIPT

function myFunction() {
document.getElementById('demo').src = "myImage.png";
}

optional parameters in SQL Server stored proc?

Yes, it is. Declare parameter as so:

@Sort varchar(50) = NULL

Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).

How to pre-populate the sms body text via an html link

Just put all of the symbols in this order (I only tested it in this order since it makes the most sense code-wise to me).

Notice for the body link... I just put... ;?&body=. Also, notice that I have found I needed to use %20 for any spaces.

I have tested it on my iphone (v. 9.2) and another android and it works just fine.

This will solve the issue with having to hack it for different devices. I have no artifacts when I tested it in the SMS.

<a href="sms:19131234567;?&body=Question%20from%20mywebsite.com.%20%20MY%20MESSAGE%20-%20" title="Click here to TEXT US gallery token needs updating!">Send me SMS</a>

How to show math equations in general github's markdown(not github's blog)

I use the below mentioned process to convert equations to markdown. This works very well for me. Its very simple!!

Let's say, I want to represent matrix multiplication equation

Step 1:

Get the script for your formulae from here - https://csrgxtu.github.io/2015/03/20/Writing-Mathematic-Fomulars-in-Markdown/

My example: I wanted to represent Z(i,j)=X(i,k) * Y(k, j); k=1 to n into a summation formulae.

enter image description here

Referencing the website, the script needed was => Z_i_j=\sum_{k=1}^{10} X_i_k * Y_k_j

Step 2:

Use URL encoder - https://www.urlencoder.org/ to convert the script to a valid url

My example:

enter image description here

Step 3:

Use this website to generate the image by copy-pasting the output from Step 2 in the "eq" request parameter - http://www.sciweavers.org/tex2img.php?eq=<b><i>paste-output-here</i></b>&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=

- My example:
http://www.sciweavers.org/tex2img.php?eq=Z_i_j=\sum_{k=1}^{10}%20X_i_k%20*%20Y_k_j&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=

enter image description here

Step 4:

Reference image using markdown syntax - ![alt text](enter url here)

- Copy this in your markdown and you are good to go:

![Z(i,j)=X(i,k) * Y(k, j); k=1 to n](http://www.sciweavers.org/tex2img.php?eq=Z_i_j%3D%5Csum_%7Bi%3D1%7D%5E%7B10%7D%20X_i_k%20%2A%20Y_k_j&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=)

Image below is the output of markdown. Hurray!!


enter image description here

Find out time it took for a python script to complete execution

Do you execute the script from the command line on Linux or UNIX? In that case, you could just use

time ./script.py

Is there a concise way to iterate over a stream with indices in Java 8?

If you are trying to get an index based on a predicate, try this:

If you only care about the first index:

OptionalInt index = IntStream.range(0, list.size())
    .filter(i -> list.get(i) == 3)
    .findFirst();

Or if you want to find multiple indexes:

IntStream.range(0, list.size())
   .filter(i -> list.get(i) == 3)
   .collect(Collectors.toList());

Add .orElse(-1); in case you want to return a value if it doesn't find it.

C - gettimeofday for computing time?

No. gettimeofday should NEVER be used to measure time.

This is causing bugs all over the place. Please don't add more bugs.

Gradle DSL method not found: 'runProguard'

If you are migrating to 1.0.0 you need to change the following properties.

In the Project's build.gradle file you need to replace minifyEnabled.

Hence your new build type should be

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'        
    }
}

Also make sure that gradle version is 1.0.0 like

classpath 'com.android.tools.build:gradle:1.0.0'

in the build.gradle file.

This should solve the problem.

Source: http://tools.android.com/tech-docs/new-build-system/migrating-to-1-0-0

How to stash my previous commit?

An alternative solution uses the stash:

Before:

~/dev/gitpro $git stash list

~/dev/gitpro $git log --oneline -3

* 7049dd5 (HEAD -> master) c111
* 3f1fa3d c222
* 0a0f6c4 c333
  1. git reset head~1 <--- head shifted one back to c222; working still contains c111 changes
  2. git stash push -m "commit 111" <--- staging/working (containing c111 changes) stashed; staging/working rolled back to revised head (containing c222 changes)
  3. git reset head~1 <--- head shifted one back to c333; working still contains c222 changes
  4. git stash push -m "commit 222" <--- staging/working (containing c222 changes) stashed; staging/working rolled back to revised head (containing c333 changes)
  5. git stash pop stash@{1} <--- oldest stash entry with c111 changes removed & applied to staging/working
  6. git commit -am "commit 111" <-- new commit with c111's changes becomes new head

note you cannot run 'git stash pop' without specifying the stash@{1} entry. The stash is a LIFO stack -- not FIFO -- so that would incorrectly pop the stash@{0} entry with c222's changes (instead of stash@{1} with c111's changes).

note if there are conflicting chunks between commits 111 and 222, then you'll be forced to resolve them when attempting to pop. (This would be the case if you went with an alternative rebase solution as well.)

After:

~/dev/gitpro $git stash list

stash@{0}: On master: c222

~/dev/gitpro $git log -2 --oneline

* edbd9e8 (HEAD -> master) c111
* 0a0f6c4 c333

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

Need to add to chosen answer: As of now, npm install in a package directory (containing package.json) will install devDependencies, whereas npm install -g will not install them.

How to count lines of Java code using IntelliJ IDEA?

Statistic plugins works fine!

Here is a quick case:

  1. Ctrl+Shift+A and serach for "Statistic" to open the panel.
  2. You will see panel as the screenshot and then click Refresh for whole project or select your project or file and Refresh on selection for only selection.

statistic

Best way to require all files from a directory in ruby?

Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file| 
  require File.basename(file, File.extname(file))
end

If you don't strip the extension then you may end up requiring the same file twice (ruby won't realize that "foo" and "foo.rb" are the same file). Requiring the same file twice can lead to spurious warnings (e.g. "warning: already initialized constant").

How do I get the RootViewController from a pushed controller?

As an addition to @dulgan's answer, it is always a good approach to use firstObject over objectAtIndex:0, because while first one returns nil if there is no object in the array, latter one throws exception.

UIViewController *rootViewController = self.navigationController.rootViewController;

Alternatively, it'd be a big plus for you to create a category named UINavigationController+Additions and define your method in that.

@interface UINavigationController (Additions)

- (UIViewController *)rootViewController;

@end

@implementation UINavigationController (Additions)

- (UIViewController *)rootViewController
{
    return self.viewControllers.firstObject;
}

@end

Failed to locate the winutils binary in the hadoop binary path

I was getting the same issue in windows. I fixed it by

  • Downloading hadoop-common-2.2.0-bin-master from link.
  • Create a user variable HADOOP_HOME in Environment variable and assign the path of hadoop-common bin directory as a value.
  • You can verify it by running hadoop in cmd.
  • Restart the IDE and Run it.

How to remove focus without setting focus to another control?

You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });

The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.

Please note this is pseudo-code and non-tested, but it's a possible direction you could try.