Programs & Examples On #Advanced search

Razor Views not seeing System.Web.Mvc.HtmlHelper

As a variation on a theme, I could have sworn up and down that my Views\Web.config was correct:

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

But I in fact needed to reference Version=4.0.0.1, not Version=4.0.0.0 because of that security update that got pushed out a while back.

How to jump back to NERDTree from file in tab?

You can focus on a split window using # ctrl-ww.

for example, pressing:

1 ctrl-ww

would focus on the first window, usually being NERDTree.

<button> vs. <input type="button" />. Which to use?

Quote

Important: If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the <button> and </button> tags, while other browsers will submit the content of the value attribute. Use the input element to create buttons in an HTML form.

From : http://www.w3schools.com/tags/tag_button.asp

If I understand correctly, the answer is compatibility and input consistency from browser to browser

How to get Printer Info in .NET?

As dowski suggested, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.

using System.Management;

...

string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
    try
    {
        foreach (ManagementObject printer in coll)
        {
            foreach (PropertyData property in printer.Properties)
            {
                Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
            }
        }
    }
    catch (ManagementException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

How do I get the path of the current executed file in Python?

My solution is:

import os
print(os.path.dirname(os.path.abspath(__file__)))

How do I add a custom script to my package.json file that runs a javascript file?

Example:

  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "build_c": "ng build --prod && del \"../../server/front-end/*.*\" /s /q & xcopy /s dist \"../../server/front-end\"",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

As you can see, the script "build_c" is building the angular application, then deletes all old files from a directory, then finally copies the result build files.

How to ignore a property in class if null, using json.net

With Json.NET

 public class Movie
 {
            public string Name { get; set; }
            public string Description { get; set; }
            public string Classification { get; set; }
            public string Studio { get; set; }
            public DateTime? ReleaseDate { get; set; }
            public List<string> ReleaseCountries { get; set; }
 }

 Movie movie = new Movie();
 movie.Name = "Bad Boys III";
 movie.Description = "It's no Bad Boys";

 string ignored = JsonConvert.SerializeObject(movie,
            Formatting.Indented,
            new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

The result will be:

{
   "Name": "Bad Boys III",
   "Description": "It's no Bad Boys"
 }

PHP salt and hash SHA256 for login password

You couldn't login because you did't get proper solt text at login time. There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user. Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

Node.js uses the environmental variable NODE_PATH to allow for specifying additional directories to include in the module search path. You can use npm itself to tell you where global modules are stored with the npm root -g command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)

export NODE_PATH=$(npm root --quiet -g)

How to use vertical align in bootstrap

You mean you want 1b and 1b to be side by side?

 <div class="col-lg-6 col-md-6 col-12 child1">
      <div class="col-6 child1a">Child content 1a</div>
      <div class="col-6 child1b">Child content 1b</div>
 </div>

Python string to unicode

Decode it with the unicode-escape codec:

>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…

This is because for a non-unicode string the \u2026 is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'). You need to decode the escapes, and the unicode-escape codec can do that for you.

Note that you can get unicode to recognise it in the same way by specifying the codec argument:

>>> unicode(a, 'unicode-escape')
u'Hello\u2026'

But the a.decode() way is nicer.

How to get the current URL within a Django template?

The other answers were incorrect, at least in my case. request.path does not provide the full url, only the relative url, e.g. /paper/53. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path.

How can I commit files with git?

in standart Vi editor in this situation you should

  1. press Esc
  2. type ":wq" (without quotes)
  3. Press Enter

How can I update a single row in a ListView?

I found the answer, thanks to your information Michelle. You can indeed get the right view using View#getChildAt(int index). The catch is that it starts counting from the first visible item. In fact, you can only get the visible items. You solve this with ListView#getFirstVisiblePosition().

Example:

private void updateView(int index){
    View v = yourListView.getChildAt(index - 
        yourListView.getFirstVisiblePosition());

    if(v == null)
       return;

    TextView someText = (TextView) v.findViewById(R.id.sometextview);
    someText.setText("Hi! I updated you manually!");
}

How can I enable auto complete support in Notepad++?

Autocomplete in Notepad++ is as simple as hitting Ctrl + Enter or Ctrl + Space in the interface.

Ctrl + Enter - as simple as that!

This, for many people, will be better than autocompleting on everything.

Pass user defined environment variable to tomcat

You should use System property instead of environment variable for this case. Edit your tomcat scripts for JAVA_OPTS and add property like:

-DAPP_MASTER_PASSWORD=foo

and in your code, write

System.getProperty("APP_MASTER_PASSWORD");

You can do this in Eclipse as well, instead of JAVA_OPTS, copy the line in VM parameters inside run configurations.

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Ran into this similar issue while using iframe to logout of sub sites with different domains. The solution I used was to load the iframe first, then update the source after the frame is loaded.

_x000D_
_x000D_
var frame = document.createElement('iframe');_x000D_
frame.style.display = 'none';_x000D_
frame.setAttribute('src', 'about:blank');_x000D_
document.body.appendChild(frame);_x000D_
frame.addEventListener('load', () => {_x000D_
  frame.setAttribute('src', url);_x000D_
});
_x000D_
_x000D_
_x000D_

No Network Security Config specified, using platform default - Android Log

This occurs to the api 28 and above, because doesn't accept http anymore, you need to change if you want to accept http or localhost requests.

  1. Create an XML file Create XML file

  2. Add the following code on the new XML file you created Add base-config

  3. Add this on AndroidManifest.xml Add this code line

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

Callback when CSS3 transition finishes

Another option would be to use the jQuery Transit Framework to handle your CSS3 transitions. The transitions/effects perform well on mobile devices and you don't have to add a single line of messy CSS3 transitions in your CSS file in order to do the animation effects.

Here is an example that will transition an element's opacity to 0 when you click on it and will be removed once the transition is complete:

$("#element").click( function () {
    $('#element').transition({ opacity: 0 }, function () { $(this).remove(); });
});

JS Fiddle Demo

Is there any method to get the URL without query string?

Try:

document.location.protocol + '//' +
document.location.host +
document.location.pathname;

(NB: .host rather than .hostname so that the port gets included too, if necessary)

Check date with todays date

    boolean isBeforeToday(Date d) {
        Date today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        return d.before(today);
    }

Check if process returns 0 with batch file

To check whether a process/command returned 0 or not, use the operators && == 0 or not == 0 ||:

Just add operator to your script:

execute_command && (

       echo\Return 0, with no execution error
) || (
        echo\Return non 0, something went wrong
     )

command && echo\Return 0 || echo\Return non 0

Get DataKey values in GridView RowCommand

I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.

On the Button:

CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'

On the Server Event

int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];

Make HTML5 video poster be same size as video itself

I had a similar issue and just fixed it by creating an image with the same aspect ratio as my video (16:9). My width is set to 100% on the video tag and now the image (320 x 180) fits perfectly. Hope that helps!

PHP date add 5 year to current date

Its very very easy with Carbon. $date = "2016-02-16"; // Or Your date $newDate = Carbon::createFromFormat('Y-m-d', $date)->addYear(1);

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)

Once the user have choose a image you can read the file-path of the chosen image and place it into your html.

Example:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

Javascript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Before and After Suite execution hook in jUnit 4.x

As far as I know there is no mechanism for doing this in JUnit, however you could try subclassing Suite and overriding the run() method with a version that does provide hooks.

Meaning of delta or epsilon argument of assertEquals for double values

Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!

From the JUnit javadoc:

delta - the maximum delta between expected and actual for which both numbers are still considered equal.

It's probably overkill, but I typically use a really small number, e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertEquals(123.456, 123.456, DELTA);
}

If you're using hamcrest assertions, you can just use the standard equalTo() with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo() (see javadoc), e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertThat(123.456, equalTo(123.456));
    assertThat(123.456, closeTo(123.456, DELTA));
}

FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals() with two doubles. The implementation (if you're interested) is:

private static boolean doublesAreEqual(double value1, double value2) {
    return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}

How do I create a Bash alias?

I just open zshrc with sublime, and edit it.

subl .zshrc

And add this on sublime:

alias blah="/usr/bin/blah"

Run this in terminal:

source ~/.bashrc

Done.

Angular 4 default radio button checked by default

We can use [(ngModel)] in following way and have a value selection variable radioSelected

Example tutorial

Demo Link

app.component.html

  <div class="text-center mt-5">
  <h4>Selected value is {{radioSel.name}}</h4>

  <div>
    <ul class="list-group">
          <li class="list-group-item"  *ngFor="let item of itemsList">
            <input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/> 
            {{item.name}}

          </li>
    </ul>
  </div>


  <h5>{{radioSelectedString}}</h5>

  </div>

app.component.ts

  import {Item} from '../app/item';
  import {ITEMS} from '../app/mock-data';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })
  export class AppComponent {
    title = 'app';
    radioSel:any;
    radioSelected:string;
    radioSelectedString:string;
    itemsList: Item[] = ITEMS;


      constructor() {
        this.itemsList = ITEMS;
        //Selecting Default Radio item here
        this.radioSelected = "item_3";
        this.getSelecteditem();
      }

      // Get row item from array  
      getSelecteditem(){
        this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
        this.radioSelectedString = JSON.stringify(this.radioSel);
      }
      // Radio Change Event
      onItemChange(item){
        this.getSelecteditem();
      }

  }

Sample Data for Listing

        export const ITEMS: Item[] = [
            {
                name:'Item 1',
                value:'item_1'
            },
            {
                name:'Item 2',
                value:'item_2'
            },
            {
                name:'Item 3',
                value:'item_3'
            },
            {
                name:'Item 4',
                value:'item_4'
                },
                {
                    name:'Item 5',
                    value:'item_5'
                }
        ];

Add quotation at the start and end of each line in Notepad++

  • One simple way is replace \n(newline) with ","(double-quote comma double-quote) after this append double-quote in the start and end of file.

example:

      AliceBlue
      AntiqueWhite
      Aqua
      Aquamarine
      Beige
  • Replcae \n with ","

      AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
    
  • Now append "(double-quote) at the start and end

     "AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
    

If your text contains blank lines in between you can use regular expression \n+ instead of \n

example:

      AliceBlue

      AntiqueWhite
      Aqua


      Aquamarine
      Beige
  • Replcae \n+ with "," (in regex mode)

      AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
    
  • Now append "(double-quote) at the start and end

     "AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
    

CSS3 Rotate Animation

try this easy

_x000D_
_x000D_
 _x000D_
 .btn-circle span {_x000D_
     top: 0;_x000D_
   _x000D_
      position: absolute;_x000D_
     font-size: 18px;_x000D_
       text-align: center;_x000D_
    text-decoration: none;_x000D_
      -webkit-animation:spin 4s linear infinite;_x000D_
    -moz-animation:spin 4s linear infinite;_x000D_
    animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
 color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } } 
_x000D_
 <button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">&#x21bb;</span></button>
_x000D_
_x000D_
_x000D_

Java error: Comparison method violates its general contract

I had the same symptom. For me it turned out that another thread was modifying the compared objects while the sorting was happening in a Stream. To resolve the issue, I mapped the objects to immutable temporary objects, collected the Stream to a temporary Collection and did the sorting on that.

Excel Formula to SUMIF date falls in particular month

=Sumifs(B:B,A:A,">=1/1/2013",A:A,"<=1/31/2013")

The beauty of this formula is you can add more data to columns A and B and it will just recalculate.

How to use relative/absolute paths in css URLs?

i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.

Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like

.icon{
  background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}

and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.

Good Luck!

MVC pattern on Android

Although this post seems to be old, I'd like to add the following two to inform about the recent development in this area for Android:

android-binding - Providing a framework that enabes the binding of android view widgets to data model. It helps to implement MVC or MVVM patterns in android applications.

roboguice - RoboGuice takes the guesswork out of development. Inject your View, Resource, System Service, or any other object, and let RoboGuice take care of the details.

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

You can use finds null separated output option with read to iterate over directory structures safely.

#!/bin/bash
find . -type f -print0 | while IFS= read -r -d $'\0' file; 
  do echo "$file" ;
done

So for your case

#!/bin/bash
find . -maxdepth 1 -type f  -print0 | while IFS= read -r -d $'\0' file; do
  for ((i=0; i<=3; i++)); do
    ./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
  done
done

additionally

#!/bin/bash
while IFS= read -r -d $'\0' file; do
  for ((i=0; i<=3; i++)); do
    ./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
  done
done < <(find . -maxdepth 1 -type f  -print0)

will run the while loop in the current scope of the script ( process ) and allow the output of find to be used in setting variables if needed

How to implement endless list with RecyclerView?

Although there are so many answers to the question, I would like to share our experience of creating the endless list view. We have recently implemented custom Carousel LayoutManager that can work in the cycle by scrolling the list infinitely as well as up to a certain point. Here is a detailed description on GitHub.

I suggest you take a look at this article with short but valuable recommendations on creating custom LayoutManagers: http://cases.azoft.com/create-custom-layoutmanager-android/

handling DATETIME values 0000-00-00 00:00:00 in JDBC

you can append the jdbc url with

?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8

With the help of this, sql convert '0000-00-00 00:00:00' as null value.

eg:

jdbc:mysql:<host-name>/<db-name>?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8

How to add an Android Studio project to GitHub

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

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

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

The backend version is not supported to design database diagrams or tables

This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.


Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.

Cannot serve WCF services in IIS on Windows 8

Seemed to be a no brainer; the WCF service should be enabled using Programs and Features -> Turn Windows features on or off in the Control Panel. Go to .NET Framework Advanced Services -> WCF Services and enable HTTP Activation as described in this blog post on mdsn.

From the command prompt (as admin), you can run:

C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45

If you get an error then use the below

C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation45

Vue.js img src concatenate variable and text

just try

_x000D_
_x000D_
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
_x000D_
_x000D_

How to find server name of SQL Server Management Studio

Note: To connect to server on SQL Server Management Studio(SSMS), we must first install SQL Server.

So steps to proceed are as

Step 1 : Downloads and Install Microsoft SQL Server 2019

Step 2 : Downloads and Install SQL Server Management Studio

If still not able to see the Server name on SSMS, have a look at these three screen:

enter image description here enter image description here enter image description here

How to detect a remote side socket close?

Since the answers deviate I decided to test this and post the result - including the test example.

The server here just writes data to a client and does not expect any input.

The server:

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
  out.println("output");
  if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
  System.out.println(clientSocket.isConnected());
  System.out.println(clientSocket.getInputStream().read());
        // thread sleep ...
  // break condition , close sockets and the like ...
}
  • clientSocket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • out.checkError() is true as soon as the client is disconnected so I recommend this

How to generate different random numbers in a loop in C++?

You need to extract the initilization of time() out of the for loop.

Here is an example that will output in the windows console expected (ahah) random number.

#include <iostream>
#include <windows.h>
#include "time.h"
int main(int argc, char*argv[])
{
    srand ( time(NULL) );
    for (int t = 0; t < 10; t++)
    {
        int random_x;

        random_x = rand() % 100;
        std::cout << "\nRandom X = " << random_x << std::endl;
    }
    Sleep(50000);
    return 0;
}

Select first row in each GROUP BY group?

The solution is not very efficient as pointed by Erwin, because of presence of SubQs

select * from purchases p1 where total in
(select max(total) from purchases where p1.customer=customer) order by total desc;

Fixed positioning in Mobile Safari

This is how i did it. I have a nav block that is below the header once you scroll the page down it 'sticks' to the top of the window. If you scroll back to top, nav goes back in it's place I use position:fixed in CSS for non mobile platforms and iOS5. Other Mobile versions do have that 'lag' until screen stops scrolling before it's set.

// css
#sticky.stick {
    width:100%;
    height:50px;
    position: fixed;
    top: 0;
    z-index: 1;
}

// jquery 
//sticky nav
    function sticky_relocate() {
      var window_top = $(window).scrollTop();
      var div_top = $('#sticky-anchor').offset().top;

      if (window_top > div_top)
        $('#sticky').addClass('stick');
      else
        $('#sticky').removeClass('stick');
     }

$(window).scroll(function(event){

    // sticky nav css NON mobile way
       sticky_relocate();

       var st = $(this).scrollTop();

    // sticky nav iPhone android mobile way iOS<5

       if (navigator.userAgent.match(/OS 5(_\d)+ like Mac OS X/i)) {
            //do nothing uses sticky_relocate() css
       } else if ( navigator.userAgent.match(/(iPod|iPhone|iPad)/i) || navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) ) {

            var window_top = $(window).scrollTop();
            var div_top = $('#sticky-anchor').offset().top;

            if (window_top > div_top) {
                $('#sticky').css({'top' : st  , 'position' : 'absolute' });
            } else {
                $('#sticky').css({'top' : 'auto' });
            }
        };

How to fix a header on scroll

Just building on Rich's answer, which uses offset.

I modified this as follows:

  • There was no need for the var $sticky in Rich's example, it wasn't doing anything
  • I've moved the offset check into a separate function, and called it on document ready as well as on scroll so if the page refreshes with the scroll half-way down the page, it resizes straight-away without having to wait for a scroll trigger

    jQuery(document).ready(function($){
        var offset = $( "#header" ).offset();
        checkOffset();
    
        $(window).scroll(function() {
            checkOffset();
        });
    
        function checkOffset() {
            if ( $(document).scrollTop() > offset.top){
                $('#header').addClass('fixed');
            } else {
                $('#header').removeClass('fixed');
            } 
        }
    
    });
    

Python string.replace regular expression

As a summary

import sys
import re

f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
     s=myfile.read()
ret = re.sub(find,replace, s)   # <<< This is where the magic happens
print ret

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

What is the difference between JavaScript and jQuery?

jQuery is a JavaScript library.

Read

wiki-jQuery, github, jQuery vs. javascript?


Source

What is JQuery?

Before JQuery, developers would create their own small frameworks (the group of code) this would allow all the developers to work around all the bugs and give them more time to work on features, so the JavaScript frameworks were born. Then came the collaboration stage, groups of developers instead of writing their own code would give it away for free and creating JavaScript code sets that everyone could use. That is what JQuery is, a library of JavaScript code. The best way to explain JQuery and its mission is well stated on the front page of the JQuery website which says:

JQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

As you can see all JQuery is JavaScript. There is more than one type of JavaScript set of code sets like MooTools it is just that JQuery is the most popular.


JavaScript vs JQuery

Which is the best JavaScript or JQuery is a contentious discussion, really the answer is neither is best. They both have their roles I have worked on online applications where JQuery was not the right tool and what the application needed was straight JavaScript development. But for most websites JQuery is all that is needed. What a web developer needs to do is make an informed decision on what tools are best for their client. Someone first coming into web development does need some exposure to both technologies just using JQuery all the time does not teach the nuances of JavaScript and how it affects the DOM. Using JavaScript all the time slows projects down and because of the JQuery library has ironed most of the issues that JavaScript will have between each web browser it makes the deployment safe as it is sure to work across all platforms.


JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.

See here.

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

To remove all the documents in all the collections:

db.getCollectionNames().forEach( function(collection_name) { 
    if (collection_name.indexOf("system.") == -1) {
        print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
        db[collection_name].remove({}); 
    }
});

How to Convert datetime value to yyyymmddhhmmss in SQL server?

This query is to convert the DateTimeOffset into the format yyyyMMddhhss with Offset. I have replaced the hyphens, colon(:), period(.) from the data, and kept the hyphen for the seperation of Offset from the DateTime.

SELECT REPLACE(SUBSTRING(CONVERT(VARCHAR(33),SYSDATETIMEOFFSET(),126), 1, 8), '-', '') +
SUBSTRING(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(33), SYSDATETIMEOFFSET(), 126),'T',''),'.',''),':',''),9,DATALENGTH(CONVERT(VARCHAR(33), SYSDATETIMEOFFSET(), 126)))

How to secure RESTful web services?

If choosing between OAuth versions, go with OAuth 2.0.

OAuth bearer tokens should only be used with a secure transport.

OAuth bearer tokens are only as secure or insecure as the transport that encrypts the conversation. HTTPS takes care of protecting against replay attacks, so it isn't necessary for the bearer token to also guard against replay.

While it is true that if someone intercepts your bearer token they can impersonate you when calling the API, there are plenty of ways to mitigate that risk. If you give your tokens a long expiration period and expect your clients to store the tokens locally, you have a greater risk of tokens being intercepted and misused than if you give your tokens a short expiration, require clients to acquire new tokens for every session, and advise clients not to persist tokens.

If you need to secure payloads that pass through multiple participants, then you need something more than HTTPS/SSL, since HTTPS/SSL only encrypts one link of the graph. This is not a fault of OAuth.

Bearer tokens are easy to for clients to obtain, easy for clients to use for API calls and are widely used (with HTTPS) to secure public facing APIs from Google, Facebook, and many other services.

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

How can I remount my Android/system as read-write in a bash script using adb?

mount -o rw,remount $(mount | grep /dev/root | awk '{print $3}')

this does the job for me, and should work for any android version.

Strings and character with printf

You're confusing the dereference operator * with pointer type annotation *. Basically, in C * means different things in different places:

  • In a type, * means a pointer. int is an integer type, int* is a pointer to integer type
  • As a prefix operator, * means 'dereference'. name is a pointer, *name is the result of dereferencing it (i.e. getting the value that the pointer points to)
  • Of course, as an infix operator, * means 'multiply'.

What is the difference between functional and non-functional requirements?

functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design

Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.

How to tell which disk Windows Used to Boot

Unless C: is not the drive that windows booted from.
Parse the %SystemRoot% variable, it contains the location of the windows folder (i.e. c:\windows).

Selenium Webdriver move mouse to Point

I am using JavaScript but some of the principles are common I am sure.

The code I am using is as follows:

    var s = new webdriver.ActionSequence(d);
    d.findElement(By.className('fc-time')).then(function(result){
        s.mouseMove(result,l).click().perform();
    });

the driver = d. The location = l is simply {x:300,y:500) - it is just an offset.

What I found during my testing was that I could not make it work without using the method to find an existing element first, using that at a basis from where to locate my click.

I suspect the figures in the locate are a bit more difficult to predict than I thought.

It is an old post but this response may help other newcomers like me.

How to set a selected option of a dropdown list control using angular JS

JS:

$scope.options = [
  {
    name: "a", 
    id: 1 
  },
  {
    name: "b",
    id: 2 
  }
];
$scope.selectedOption = $scope.options[1];

How do I replace a character in a string in Java?

//I think this will work, you don't have to replace on the even, it's just an example. 

 public void emphasize(String phrase, char ch)
    {
        char phraseArray[] = phrase.toCharArray(); 
        for(int i=0; i< phrase.length(); i++)
        {
            if(i%2==0)// even number
            {
                String value = Character.toString(phraseArray[i]); 
                value = value.replace(value,"*"); 
                phraseArray[i] = value.charAt(0);
            }
        }
    }

numpy max vs amax vs maximum

For completeness, in Numpy there are four maximum related functions. They fall into two different categories:

  • np.amax/np.max, np.nanmax: for single array order statistics
  • and np.maximum, np.fmax: for element-wise comparison of two arrays

I. For single array order statistics

NaNs propagator np.amax/np.max and its NaN ignorant counterpart np.nanmax.

  • np.max is just an alias of np.amax, so they are considered as one function.

    >>> np.max.__name__
    'amax'
    >>> np.max is np.amax
    True
    
  • np.max propagates NaNs while np.nanmax ignores NaNs.

    >>> np.max([np.nan, 3.14, -1])
    nan
    >>> np.nanmax([np.nan, 3.14, -1])
    3.14
    

II. For element-wise comparison of two arrays

NaNs propagator np.maximum and its NaNs ignorant counterpart np.fmax.

  • Both functions require two arrays as the first two positional args to compare with.

    # x1 and x2 must be the same shape or can be broadcast
    np.maximum(x1, x2, /, ...);
    np.fmax(x1, x2, /, ...)
    
  • np.maximum propagates NaNs while np.fmax ignores NaNs.

    >>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([ nan,  nan, 2.72])
    >>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([-inf, 3.14, 2.72])
    
  • The element-wise functions are np.ufunc(Universal Function), which means they have some special properties that normal Numpy function don't have.

    >>> type(np.maximum)
    <class 'numpy.ufunc'>
    >>> type(np.fmax)
    <class 'numpy.ufunc'>
    >>> #---------------#
    >>> type(np.max)
    <class 'function'>
    >>> type(np.nanmax)
    <class 'function'>
    

And finally, the same rules apply to the four minimum related functions:

  • np.amin/np.min, np.nanmin;
  • and np.minimum, np.fmin.

Purpose of a constructor in Java?

A Java constructor has the same name as the name of the class to which it belongs.

Constructor’s syntax does not include a return type, since constructors never return a value.

Constructor is always called when object is created. example:- Default constructor

class Student3{  
    int id;  
    String name;  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student3 s1=new Student3();  
        Student3 s2=new Student3();  
        s1.display();  
        s2.display();  
    }  
} 

Output:

0 null
0 null

Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

class Student4{  
    int id;  
    String name;  
    Student4(int i,String n){  
        id = i;  
        name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student4 s1 = new Student4(111,"Karan");  
        Student4 s2 = new Student4(222,"Aryan");  
        s1.display();  
        s2.display();  
    }  
}  

Output:

111 Karan
222 Aryan

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

Reading data from a website using C#

Regarding the suggestion So I would suggest that you use WebClient and investigate the causes of the 30 second delay.

From the answers for the question System.Net.WebClient unreasonably slow

Try setting Proxy = null;

WebClient wc = new WebClient(); wc.Proxy = null;

Credit to Alex Burtsev

Linq select object from list depending on objects attribute

Few things to fix here:

  1. No parenthesis in class declaration
  2. Make the "correct" property as public
  3. And then do the selection

Your code will look something like this

List<Answer> answers = new List<Answer>();
/* test
answers.Add(new Answer() { correct = false });
answers.Add(new Answer() { correct = true });
answers.Add(new Answer() { correct = false });
*/
Answer answer = answers.Single(a => a.correct == true);

and the class

class Answer
{
   public bool correct;
}

How to set a timeout on a http.request() in Node?

Curious, what happens if you use straight net.sockets instead? Here's some sample code I put together for testing purposes:

var net = require('net');

function HttpRequest(host, port, path, method) {
  return {
    headers: [],
    port: 80,
    path: "/",
    method: "GET",
    socket: null,
    _setDefaultHeaders: function() {

      this.headers.push(this.method + " " + this.path + " HTTP/1.1");
      this.headers.push("Host: " + this.host);
    },
    SetHeaders: function(headers) {
      for (var i = 0; i < headers.length; i++) {
        this.headers.push(headers[i]);
      }
    },
    WriteHeaders: function() {
      if(this.socket) {
        this.socket.write(this.headers.join("\r\n"));
        this.socket.write("\r\n\r\n"); // to signal headers are complete
      }
    },
    MakeRequest: function(data) {
      if(data) {
        this.socket.write(data);
      }

      this.socket.end();
    },
    SetupRequest: function() {
      this.host = host;

      if(path) {
        this.path = path;
      }
      if(port) {
        this.port = port;
      }
      if(method) {
        this.method = method;
      }

      this._setDefaultHeaders();

      this.socket = net.createConnection(this.port, this.host);
    }
  }
};

var request = HttpRequest("www.somesite.com");
request.SetupRequest();

request.socket.setTimeout(30000, function(){
  console.error("Connection timed out.");
});

request.socket.on("data", function(data) {
  console.log(data.toString('utf8'));
});

request.WriteHeaders();
request.MakeRequest();

img tag displays wrong orientation

I found part of the solution. Images now have metadata that specify the orientation of the photo. There is a new CSS spec for image-orientation.

Just add this to your CSS:

img {
    image-orientation: from-image;
}

According to the spec as of Jan 25 2016, Firefox and iOS Safari (behind a prefix) are the only browsers that support this. I'm seeing issues with Safari and Chrome still. However, mobile Safari seems to natively support orientation without the CSS tag.

I suppose we'll have to wait and see if browsers wills start supporting image-orientation.

How to create a JSON object

You could json encode a generic object.

$post_data = new stdClass();
$post_data->item = new stdClass();
$post_data->item->item_type_id = $item_type;
$post_data->item->string_key = $string_key;
$post_data->item->string_value = $string_value;
$post_data->item->string_extra = $string_extra;
$post_data->item->is_public = $public;
$post_data->item->is_public_for_contacts = $public_contacts;
echo json_encode($post_data);

Creating a new user and password with Ansible

Tried many utilities including mkpasswd, Python etc. But it seems like there is some compatibility issue with Ansible in reading HASH values generated by other tools. So finally it worked by ansible # value itself.

ansible all -i localhost, -m debug -a "msg={{ 'yourpasswd' | password_hash('sha512', 'mysecretsalt') }}"

Playbook -

- name: User creation
  user: 
    name: username  
    uid: UID
    group: grpname
    shell: /bin/bash
    comment: "test user"
    password: "$6$mysecretsalt$1SMjoVXjYf.3sJR3a1WUxlDCmdJwC613.SUD4DOf40ASDFASJHASDFCDDDWERWEYbs8G00NHmOg29E0"

ESLint not working in VS Code?

Restarting VSCode worked for me.

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

CSS white space at bottom of page despite having both min-height and height tag

The problem is the background image on the html element. You appear to have set it to "null" which is not valid. Try removing that CSS rule entirely, or at least setting background-image:none

EDIT: the CSS file says it is "generated" so I don't know exactly what you will be able to edit. The problem is this line:

html { background-color:null !important; background-position:null !important; background-repeat:repeat !important; background-image:url('http://images.freewebs.com/Images/null.gif') !important; }

I'm guessing you've put null as a value and it has set the background to a GIF called 'null'.

What does git push -u mean?

"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull or git push without arguments. A little bit down, this article explains and demonstrates this concept.

Rails find_or_create_by more than one attribute?

Multiple attributes can be connected with an and:

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

(use find_or_initialize_by if you don't want to save the record right away)

Edit: The above method is deprecated in Rails 4. The new way to do it will be:

GroupMember.where(:member_id => 4, :group_id => 7).first_or_create

and

GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize

Edit 2: Not all of these were factored out of rails just the attribute specific ones.

https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md

Example

GroupMember.find_or_create_by_member_id_and_group_id(4, 7)

became

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

Multi column forms with fieldsets

There are a couple of things that need to be adjusted in your layout:

  1. You are nesting col elements within form-group elements. This should be the other way around (the form-group should be within the col-sm-xx element).

  2. You should always use a row div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12 is still on the same row with the above 3 .col-sm-4 resulting in a total of columns greater than 12, and causing the overlap problem.

Here is a fixed demo.

And an excerpt of what the problematic section HTML should become:

<fieldset>
    <legend>Personal Information</legend>
    <div class='row'>
        <div class='col-sm-4'>    
            <div class='form-group'>
                <label for="user_title">Title</label>
                <input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_firstname">First name</label>
                <input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_lastname">Last name</label>
                <input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
    <div class='row'>
        <div class='col-sm-12'>
            <div class='form-group'>

                <label for="user_email">Email</label>
                <input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
</fieldset>

How can I clear event subscriptions in C#?

Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events.

How to list all methods for an object in Ruby?

To expound upon @clyfe's answer. You can get a list of your instance methods using the following code (assuming that you have an Object Class named "Parser"):

Parser.new.methods - Object.new.methods

LINQ to Entities how to update a record

They both track your changes to the collection, just call the SaveChanges() method that should update the DB.

How to solve a pair of nonlinear equations using Python?

I got Broyden's method to work for coupled non-linear equations (generally involving polynomials and exponentials) in IDL, but I haven't tried it in Python:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.broyden1.html#scipy.optimize.broyden1

scipy.optimize.broyden1

scipy.optimize.broyden1(F, xin, iter=None, alpha=None, reduction_method='restart', max_rank=None, verbose=False, maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, tol_norm=None, line_search='armijo', callback=None, **kw)[source]

Find a root of a function, using Broyden’s first Jacobian approximation.

This method is also known as “Broyden’s good method”.

include antiforgerytoken in ajax post ASP.NET MVC

In Asp.Net Core you can request the token directly, as documented:

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf    
@functions{
    public string GetAntiXsrfRequestToken()
    {
        return Xsrf.GetAndStoreTokens(Context).RequestToken;
    }
}

And use it in javascript:

function DoSomething(id) {
    $.post("/something/todo/"+id,
               { "__RequestVerificationToken": '@GetAntiXsrfRequestToken()' });
}

You can add the recommended global filter, as documented:

services.AddMvc(options =>
{
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
})

Update

The above solution works in scripts that are part of the .cshtml. If this is not the case then you can't use this directly. My solution was to use a hidden field to store the value first.

My workaround, still using GetAntiXsrfRequestToken:

When there is no form:

<input type="hidden" id="RequestVerificationToken" value="@GetAntiXsrfRequestToken()">

The name attribute can be omitted since I use the id attribute.

Each form includes this token. So instead of adding yet another copy of the same token in a hidden field, you can also search for an existing field by name. Please note: there can be multiple forms inside a document, so name is in that case not unique. Unlike an id attribute that should be unique.

In the script, find by id:

function DoSomething(id) {
    $.post("/something/todo/"+id,
       { "__RequestVerificationToken": $('#RequestVerificationToken').val() });
}

An alternative, without having to reference the token, is to submit the form with script.

Sample form:

<form id="my_form" action="/something/todo/create" method="post">
</form>

The token is automatically added to the form as a hidden field:

<form id="my_form" action="/something/todo/create" method="post">
<input name="__RequestVerificationToken" type="hidden" value="Cf..." /></form>

And submit in the script:

function DoSomething() {
    $('#my_form').submit();
}

Or using a post method:

function DoSomething() {
    var form = $('#my_form');

    $.post("/something/todo/create", form.serialize());
}

Cleanest Way to Invoke Cross-Thread Events

I made the following 'universal' cross thread call class for my own purpose, but I think it's worth to share it:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace CrossThreadCalls
{
  public static class clsCrossThreadCalls
  {
    private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);
    public static void SetAnyProperty(Control c, string Property, object Value)
    {
      if (c.GetType().GetProperty(Property) != null)
      {
        //The given property exists
        if (c.InvokeRequired)
        {
          SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);
          c.BeginInvoke(d, c, Property, Value);
        }
        else
        {
          c.GetType().GetProperty(Property).SetValue(c, Value, null);
        }
      }
    }

    private delegate void SetTextPropertyCallBack(Control c, string Value);
    public static void SetTextProperty(Control c, string Value)
    {
      if (c.InvokeRequired)
      {
        SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);
        c.BeginInvoke(d, c, Value);
      }
      else
      {
        c.Text = Value;
      }
    }
  }

And you can simply use SetAnyProperty() from another thread:

CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, "Text", KvaserCanReader.GetSpeed.ToString());

In this example the above KvaserCanReader class runs its own thread and makes a call to set the text property of the lb_Speed label on the main form.

Why can a function modify some arguments as perceived by the caller, but not others?

You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:

Any time you see varname =, you're creating a new name binding within the function's scope. Whatever value varname was bound to before is lost within this scope.

Any time you see varname.foo() you're calling a method on varname. The method may alter varname (e.g. list.append). varname (or, rather, the object that varname names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.

[note that the global keyword creates an exception to the first case]

Is there a Subversion command to reset the working copy?

Delete unversioned files and revert any changes:

svn revert D:\tmp\sql -R
svn cleanup D:\tmp\sql --remove-unversioned

Out:

D         D:\tmp\sql\update\abc.txt

What is the !! (not not) operator in JavaScript?

I think worth mentioning is, that a condition combined with logical AND/OR will not return a boolean value but last success or first fail in case of && and first success or last fail in case of || of condition chain.

res = (1 && 2); // res is 2
res = (true && alert) // res is function alert()
res = ('foo' || alert) // res is 'foo'

In order to cast the condition to a true boolean literal we can use the double negation:

res = !!(1 && 2); // res is true
res = !!(true && alert) // res is true
res = !!('foo' || alert) // res is true

node.js execute system command synchronously

I had a similar problem and I ended up writing a node extension for this. You can check out the git repository. It's open source and free and all that good stuff !

https://github.com/aponxi/npm-execxi

ExecXI is a node extension written in C++ to execute shell commands one by one, outputting the command's output to the console in real-time. Optional chained, and unchained ways are present; meaning that you can choose to stop the script after a command fails (chained), or you can continue as if nothing has happened !

Usage instructions are in the ReadMe file. Feel free to make pull requests or submit issues!

EDIT: However it doesn't return the stdout yet... Just outputs them in real-time. It does now. Well, I just released it today. Maybe we can build on it.

Anyway, I thought it was worth to mention it.

How do I call the base class constructor?

In the header file define a base class:

class BaseClass {
public:
    BaseClass(params);
};

Then define a derived class as inheriting the BaseClass:

class DerivedClass : public BaseClass {
public:
    DerivedClass(params);
};

In the source file define the BaseClass constructor:

BaseClass::BaseClass(params)
{
     //Perform BaseClass initialization
}

By default the derived constructor only calls the default base constructor with no parameters; so in this example, the base class constructor is NOT called automatically when the derived constructor is called, but it can be achieved simply by adding the base class constructor syntax after a colon (:). Define a derived constructor that automatically calls its base constructor:

DerivedClass::DerivedClass(params) : BaseClass(params)
{
     //This occurs AFTER BaseClass(params) is called first and can
     //perform additional initialization for the derived class
}

The BaseClass constructor is called BEFORE the DerivedClass constructor, and the same/different parameters params may be forwarded to the base class if desired. This can be nested for deeper derived classes. The derived constructor must call EXACTLY ONE base constructor. The destructors are AUTOMATICALLY called in the REVERSE order that the constructors were called.

EDIT: There is an exception to this rule if you are inheriting from any virtual classes, typically to achieve multiple inheritance or diamond inheritance. Then you MUST explicitly call the base constructors of all virtual base classes and pass the parameters explicitly, otherwise it will only call their default constructors without any parameters. See: virtual inheritance - skipping constructors

Restore the mysql database from .frm files

I just copy pasted the database folders to data folder in MySQL, i.e. If you have a database called alto then find the folder alto in your MySQL -> Data folder in your backup and copy the entire alto folder and past it to newly installed MySQL -> data folder, restart the MySQL and this works perfect.

No Main class found in NetBeans

Press the hammer to the left of the green arrow (run), for the program to clean & build project. Press green arrow. Select Main Class.

Hope it works for u.

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

This error can occur in several places, most commonly running further LINQ queries on top of a null collection. LINQ as Query Syntax can appear more null-safe than it is. Consider the following samples:

var filteredCollection = from item in getMyCollection()
                         orderby item.ReportDate
                         select item;

This code is not NULL SAFE, meaning that if getMyCollection() returns a null, you'll get the Value cannot be null. Parameter name: source error. Very annoying! But it makes perfect sense because LINQ Query syntax is just syntactic sugar for this equivalent code:

var filteredCollection = getMyCollection().OrderBy(x => x.ReportDate);

Which obviously will blow up if the starting method returns a null.

To prevent this, you can use a null coalescing operator in your LINQ query like so:

var filteredCollection = from item in getMyCollection() ?? 
                              Enumerable.Empty<CollectionItemClass>()
                         orderby item.ReportDate
                         select item;

However, you'll have to remember to do this in any related queries. The best approach (if you control the code that generates the collection) is to make it a coding practice to NEVER RETURN A NULL COLLECTION, EVER. In some cases, returning a null object from a method like "getCustomerById(string id)" is fine, depending on your team coding style, but if you have a method that returns a collection of business objects, like "getAllcustomers()" then it should NEVER return a null array/enumerable/etc. Always always always use an if check, the null coalescing operator, or some other switch to return an empty array/list/enumerable etc, so that consumers of your method can freely LINQ over the results.

Regex match everything after question mark?

Check out this site: http://rubular.com/ Basically the site allows you to enter some example text (what you would be looking for on your site) and then as you build the regular expression it will highlight what is being matched in real time.

Write HTML file using Java

Templates and other methods based on preliminary creation of the document in memory are likely to impose certain limits on resulting document size.

Meanwhile a very straightforward and reliable write-on-the-fly approach to creation of plain HTML exists, based on a SAX handler and default XSLT transformer, the latter having intrinsic capability of HTML output:

String encoding = "UTF-8";
FileOutputStream fos = new FileOutputStream("myfile.html");
OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
StreamResult streamResult = new StreamResult(writer);

SAXTransformerFactory saxFactory =
    (SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler tHandler = saxFactory.newTransformerHandler();
tHandler.setResult(streamResult);

Transformer transformer = tHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

writer.write("<!DOCTYPE html>\n");
writer.flush();
tHandler.startDocument();
    tHandler.startElement("", "", "html", new AttributesImpl());
        tHandler.startElement("", "", "head", new AttributesImpl());
            tHandler.startElement("", "", "title", new AttributesImpl());
                tHandler.characters("Hello".toCharArray(), 0, 5);
            tHandler.endElement("", "", "title");
        tHandler.endElement("", "", "head");
        tHandler.startElement("", "", "body", new AttributesImpl());
            tHandler.startElement("", "", "p", new AttributesImpl());
                tHandler.characters("5 > 3".toCharArray(), 0, 5); // note '>' character
            tHandler.endElement("", "", "p");
        tHandler.endElement("", "", "body");
    tHandler.endElement("", "", "html");
tHandler.endDocument();
writer.close();

Note that XSLT transformer will release you from the burden of escaping special characters like >, as it takes necessary care of it by itself.

And it is easy to wrap SAX methods like startElement() and characters() to something more convenient to one's taste...

What is a raw type and why shouldn't we use it?

Raw types are fine when they express what you want to express.

For example, a deserialisation function might return a List, but it doesn't know the list's element type. So List is the appropriate return type here.

Java synchronized block vs. Collections.synchronizedMap

Collections.synchronizedMap() guarantees that each atomic operation you want to run on the map will be synchronized.

Running two (or more) operations on the map however, must be synchronized in a block. So yes - you are synchronizing correctly.

how to change color of TextinputLayout's label and edittext underline android

I used all of the above answers and none worked. This answer works for API 21+. Use app:hintTextColor attribute when text field is focused and app:textColorHint attribute when in other states. To change the bottmline color use this attribute app:boxStrokeColor as demonstrated below:

<com.google.android.material.textfield.TextInputLayout
            app:boxStrokeColor="@color/colorAccent"
            app:hintTextColor="@color/colorAccent"
            android:textColorHint="@android:color/darker_gray"
    
       <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>

It works for AutoCompleteTextView as well. Hope it works for you:)

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Generate a random number in the range 1 - 10

This stored procedure inserts a rand number into a table. Look out, it inserts an endless numbers. Stop executing it when u get enough numbers.

create a table for the cursor:

CREATE TABLE [dbo].[SearchIndex](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Cursor] [nvarchar](255) NULL) 

GO

Create a table to contain your numbers:

CREATE TABLE [dbo].[ID](
[IDN] [int] IDENTITY(1,1) NOT NULL,
[ID] [int] NULL)

INSERTING THE SCRIPT :

INSERT INTO [SearchIndex]([Cursor])  SELECT N'INSERT INTO ID  SELECT   FLOOR(rand() * 9 + 1)  SELECT COUNT (ID) FROM ID

CREATING AND EXECUTING THE PROCEDURE:

CREATE PROCEDURE [dbo].[RandNumbers] AS
BEGIN
Declare  CURSE  CURSOR  FOR (SELECT  [Cursor] FROM [dbo].[SearchIndex]  WHERE [Cursor] IS NOT NULL)
DECLARE @RandNoSscript NVARCHAR (250)
OPEN CURSE
FETCH NEXT FROM CURSE
INTO @RandNoSscript 
WHILE @@FETCH_STATUS IS NOT NULL 
BEGIN
Print @RandNoSscript
EXEC SP_EXECUTESQL @RandNoSscript;  
 END
 END
GO

Fill your table:

EXEC RandNumbers

Failed to find 'ANDROID_HOME' environment variable

You may want to confirm that your development environment has been set correctly.

Quoting from spring.io:

Set up the Android development environment

Before you can build Android applications, you must install the Android SDK. Installing the Android SDK also installs the AVD Manager, a graphical user interface for creating and managing Android Virtual Devices (AVDs).

  1. From the Android web site, download the correct version of the Android SDK for your operating system.

  2. Unzip the archive to a location of your choosing. For example, on Linux or Mac, you can place it in the root of your user directory. See the Android Developers web site for additional installation details.

  3. Configure the ANDROID_HOME environment variable based on the location of the Android SDK. Additionally, consider adding ANDROID_HOME/tools, and ANDROID_HOME/platform-tools to your PATH.

Mac OS X

export ANDROID_HOME=/<installation location>/android-sdk-macosx
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Linux

export ANDROID_HOME=/<installation location>/android-sdk-linux
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Windows

set ANDROID_HOME=C:\<installation location>\android-sdk-windows
set PATH=%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools

The Android SDK download does not include specific Android platforms. To run the code in this guide, you need to download and install the latest SDK platform. You do this by using the Android SDK and AVD Manager that you installed in the previous section.

  1. Open the Android SDK Manager window:

    android
    

    Note: If this command does not open the Android SDK Manager, then your path is not configured correctly.

  2. Select the Tools checkbox.

  3. Select the checkbox for the latest Android SDK.

  4. From the Extras folder, select the checkbox for the Android Support Library.

  5. Click the Install packages... button to complete the download and installation.

    Note: You may want to install all the available updates, but be aware it will take longer, as each API level is a large download.

Check string length in PHP

The xpath() function does not return a string. It returns an array with XML elements (of type SimpleXMLElement), which may be casted to a string.

if (count($message)) {
   if (strlen((string)$message[0]) < 141) {
      echo "There Are No Contests.";
   }
   else if(strlen((string)$message[0]) > 142) {
      echo "There is One Active Contest.";
   }
}

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

The code from the accepted answer helped me to debug the issue. I then realized that the SN field of the certificate argument wasn't the same as what I thought was my SMTP server. By setting the Host property of the SmtpClient instance to the SN value of the certificate I was able to fix the issue.

How to check if any fields in a form are empty in php

your form is missing the method...

<form name="registrationform" action="register.php" method="post"> //here

anywyas to check the posted data u can use isset()..

Determine if a variable is set and is not NULL

if(!isset($firstname) || trim($firstname) == '')
{
   echo "You did not fill out the required fields.";
}

Count number of columns in a table row

Why not use reduce so that we can take colspan into account? :)

function getColumns(table) {
    var cellsArray = [];
    var cells = table.rows[0].cells;

    // Cast the cells to an array
    // (there are *cooler* ways of doing this, but this is the fastest by far)
    // Taken from https://stackoverflow.com/a/15144269/6424295
    for(var i=-1, l=cells.length; ++i!==l; cellsArray[i]=cells[i]);

    return cellsArray.reduce(
        (cols, cell) =>
            // Check if the cell is visible and add it / ignore it
            (cell.offsetParent !== null) ? cols += cell.colSpan : cols,
        0
    );
}

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

Like @itsneo said, I personally find ? + [ and ] the most convenient ones on a mac. But I can understand if you come from Linux side of things. Then you can use ? + alt + ? or ?.

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You're looking for Select which can be used to transform\project the input sequence:

IEnumerable<string> strings = integers.Select(i => i.ToString());

Measure the time it takes to execute a t-sql query

If you want a more accurate measurement than the answer above:

set statistics time on 

-- Query 1 goes here

-- Query 2 goes here

set statistics time off

The results will be in the Messages window.

Update (2015-07-29):

By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats that may also be of value:

-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.

-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';

SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0)) 
       AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
      (OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
      (DB_NAME(database_id)=@DbName OR @DbName IS NULL)

Disabling Log4J Output in Java

If you want to turn off logging programmatically then use

List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
    logger.setLevel(Level.OFF);
}

Error inflating when extending a class

fwiw, I received this error due to some custom initialization within the constructor attempting to access a null object.

Objective-C: Reading a file line by line

To read a file line by line (also for extreme big files) can be done by the following functions:

DDFileReader * reader = [[DDFileReader alloc] initWithFilePath:pathToMyFile];
NSString * line = nil;
while ((line = [reader readLine])) {
  NSLog(@"read line: %@", line);
}
[reader release];

Or:

DDFileReader * reader = [[DDFileReader alloc] initWithFilePath:pathToMyFile];
[reader enumerateLinesUsingBlock:^(NSString * line, BOOL * stop) {
  NSLog(@"read line: %@", line);
}];
[reader release];

The class DDFileReader that enables this is the following:

Interface File (.h):

@interface DDFileReader : NSObject {
    NSString * filePath;

    NSFileHandle * fileHandle;
    unsigned long long currentOffset;
    unsigned long long totalFileLength;

    NSString * lineDelimiter;
    NSUInteger chunkSize;
}

@property (nonatomic, copy) NSString * lineDelimiter;
@property (nonatomic) NSUInteger chunkSize;

- (id) initWithFilePath:(NSString *)aPath;

- (NSString *) readLine;
- (NSString *) readTrimmedLine;

#if NS_BLOCKS_AVAILABLE
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL *))block;
#endif

@end

Implementation (.m)

#import "DDFileReader.h"

@interface NSData (DDAdditions)

- (NSRange) rangeOfData_dd:(NSData *)dataToFind;

@end

@implementation NSData (DDAdditions)

- (NSRange) rangeOfData_dd:(NSData *)dataToFind {

    const void * bytes = [self bytes];
    NSUInteger length = [self length];

    const void * searchBytes = [dataToFind bytes];
    NSUInteger searchLength = [dataToFind length];
    NSUInteger searchIndex = 0;

    NSRange foundRange = {NSNotFound, searchLength};
    for (NSUInteger index = 0; index < length; index++) {
        if (((char *)bytes)[index] == ((char *)searchBytes)[searchIndex]) {
            //the current character matches
            if (foundRange.location == NSNotFound) {
                foundRange.location = index;
            }
            searchIndex++;
            if (searchIndex >= searchLength) { return foundRange; }
        } else {
            searchIndex = 0;
            foundRange.location = NSNotFound;
        }
    }
    return foundRange;
}

@end

@implementation DDFileReader
@synthesize lineDelimiter, chunkSize;

- (id) initWithFilePath:(NSString *)aPath {
    if (self = [super init]) {
        fileHandle = [NSFileHandle fileHandleForReadingAtPath:aPath];
        if (fileHandle == nil) {
            [self release]; return nil;
        }

        lineDelimiter = [[NSString alloc] initWithString:@"\n"];
        [fileHandle retain];
        filePath = [aPath retain];
        currentOffset = 0ULL;
        chunkSize = 10;
        [fileHandle seekToEndOfFile];
        totalFileLength = [fileHandle offsetInFile];
        //we don't need to seek back, since readLine will do that.
    }
    return self;
}

- (void) dealloc {
    [fileHandle closeFile];
    [fileHandle release], fileHandle = nil;
    [filePath release], filePath = nil;
    [lineDelimiter release], lineDelimiter = nil;
    currentOffset = 0ULL;
    [super dealloc];
}

- (NSString *) readLine {
    if (currentOffset >= totalFileLength) { return nil; }

    NSData * newLineData = [lineDelimiter dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle seekToFileOffset:currentOffset];
    NSMutableData * currentData = [[NSMutableData alloc] init];
    BOOL shouldReadMore = YES;

    NSAutoreleasePool * readPool = [[NSAutoreleasePool alloc] init];
    while (shouldReadMore) {
        if (currentOffset >= totalFileLength) { break; }
        NSData * chunk = [fileHandle readDataOfLength:chunkSize];
        NSRange newLineRange = [chunk rangeOfData_dd:newLineData];
        if (newLineRange.location != NSNotFound) {

            //include the length so we can include the delimiter in the string
            chunk = [chunk subdataWithRange:NSMakeRange(0, newLineRange.location+[newLineData length])];
            shouldReadMore = NO;
        }
        [currentData appendData:chunk];
        currentOffset += [chunk length];
    }
    [readPool release];

    NSString * line = [[NSString alloc] initWithData:currentData encoding:NSUTF8StringEncoding];
    [currentData release];
    return [line autorelease];
}

- (NSString *) readTrimmedLine {
    return [[self readLine] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

#if NS_BLOCKS_AVAILABLE
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL*))block {
  NSString * line = nil;
  BOOL stop = NO;
  while (stop == NO && (line = [self readLine])) {
    block(line, &stop);
  }
}
#endif

@end

The class was done by Dave DeLong

How can I rebuild indexes and update stats in MySQL innoDB?

You can also use the provided CLI tool mysqlcheck to run the optimizations. It's got a ton of switches but at its most basic you just pass in the database, username, and password.

Adding this to cron or the Windows Scheduler can make this an automated process. (MariaDB but basically the same thing.)

Change hover color on a button with Bootstrap customization

The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:

/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
    color: #fff;
    background-color: #0495c9;
    border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
    background-color: #00b3db;
    border-color: #285e8e; /*set the color you want here*/
}

How do I get the different parts of a Flask request's url?

If you are using Python, I would suggest by exploring the request object:

dir(request)

Since the object support the method dict:

request.__dict__

It can be printed or saved. I use it to log 404 codes in Flask:

@app.errorhandler(404)
def not_found(e):
    with open("./404.csv", "a") as f:
        f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
    return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

Why is the console window closing immediately once displayed my output?

this is the answer async at console app in C#?

anything whereever in the console app never use await but instead use theAsyncMethod().GetAwaiter().GetResult();,

example

var result = await HttpClientInstance.SendAsync(message);

becomes

var result = HttpClientInstance.SendAsync(message).GetAwaiter().GetResult();

How do I syntax check a Bash script without running it?

If you need in a variable the validity of all the files in a directory (git pre-commit hook, build lint script), you can catch the stderr output of the "sh -n" or "bash -n" commands (see other answers) in a variable, and have a "if/else" based on that

bashErrLines=$(find bin/ -type f -name '*.sh' -exec sh -n {} \;  2>&1 > /dev/null)
  if [ "$bashErrLines" != "" ]; then 
   # at least one sh file in the bin dir has a syntax error
   echo $bashErrLines; 
   exit; 
  fi

Change "sh" with "bash" depending on your needs

Where can I find "make" program for Mac OS X Lion?

If you need only make and friends. Try installing the command-line-tools provided by Apple. (Assuming you are not doing any iOS development.)

How to connect to LocalDB in Visual Studio Server Explorer?

The following works with Visual Studio 2017 Community Edition on Windows 10 using SQLServer Express 2016.

Open a PowerShell check what it is called using SqlLocalDB.exe info and whether it is Running with SqlLocalDB.exe info NAME. Here's what it looks like on my machine:

> SqlLocalDB.exe info
MSSQLLocalDB
> SqlLocalDB.exe info MSSQLLocalDB
Name:               mssqllocaldb
Version:            13.0.1601.5
Shared name:
Owner:              DESKTOP-I4H3E09\simon
Auto-create:        Yes
State:              Running
Last start time:    4/12/2017 8:24:36 AM
Instance pipe name: np:\\.\pipe\LOCALDB#EFC58609\tsql\query
>

If it isn't running then you need to start it with SqlLocalDB.exe start MSSQLLocalDB. When it is running you see the Instance pipe name: which starts with np:\\. Copy that named pipe string. Within VS2017 open the view Server Explorer and create a new connection of type Microsoft SQL Server (SqlClient) (don't be fooled by the other file types you want the full fat connection type) and set the Server name: to be the instance pipe name you copied from PowerShell.

I also set the Connect to database to be the same database that was in the connection string that was working in my Dotnet Core / Entity Framework Core project which was set up using dotnet ef database update.

You can login and create a database using the sqlcmd and the named pipe string:

sqlcmd -S np:\\.\pipe\LOCALDB#EFC58609\tsql\query 1> create database EFGetStarted.ConsoleApp.NewDb; 2> GO

There are instructions on how to create a user for your application at https://docs.microsoft.com/en-us/sql/tools/sqllocaldb-utility

A simple explanation of Naive Bayes Classification

Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action
It uses an example problem from this book on page 351
This is the data set that we will be using
enter image description here
In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'} then what is the probability that he will buy or will not buy a computer.
The code below exactly answers that question.
Just create a file called named new_dataset.csv and paste the following content.

Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no

Here is the code the comments explains everything we are doing here! [python]

import pandas as pd 
import pprint 

class Classifier():
    data = None
    class_attr = None
    priori = {}
    cp = {}
    hypothesis = None


    def __init__(self,filename=None, class_attr=None ):
        self.data = pd.read_csv(filename, sep=',', header =(0))
        self.class_attr = class_attr

    '''
        probability(class) =    How many  times it appears in cloumn
                             __________________________________________
                                  count of all class attribute
    '''
    def calculate_priori(self):
        class_values = list(set(self.data[self.class_attr]))
        class_data =  list(self.data[self.class_attr])
        for i in class_values:
            self.priori[i]  = class_data.count(i)/float(len(class_data))
        print "Priori Values: ", self.priori

    '''
        Here we calculate the individual probabilites 
        P(outcome|evidence) =   P(Likelihood of Evidence) x Prior prob of outcome
                               ___________________________________________
                                                    P(Evidence)
    '''
    def get_cp(self, attr, attr_type, class_value):
        data_attr = list(self.data[attr])
        class_data = list(self.data[self.class_attr])
        total =1
        for i in range(0, len(data_attr)):
            if class_data[i] == class_value and data_attr[i] == attr_type:
                total+=1
        return total/float(class_data.count(class_value))

    '''
        Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
        (Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
        scaled by P(Multiple Evidence)
    '''
    def calculate_conditional_probabilities(self, hypothesis):
        for i in self.priori:
            self.cp[i] = {}
            for j in hypothesis:
                self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
        print "\nCalculated Conditional Probabilities: \n"
        pprint.pprint(self.cp)

    def classify(self):
        print "Result: "
        for i in self.cp:
            print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]

if __name__ == "__main__":
    c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
    c.calculate_priori()
    c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}

    c.calculate_conditional_probabilities(c.hypothesis)
    c.classify()

output:

Priori Values:  {'yes': 0.6428571428571429, 'no': 0.35714285714285715}

Calculated Conditional Probabilities: 

{
 'no': {
        '<=30': 0.8,
        'fair': 0.6, 
        'medium': 0.6, 
        'yes': 0.4
        },
'yes': {
        '<=30': 0.3333333333333333,
        'fair': 0.7777777777777778,
        'medium': 0.5555555555555556,
        'yes': 0.7777777777777778
      }
}

Result: 
yes  ==>  0.0720164609053
no  ==>  0.0411428571429

Hope it helps in better understanding the problem

peace

Chrome not rendering SVG referenced via <img> tag

I also got the same issue with chrome, after adding DOCTYPE it works as expected

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

Before

    <?xml version="1.0" encoding="iso-8859-1"?>
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="792px" height="792px" viewBox="0 0 792 792" style="enable-background:new 0 0 792 792;" xml:space="preserve">
    <g fill="none" stroke="black" stroke-width="15">
  ......
  ......
  .......
  </g>
</svg>

After

    <?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="792px" height="792px" viewBox="0 0 792 792" style="enable-background:new 0 0 792 792;" xml:space="preserve">
    <g fill="none" stroke="black" stroke-width="15">
  ......
  ......
  .......
  </g>
</svg>

Group by with multiple columns using lambda

if your table is like this

rowId     col1    col2    col3    col4
 1          a       e       12       2
 2          b       f       42       5
 3          a       e       32       2
 4          b       f       44       5


var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 =  r.Field<int>("col1"), pp2 = r.Field<int>("col2")});

Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

public IActionResult AddURLTest()
{
    return ViewComponent("AddURL");
}

You can load it using JQuery load method.

$(document).ready (function(){
    $("#LoadSignIn").click(function(){
        $('#UserControl').load("/Home/AddURLTest");
    });
});

source code link

How can I split a text file using PowerShell?

Here is my solution to split a file called patch6.txt (about 32,000 lines) into separate files of 1000 lines each. Its not quick, but it does the job.

$infile = "D:\Malcolm\Test\patch6.txt"
$path = "D:\Malcolm\Test\"
$lineCount = 1
$fileCount = 1

foreach ($computername in get-content $infile)
{
    write $computername | out-file -Append $path_$fileCount".txt"
    $lineCount++

    if ($lineCount -eq 1000)
    {
        $fileCount++
        $lineCount = 1
    }
}

Django download a file

When you upload a file using FileField, the file will have a URL that you can use to point to the file and use HTML download attribute to download that file you can simply do this.

models.py

The model.py looks like this

class CsvFile(models.Model):
    csv_file = models.FileField(upload_to='documents')

views.py

#csv upload

class CsvUploadView(generic.CreateView):

   model = CsvFile
   fields = ['csv_file']
   template_name = 'upload.html'

#csv download

class CsvDownloadView(generic.ListView):

    model = CsvFile
    fields = ['csv_file']
    template_name = 'download.html'

Then in your templates.

#Upload template

upload.html

<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>

#download template

download.html

  {% for document in object_list %}

     <a href="{{ document.csv_file.url }}" download  class="btn btn-dark float-right">Download</a>

  {% endfor %}

I did not use forms, just rendered model but either way, FileField is there and it will work the same.

Converting a String to a List of Words?

You can try and do this:

tryTrans = string.maketrans(",!", "  ")
str = "This is a string, with words!"
str = str.translate(tryTrans)
listOfWords = str.split()

How to show alert message in mvc 4 controller?

TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])

How to determine if a string is a number with C++?

You may test if a string is convertible to integer by using boost::lexical_cast. If it throws bad_lexical_cast exception then string could not be converted, otherwise it can.

See example of such a test program below:

#include <boost/lexical_cast.hpp>
#include <iostream>

int main(int, char** argv)
{
        try
        {
                int x = boost::lexical_cast<int>(argv[1]);
                std::cout << x << " YES\n";
        }
        catch (boost::bad_lexical_cast const &)
        {
                std:: cout << "NO\n";
        }
        return 0;
}

Sample execution:

# ./a.out 12
12 YES
# ./a.out 12/3
NO

Pandas dataframe get first row of each group

I'd suggest to use .nth(0) rather than .first() if you need to get the first row.

The difference between them is how they handle NaNs, so .nth(0) will return the first row of group no matter what are the values in this row, while .first() will eventually return the first not NaN value in each column.

E.g. if your dataset is :

df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
            'value'  : ["first","second","third", np.NaN,
                        "second","first","second","third",
                        "fourth","first","second"]})

>>> df.groupby('id').nth(0)
    value
id        
1    first
2    NaN
3    first
4    first

And

>>> df.groupby('id').first()
    value
id        
1    first
2    second
3    first
4    first

How do you create vectors with specific intervals in R?

Use the code

x = seq(0,100,5) #this means (starting number, ending number, interval)

the output will be

[1]   0   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75
[17]  80  85  90  95 100

Flexbox: center horizontally and vertically

You can make use of

display: flex;
align-items: center;
justify-content: center;

on your parent component

enter image description here

Read XML Attribute using XmlDocument

XmlDocument.Attributes perhaps? (Which has a method GetNamedItem that will presumably do what you want, although I've always just iterated the attribute collection)

c++ array - expression must have a constant value

Using the GCC compiler(which I did locally) and an online compiler(link), a code similar to the one in the question runs provided a variable name.

#include<iostream>

int main(){
    int r= 2, c=3;
    int arr[r][c];
    arr[0][1]= 3;
    std::cout<<arr[0][1];
}

Output: 3

Though I quote cplusplus.com,

NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression since arrays are blocks of static memory whose size must be determined at compile-time before the program runs.

It seems like the present compilers have been changed in this regard. This is a C99 standard which the maintainers of the standard compilers added to their compilers.

We need not have a const declaration. During compilation, the compiler automatically substitutes the value.

This question goes around the topic.

NOTE: This is not the standard coding practice, so some compilers might still throw an error.

How is "mvn clean install" different from "mvn install"?

To stick with the Maven terms:

  • "clean" is a phase of the clean lifecycle
  • "install" is a phase of the default lifecycle

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference

How to make for loops in Java increase by increments other than 1

It's just a syntax error. You just have to replace j+3 by j=j+3 or j+=3.

How to provide shadow to Button

For android version 5.0 & above

try the Elevation for other views..

android:elevation="10dp"

For Buttons,

android:stateListAnimator="@anim/button_state_list_animator"

button_state_list_animator.xml - https://android.googlesource.com/platform/frameworks/base/+/master/core/res/res/anim/button_state_list_anim_material.xml

below 5.0 version,

For all views,

 android:background="@android:drawable/dialog_holo_light_frame"

My output:

enter image description here

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
//OR    
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
//OR    
SET autocommit = ON;

How to determine if OpenSSL and mod_ssl are installed on Apache2

You should install this Apache mod, http://httpd.apache.org/docs/2.0/mod/mod_info.html, it basically gives you a run down of the mods you're using and the Apache settings. I have this enabled on my Apache and it gives me this info for my website,

Server Version: Apache/2.2.3 (Debian) mod_jk/1.2.18 PHP/5.2.0-8+etch13 mod_ssl/2.2.3 OpenSSL/0.9.8c mod_perl/2.0.2 Perl/v5.8.8

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

How to add smooth scrolling to Bootstrap's scroll spy function

What onetrickpony posted is okay, but if you want to have a more general solution, you can just use the code below.

Instead of selecting just the id of the anchor, you can make it bit more standard-like and just selecting the attribute name of the <a>-Tag. This will save you from writing an extra id tag. Just add the smoothscroll class to the navbar element.

What changed

1) $('#nav ul li a[href^="#"]') to $('#nav.smoothscroll ul li a[href^="#"]')

2) $(this.hash) to $('a[name="' + this.hash.replace('#', '') + '"]')

Final Code

/* Enable smooth scrolling on all links with anchors */
$('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {

  // prevent default anchor click behavior
  e.preventDefault();

  // store hash
  var hash = this.hash;

  // animate
  $('html, body').animate({
    scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
  }, 300, function(){

    // when done, add hash to url
    // (default click behaviour)
    window.location.hash = hash;

  });
});

Transform only one axis to log10 scale with ggplot2

I think I got it at last by doing some manual transformations with the data before visualization:

d <- diamonds
# computing logarithm of prices
d$price <- log10(d$price)

And work out a formatter to later compute 'back' the logarithmic data:

formatBack <- function(x) 10^x 
# or with special formatter (here: "dollar")
formatBack <- function(x) paste(round(10^x, 2), "$", sep=' ') 

And draw the plot with given formatter:

m <- ggplot(d, aes(y = price, x = color))
m + geom_boxplot() + scale_y_continuous(formatter='formatBack')

alt text

Sorry to the community to bother you with a question I could have solved before! The funny part is: I was working hard to make this plot work a month ago but did not succeed. After asking here, I got it.

Anyway, thanks to @DWin for motivation!

Java check if boolean is null

null is a value assigned to a reference type. null is a reserved value, indicating that a reference does not resemble an instance of an object.

A boolean is not an instance of an Object. It is a primitive type, like int and float. In the same way that: int x has a value of 0, boolean x has a value of false.

IBOutlet and IBAction

The traditional way to flag a method so that it will appear in Interface Builder, and you can drag a connection to it, has been to make the method return type IBAction. However, if you make your method void, instead (IBAction is #define'd to be void), and provide an (id) argument, the method is still visible. This provides extra flexibility, al

All 3 of these are visible from Interface Builder:

-(void) someMethod1:(id) sender; 
-(IBAction) someMethod2; 
-(IBAction) someMethod3:(id) sender;

See Apple's Interface Builder User Guide for details, particularly the section entitled Xcode Integration.

Resize image in the wiki of GitHub using Markdown

On GitHub, you can use HTML directly instead of Markdown:

<a href="url"><img src="http://url.to/image.png" align="left" height="48" width="48" ></a>

This should make it.

What does -save-dev mean in npm install grunt --save-dev

--save-dev: Package will appear in your devDependencies.

According to the npm install docs.

If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.

In other words, when you run npm install, your project's devDependencies will be installed, but the devDependencies for any packages that your app depends on will not be installed; further, other apps having your app as a dependency need not install your devDependencies. Such modules should only be needed when developing the app (eg grunt, mocha etc).

According to the package.json docs

Edit: Attempt at visualising what npm install does:

  • yourproject
    • dependency installed
      • dependency installed
        • dependency installed
        • devDependency NOT installed
      • devDependency NOT installed
    • devDependency installed
      • dependency installed
      • devDependency NOT installed

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

Need help rounding to 2 decimal places

The System.Math.Round method uses the Double structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:

Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)

Result: 0.58

Making an array of integers in iOS

I created a simple Objective C wrapper around the good old C array to be used more conveniently: https://gist.github.com/4705733

How do I access call log for android?

Before considering making Read Call Log or Read SMS permissions a part of your application I strongly advise you to have a look at this policy of Google Play Market: https://support.google.com/googleplay/android-developer/answer/9047303?hl=en

Those permissions are very sensitive and you will have to prove that your application needs them. But even if it really needs them Google Play Support team may easily reject your request without proper explanations.

This is what happened to me. After providing all the needed information along with the Demonstration video of my application it was rejected with the explanation that my "account is not authorized to provide a certain use case solution in my application" (the list of use cases they may consider as an exception is listed on that Policy page). No link to any policy statement was provided to explain what it all means. Basically they just judged my app as not to go without proper explanation.

I wish you good luck of cause with your applications guys but be careful.

SQL, How to convert VARCHAR to bigint?

an alternative would be to do something like:

SELECT
   CAST(P0.seconds as bigint) as seconds
FROM
   (
   SELECT
      seconds
   FROM
      TableName
   WHERE
      ISNUMERIC(seconds) = 1
   ) P0

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I found this blog post which cleared up a few things. To quote the most relevant bit:

Mixed Active Content is now blocked by default in Firefox 23!

What is Mixed Content?
When a user visits a page served over HTTP, their connection is open for eavesdropping and man-in-the-middle (MITM) attacks. When a user visits a page served over HTTPS, their connection with the web server is authenticated and encrypted with SSL and hence safeguarded from eavesdroppers and MITM attacks.

However, if an HTTPS page includes HTTP content, the HTTP portion can be read or modified by attackers, even though the main page is served over HTTPS. When an HTTPS page has HTTP content, we call that content “mixed”. The webpage that the user is visiting is only partially encrypted, since some of the content is retrieved unencrypted over HTTP. The Mixed Content Blocker blocks certain HTTP requests on HTTPS pages.

The resolution, in my case, was to simply ensure the jquery includes were as follows (note the removal of the protocol):

<link rel="stylesheet" href="//code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css" type="text/css">
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"></script>

Note that the temporary 'fix' is to click on the 'shield' icon in the top-left corner of the address bar and select 'Disable Protection on This Page', although this is not recommended for obvious reasons.

UPDATE: This link from the Firefox (Mozilla) support pages is also useful in explaining what constitutes mixed content and, as given in the above paragraph, does actually provide details of how to display the page regardless:

Most websites will continue to work normally without any action on your part.

If you need to allow the mixed content to be displayed, you can do that easily:

Click the shield icon Mixed Content Shield in the address bar and choose Disable Protection on This Page from the dropdown menu.

The icon in the address bar will change to an orange warning triangle Warning Identity Icon to remind you that insecure content is being displayed.

To revert the previous action (re-block mixed content), just reload the page.

Postgres integer arrays as parameters?

See: http://www.postgresql.org/docs/9.1/static/arrays.html

If your non-native driver still does not allow you to pass arrays, then you can:

  • pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array)

    CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$ 
    DECLARE
           ids INT[];
    BEGIN
           ids = string_to_array($1,',');
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(:1)
    

    with :1 = '1,2,3,4'

  • rely on Postgres itself to cast from a string to an array

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method('{1,2,3,4}')
    
  • choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(ARRAY [1,2,3,4])
    

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

If you've got all the plugin JS's imported and in the correct order, but you're still having issues, it seems that specifying your own "add" handler nerfs the one from the *-validate.js plugin, which normally would fire off all the validation by calling data.process(). So to fix it just do something like this in your "add" event handler:

$('#whatever').fileupload({
...
add: function(e, data) {
   var $this = $(this);
   data.process(function() {
      return $this.fileupload('process', data);
   }).done(function(){
      //do success stuff
      data.submit(); <-- fire off the upload to the server
   }).fail(function() {
      alert(data.files[0].error);
   });
}
...
});

ContractFilter mismatch at the EndpointDispatcher exception

So, my case was the following. I didn't use proxy for the client-server interaction, I used ChannelFactory (thus all the advice to upgrade to service reference was meaningless to me).

The service was hosted in IIS and for some reason it had wrong references in the bin folder there. The project recompilation simply didn't lead to new dlls in that folder.

So I just deleted all the stuff from there and added reference to the service in the same solution, then recompiled and now everything works.

Why is Visual Studio 2013 very slow?

It is something concerned with the graphics drivers. If you update them you will be fine.

Or you can disable the hardware graphics acceleration in Visual Studio according to these steps:

  1. In Visual Studio, click "Tools", and then click "Options".

  2. In the Options dialog box, navigate to the "Environment > General" section and clear the "Automatically adjust visual experience based on client performance" check box. (Refer to the following screen shot for this step.)

  3. Clear the "Use hardware graphics acceleration if available" check box to prevent the use of hardware graphics acceleration.

  4. Select or clear the "Enable rich client visual experience" check box to make sure that rich visuals are always on or off, respectively. When this check box is selected, rich visuals are used independent of the computer environment. For example, rich visuals are used when you run Visual Studio locally on a rich client and over remote desktop.

enter image description here

References:

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

We had the same issue while trying to launch Selenium tests from Jenkins. I had selected the 'Start Xvfb before the build, and shut it down after' box and passed in the necessary screen options, but I was still getting this error.

It finally worked when we passed in the following commands in the Execute Shell box.

Xvfb :99 -ac -screen 0 1280x1024x24 & nice -n 10 x11vnc 2>&1 & ... killall Xvfb

Automatically add all files in a folder to a target using CMake?

As of CMake 3.1+ the developers strongly discourage users from using file(GLOB or file(GLOB_RECURSE to collect lists of source files.

Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.

See the documentation here.

There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.


It is possible. E.g. with file(GLOB:

cmake_minimum_required(VERSION 2.8)

file(GLOB helloworld_SRC
     "*.h"
     "*.cpp"
)

add_executable(helloworld ${helloworld_SRC})

Note that this requires manual re-running of cmake if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.

As of CMake 3.12, you can pass the CONFIGURE_DEPENDS flag to file(GLOB to automatically check and reset the file lists any time the build is invoked. You would write:

cmake_minimum_required(VERSION 3.12)

file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")

This at least lets you avoid manually re-running CMake every time a file is added.

Check if a number has a decimal place/is a whole number

Perhaps this works for you?

It uses regex to check if there is a comma in the number, and if there is not, then it will add the comma and stripe.

var myNumber = '50';
function addCommaStripe(text){
    if(/,/.test(text) == false){
        return text += ',-';
    } else {
        return text;
    }
}
myNumber = addCommaStripe(myNumber);

Benefits of EBS vs. instance-store (and vice-versa)

Eric pretty much nailed it. We (Bitnami) are a popular provider of free AMIs for popular applications and development frameworks (PHP, Joomla, Drupal, you get the idea). I can tell you that EBS-backed AMIs are significantly more popular than S3-backed. In general I think s3-backed instances are used for distributed, time-limited jobs (for example, large scale processing of data) where if one machine fails, another one is simply spinned up. EBS-backed AMIS tend to be used for 'traditional' server tasks, such as web or database servers that keep state locally and thus require the data to be available in the case of crashing.

One aspect I did not see mentioned is the fact that you can take snapshots of an EBS-backed instance while running, effectively allowing you to have very cost-effective backups of your infrastructure (the snapshots are block-based and incremental)

nginx upload client_max_body_size issue

nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size by sending a 413 response and closing the connection.

Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.

If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large response rather than 100 Continue if Content-Length exceeds the maximum body size.

Default Activity not found in Android Studio

Modify "Workspace.xml" (press Ctrl + Shft + R to search it)

  1. Modify the activity name with package name

  2. Make sure to change "name="USE_COMMAND_LINE" to value="false"

  3. Reload the project

Done!

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

SQL is a declarative language, not a procedural language. That is, you construct a SQL statement to describe the results that you want. You are not telling the SQL engine how to do the work.

As a general rule, it is a good idea to let the SQL engine and SQL optimizer find the best query plan. There are many person-years of effort that go into developing a SQL engine, so let the engineers do what they know how to do.

Of course, there are situations where the query plan is not optimal. Then you want to use query hints, restructure the query, update statistics, use temporary tables, add indexes, and so on to get better performance.

As for your question. The performance of CTEs and subqueries should, in theory, be the same since both provide the same information to the query optimizer. One difference is that a CTE used more than once could be easily identified and calculated once. The results could then be stored and read multiple times. Unfortunately, SQL Server does not seem to take advantage of this basic optimization method (you might call this common subquery elimination).

Temporary tables are a different matter, because you are providing more guidance on how the query should be run. One major difference is that the optimizer can use statistics from the temporary table to establish its query plan. This can result in performance gains. Also, if you have a complicated CTE (subquery) that is used more than once, then storing it in a temporary table will often give a performance boost. The query is executed only once.

The answer to your question is that you need to play around to get the performance you expect, particularly for complex queries that are run on a regular basis. In an ideal world, the query optimizer would find the perfect execution path. Although it often does, you may be able to find a way to get better performance.

How to find all the subclasses of a class given its name?

Python 3.6 - __init_subclass__

As other answer mentioned you can check the __subclasses__ attribute to get the list of subclasses, since python 3.6 you can modify this attribute creation by overriding the __init_subclass__ method.

class PluginBase:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)

class Plugin1(PluginBase):
    pass

class Plugin2(PluginBase):
    pass

This way, if you know what you're doing, you can override the behavior of of __subclasses__ and omit/add subclasses from this list.

What is the maximum length of a table name in Oracle?

Teach a man to fish

Notice the data-type and size

>describe all_tab_columns

VIEW all_tab_columns

Name                                      Null?    Type                        
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)                
 TABLE_NAME                                NOT NULL VARCHAR2(30)                
 COLUMN_NAME                               NOT NULL VARCHAR2(30)                
 DATA_TYPE                                          VARCHAR2(106)               
 DATA_TYPE_MOD                                      VARCHAR2(3)                 
 DATA_TYPE_OWNER                                    VARCHAR2(30)                
 DATA_LENGTH                               NOT NULL NUMBER                      
 DATA_PRECISION                                     NUMBER                      
 DATA_SCALE                                         NUMBER                      
 NULLABLE                                           VARCHAR2(1)                 
 COLUMN_ID                                          NUMBER                      
 DEFAULT_LENGTH                                     NUMBER                      
 DATA_DEFAULT                                       LONG                        
 NUM_DISTINCT                                       NUMBER                      
 LOW_VALUE                                          RAW(32)                     
 HIGH_VALUE                                         RAW(32)                     
 DENSITY                                            NUMBER                      
 NUM_NULLS                                          NUMBER                      
 NUM_BUCKETS                                        NUMBER                      
 LAST_ANALYZED                                      DATE                        
 SAMPLE_SIZE                                        NUMBER                      
 CHARACTER_SET_NAME                                 VARCHAR2(44)                
 CHAR_COL_DECL_LENGTH                               NUMBER                      
 GLOBAL_STATS                                       VARCHAR2(3)                 
 USER_STATS                                         VARCHAR2(3)                 
 AVG_COL_LEN                                        NUMBER                      
 CHAR_LENGTH                                        NUMBER                      
 CHAR_USED                                          VARCHAR2(1)                 
 V80_FMT_IMAGE                                      VARCHAR2(3)                 
 DATA_UPGRADED                                      VARCHAR2(3)                 
 HISTOGRAM                                          VARCHAR2(15)                

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

Explicitly adding a npm version to file package.json ("npm": "1.1.x") and not checking in folder node_modules to Git worked for me.

It may be slower to deploy (since it downloads the packages each time), but I couldn't get the packages to compile when they were checked in. Heroku was looking for files that only existed on my local box.

MYSQL import data from csv using LOAD DATA INFILE

You can use LOAD DATA INFILE command to import csv file into table.

Check this link MySQL - LOAD DATA INFILE.

LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abc
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);

For MySQL 8.0 users:

Using the LOCAL keyword hold security risks and as of MySQL 8.0 the LOCAL capability is set to False by default. You might see the error:

ERROR 1148: The used command is not allowed with this MySQL version

You can overwrite it by following the instructions in the docs. Beware that such overwrite does not solve the security issue but rather just an acknowledge that you are aware and willing to take the risk.

How to make a HTML list appear horizontally instead of vertically using CSS only?

You will have to use something like below

_x000D_
_x000D_
#menu ul{_x000D_
  list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
  display: inline;_x000D_
}_x000D_
 
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>First menu item</li>_x000D_
    <li>Second menu item</li>_x000D_
    <li>Third menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to Find App Pool Recycles in Event Log

As link-only answers are not preferred, I will just copy and paste the content of the link of the accepted answer


It is definitely System Log.

Which Log file? Well -- you can check the physical path by right-clicking on the System Log (e.g. Server Manager | Diagnostics | Event Viewer | Windows Logs). The default physical path is %SystemRoot%\System32\Winevt\Logs\System.evtx.

You can create a Custom Filter and filter by "Source: WAS" to quickly see only entries generated by IIS.

You may need first to enable logging of such even for a specific App Pool -- by default App Pool has only 3 recycle events out of 8 enabled. To change it using GUI: II S Manager | Application Pools | Select App Pool -> Advanced Settings | Generate Recycle Event Log Entry.

Creating a script for a Telnet session?

Check for the SendCommand tool.

You can use it as follows:

perl sendcommand.pl -i login.txt -t cisco -c "show ip route"

How can I retrieve the remote git address of a repo?

When you want to show an URL of remote branches, try:

git remote -v

How to make System.out.println() shorter

Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.

Read environment variables in Node.js

If you want to use a string key generated in your Node.js program, say, var v = 'HOME', you can use process.env[v].

Otherwise, process.env.VARNAME has to be hardcoded in your program.

How to hide close button in WPF window?

To disable close button you should add the following code to your Window class (the code was taken from here, edited and reformatted a bit):

protected override void OnSourceInitialized(EventArgs e)
{
    base.OnSourceInitialized(e);

    HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;

    if (hwndSource != null)
    {
        hwndSource.AddHook(HwndSourceHook);
    }

}

private bool allowClosing = false;

[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);

private const uint MF_BYCOMMAND = 0x00000000;
private const uint MF_GRAYED = 0x00000001;

private const uint SC_CLOSE = 0xF060;

private const int WM_SHOWWINDOW = 0x00000018;
private const int WM_CLOSE = 0x10;

private IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    switch (msg)
    {
        case WM_SHOWWINDOW:
            {
                IntPtr hMenu = GetSystemMenu(hwnd, false);
                if (hMenu != IntPtr.Zero)
                {
                    EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
                }
            }
            break;
        case WM_CLOSE:
            if (!allowClosing)
            {
                handled = true;
            }
            break;
    }
    return IntPtr.Zero;
}

This code also disables close item in System menu and disallows closing the dialog using Alt+F4.

You will probably want to close the window programmatically. Just calling Close() will not work. Do something like this:

allowClosing = true;
Close();

What is the best open XML parser for C++?

Do not use TinyXML if you're concerned about efficiency/memory management (it tends to allocate lots of tiny blocks). My personal favourite is RapidXML.

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

We were getting this same error in Fiddler when trying to figure out why our Silverlight ArcGIS map viewer wasn't loading the map. In our case it was a typo in the URL in the code. There was an equal sign in there for some reason.
http:=//someurltosome/awesome/place
instead of
http://someurltosome/awesome/place

After taking out that equal sign it worked great (of course).

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Uploading both data and files in one form using Ajax?

The problem I had was using the wrong jQuery identifier.

You can upload data and files with one form using ajax.

PHP + HTML

<?php

print_r($_POST);
print_r($_FILES);
?>

<form id="data" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button>Submit</button>
</form>

jQuery + Ajax

$("form#data").submit(function(e) {
    e.preventDefault();    
    var formData = new FormData(this);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });
});

Short Version

$("form#data").submit(function(e) {
    e.preventDefault();
    var formData = new FormData(this);    

    $.post($(this).attr("action"), formData, function(data) {
        alert(data);
    });
});

PostgreSQL: insert from another table

You could use coalesce:

insert into destination select coalesce(field1,'somedata'),... from source;

Difference between adjustResize and adjustPan in android?

As doc says also keep in mind the correct value combination:

The setting must be one of the values listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group — multiple "state..." values, for example — has undefined results. Individual values are separated by a vertical bar (|). For example:

<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >

Insert line at middle of file with Python?

There is a combination of techniques which I found useful in solving this issue:

with open(file, 'r+') as fd:
    contents = fd.readlines()
    contents.insert(index, new_string)  # new_string should end in a newline
    fd.seek(0)  # readlines consumes the iterator, so we need to start over
    fd.writelines(contents)  # No need to truncate as we are increasing filesize

In our particular application, we wanted to add it after a certain string:

with open(file, 'r+') as fd:
    contents = fd.readlines()
    if match_string in contents[-1]:  # Handle last line to prevent IndexError
        contents.append(insert_string)
    else:
        for index, line in enumerate(contents):
            if match_string in line and insert_string not in contents[index + 1]:
                contents.insert(index + 1, insert_string)
                break
    fd.seek(0)
    fd.writelines(contents)

If you want it to insert the string after every instance of the match, instead of just the first, remove the else: (and properly unindent) and the break.

Note also that the and insert_string not in contents[index + 1]: prevents it from adding more than one copy after the match_string, so it's safe to run repeatedly.

Export HTML table to pdf using jspdf

We can separate out section of which we need to convert in PDF

For example, if table is in class "pdf-table-wrap"

After this, we need to call html2canvas function combined with jsPDF

following is sample code

var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var imgData = canvas.toDataURL("image/png", 1.0);
        var width = canvas.width;
        var height = canvas.clientHeight;
        pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));

    }
});
setTimeout(function() {
    //jsPDF code to save file
    pdf.save('sample.pdf');
}, 0);

Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

It is not necessary to stop timer, see nice solution from this post:

"You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately."

private void CreatorLoop(object state) 
 {
   if (Monitor.TryEnter(lockObject))
   {
     try
     {
       // Work here
     }
     finally
     {
       Monitor.Exit(lockObject);
     }
   }
 }

Plotting multiple lines, in different colors, with pandas dataframe

You could use groupby to split the DataFrame into subgroups according to the color:

for key, grp in df.groupby(['color']):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()

for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)

plt.legend(loc='best')
plt.show()

yields enter image description here

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

How do I serialize a C# anonymous type to a JSON string?

Assuming you are using this for a web service, you can just apply the following attribute to the class:

[System.Web.Script.Services.ScriptService]

Then the following attribute to each method that should return Json:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

And set the return type for the methods to be "object"

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

Check if a Postgres JSON array contains a string

You could use @> operator to do this something like

SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';

Finding repeated words on a string and counting the repetitions

    public static void main(String[] args){
    String string = "elamparuthi, elam, elamparuthi";
    String[] s = string.replace(" ", "").split(",");
    String[] op;
    String ops = "";

    for(int i=0; i<=s.length-1; i++){
        if(!ops.contains(s[i]+"")){
            if(ops != "")ops+=", "; 
            ops+=s[i];
        }

    }
    System.out.println(ops);
}

How do I select an entire row which has the largest ID in the table?

Try with this

 SELECT top 1  id, Col2,  row_number() over (order by id desc)  FROM Table

What is the difference between require and require-dev sections in composer.json?

General rule is that you want packages from require-dev section only in development (dev) environments, for example local environment.

Packages in require-dev section are packages which help you debug app, run tests etc.

At staging and production environment you probably want only packages from require section.

But anyway you can run composer install --no-dev and composer update --no-dev on any environment, command will install only packages from required section not from require-dev, but probably you want to run this only at staging and production environments not on local.

Theoretically you can put all packages in require section and nothing will happened, but you don't want developing packages at production environment because of the following reasons :

  1. speed
  2. potential of expose some debuging info
  3. etc

Some good candidates for require-dev are :

"filp/whoops": "^2.0",
"fzaninotto/faker": "^1.4",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^2.0",
"phpunit/phpunit": "^7.0"

you can see what above packages are doing and you will see why you don't need them on production.

See more here : https://getcomposer.org/doc/04-schema.md