Programs & Examples On #Directoryservices

System.DirectoryServices is the .NET library used to access Microsoft's Active Directory, which holds information about users, groups, computers, permissions and more

How to get all the AD groups for a particular user?

If you have a LDAP connection with a username and password to connect to Active Directory, here is the code I used to connect properly:

using System.DirectoryServices.AccountManagement;

// ...

// Connection information
var connectionString = "LDAP://domain.com/DC=domain,DC=com";
var connectionUsername = "your_ad_username";
var connectionPassword = "your_ad_password";

// Get groups for this user
var username = "myusername";

// Split the LDAP Uri
var uri = new Uri(connectionString);
var host = uri.Host;
var container = uri.Segments.Count() >=1 ? uri.Segments[1] : "";

// Create context to connect to AD
var princContext = new PrincipalContext(ContextType.Domain, host, container, connectionUsername, connectionPassword);

// Get User
UserPrincipal user = UserPrincipal.FindByIdentity(princContext, IdentityType.SamAccountName, username);

// Browse user's groups
foreach (GroupPrincipal group in user.GetGroups())
{
    Console.Out.WriteLine(group.Name);
}

Error 0x80005000 and DirectoryServices

I encounter this error when I'm querying an entry of another domain of the forrest and this entry have some custom attribut of the other domain.

To solve this error, I only need to specify the server in the url LDAP :

Path with error = LDAP://CN=MyObj,DC=DOMAIN,DC=COM

Path without error : LDAP://domain.com:389/CN=MyObj,DC=Domain,DC=COM

Get json value from response

Use safely-turning-a-json-string-into-an-object

var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

var jsonObject = (new Function("return " + jsonString))();

alert(jsonObject.id);

How to get Linux console window width in Python

Try "blessings"

I was looking for the very same thing. It is very easy to use and offers tools for coloring, styling and positioning in the terminal. What you need is as easy as:

from blessings import Terminal

t = Terminal()

w = t.width
h = t.height

Works like a charm in Linux. (I'm not sure about MacOSX and Windows)

Download and documentation here

or you can install it with pip:

pip install blessings

How can I call controller/view helper methods from the console in Ruby on Rails?

Here is how to make an authenticated POST request, using Refinery as an example:

# Start Rails console
rails console
# Get the login form
app.get '/community_members/sign_in'
# View the session
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the login request.
# Log in from the console to create a session
app.post '/community_members/login', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=",  "refinery_user[login]"=>'chloe', 'refinery_user[password]'=>'test'}
# View the session to verify CSRF token is the same
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the request. It's best to edit this in Notepad++
app.post '/refinery/blog/posts', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=", "switch_locale"=>"en", "post"=>{"title"=>"Test", "homepage"=>"0", "featured"=>"0", "magazine"=>"0", "refinery_category_ids"=>["1282"], "body"=>"Tests do a body good.", "custom_teaser"=>"", "draft"=>"0", "tag_list"=>"", "published_at(1i)"=>"2014", "published_at(2i)"=>"5", "published_at(3i)"=>"27", "published_at(4i)"=>"21", "published_at(5i)"=>"20", "custom_url"=>"", "source_url_title"=>"", "source_url"=>"", "user_id"=>"56", "browser_title"=>"", "meta_description"=>""}, "continue_editing"=>"false", "locale"=>:en}

You might find these useful too if you get an error:

app.cookies.to_hash
app.flash.to_hash
app.response # long, raw, HTML

Deleting array elements in JavaScript - delete vs splice

Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.

The following code will display "a", "b", "undefined", "d"

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Whereas this will display "a", "b", "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

How to dismiss ViewController in Swift?

Based on my experience, I add a method to dismiss me as extension to UIViewController:

extension UIViewController {
    func dismissMe(animated: Bool, completion: (()->())?) {
        var count = 0
        if let c = self.navigationController?.viewControllers.count {
            count = c
        }
        if count > 1 {
            self.navigationController?.popViewController(animated: animated)
            if let handler = completion {
                handler()
            }
        } else {
            dismiss(animated: animated, completion: completion)
        }
    }
}

Then I call this method to dismiss view controller in any UIViewController subclass. For example, in cancel action:

class MyViewController: UIViewController {
   ...
   @IBAction func cancel(sender: AnyObject) {
     dismissMe(animated: true, completion: nil)
   }
   ...
}

How to prevent custom views from losing state across screen orientation changes

You do this by implementing View#onSaveInstanceState and View#onRestoreInstanceState and extending the View.BaseSavedState class.

public class CustomView extends View {

  private int stateToSave;

  ...

  @Override
  public Parcelable onSaveInstanceState() {
    //begin boilerplate code that allows parent classes to save state
    Parcelable superState = super.onSaveInstanceState();

    SavedState ss = new SavedState(superState);
    //end

    ss.stateToSave = this.stateToSave;

    return ss;
  }

  @Override
  public void onRestoreInstanceState(Parcelable state) {
    //begin boilerplate code so parent classes can restore state
    if(!(state instanceof SavedState)) {
      super.onRestoreInstanceState(state);
      return;
    }

    SavedState ss = (SavedState)state;
    super.onRestoreInstanceState(ss.getSuperState());
    //end

    this.stateToSave = ss.stateToSave;
  }

  static class SavedState extends BaseSavedState {
    int stateToSave;

    SavedState(Parcelable superState) {
      super(superState);
    }

    private SavedState(Parcel in) {
      super(in);
      this.stateToSave = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
      super.writeToParcel(out, flags);
      out.writeInt(this.stateToSave);
    }

    //required field that makes Parcelables from a Parcel
    public static final Parcelable.Creator<SavedState> CREATOR =
        new Parcelable.Creator<SavedState>() {
          public SavedState createFromParcel(Parcel in) {
            return new SavedState(in);
          }
          public SavedState[] newArray(int size) {
            return new SavedState[size];
          }
    };
  }
}

The work is split between the View and the View's SavedState class. You should do all the work of reading and writing to and from the Parcel in the SavedState class. Then your View class can do the work of extracting the state members and doing the work necessary to get the class back to a valid state.

Notes: View#onSavedInstanceState and View#onRestoreInstanceState are called automatically for you if View#getId returns a value >= 0. This happens when you give it an id in xml or call setId manually. Otherwise you have to call View#onSaveInstanceState and write the Parcelable returned to the parcel you get in Activity#onSaveInstanceState to save the state and subsequently read it and pass it to View#onRestoreInstanceState from Activity#onRestoreInstanceState.

Another simple example of this is the CompoundButton

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Cannot find vcvarsall.bat when running a Python script

In case anyone comes here looking for an answer for Python 3.5; you need Visual Studio 2015.

Get Visual Studio 2015 Community here: https://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx, this worked for me with no further steps needed.

Many thanks to Ionel, apparently the only place on the web to find this information! http://blog.ionelmc.ro/2014/12/21/compiling-python-extensions-on-windows/

Python: print a generator expression?

Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:

def gen():
    x = 0
    while True:
        yield x
        x += 1
g1 = gen()
list(g1)   # never ends

Also, reading a generator changes it, so there's not a perfect way to view it. To see a sample of the generator's output, you could do

g1 = gen()
[g1.next() for i in range(10)]

Where does Oracle SQL Developer store connections?

With SQLDeveloper v19.1.0 on Windows, I found this as a JSON file in

C:\Users\<username>\AppData\Roaming\SQL Developer\system<versionNumber>\o.jdeveloper.db.connection

The file name is connections.json

How to get row from R data.frame

10 years later ---> Using tidyverse we could achieve this simply and borrowing a leaf from Christopher Bottoms. For a better grasp, see slice().

library(tidyverse)
x <- structure(list(A = c(5,    3.5, 3.25, 4.25,  1.5 ), 
                    B = c(4.25, 4,   4,    4.5,   4.5 ),
                    C = c(4.5,  2.5, 4,    2.25,  3   )
),
.Names    = c("A", "B", "C"),
class     = "data.frame",
row.names = c(NA, -5L)
)

x
#>      A    B    C
#> 1 5.00 4.25 4.50
#> 2 3.50 4.00 2.50
#> 3 3.25 4.00 4.00
#> 4 4.25 4.50 2.25
#> 5 1.50 4.50 3.00

y<-c(A=5, B=4.25, C=4.5)
y
#>    A    B    C 
#> 5.00 4.25 4.50

#The slice() verb allows one to subset data row-wise. 
x <- x %>% slice(1) #(n) for the nth row, or (i:n) for range i to n, (i:n()) for i to last row...

x
#>   A    B   C
#> 1 5 4.25 4.5

#Test that the items in the row match the vector you wanted
x[1,]==y
#>      A    B    C
#> 1 TRUE TRUE TRUE

Created on 2020-08-06 by the reprex package (v0.3.0)

Angular ng-if not true

In angular 1, you can use ng-show and ng-hide.In your case, you would use ng-hide. For example:

<li ng-hide="area"></li>

How can I bind a background color in WPF/XAML?

The Background property expects a Brush object, not a string. Change the type of the property to Brush and initialize it thus:

Background = new SolidColorBrush(Colors.Red);

Laravel - Return json along with http status code

I think it is better practice to keep your response under single control and for this reason I found out the most official solution.

response()->json([...])
    ->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);

add this after namespace declaration:

use Illuminate\Http\Response;

How to create range in Swift?

I want to do this:

print("Hello"[1...3])
// out: Error

But unfortunately, I can't write a subscript of my own because the loathed one takes up the name space.

We can do this however:

print("Hello"[range: 1...3])
// out: ell 

Just add this to your project:

extension String {
    subscript(range: ClosedRange<Int>) -> String {
        get {
            let start = String.Index(utf16Offset: range.lowerBound, in: self)
            let end = String.Index(utf16Offset: range.upperBound, in: self)
            return String(self[start...end])
        }
    }
}

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

There are two solutions to this:

a) Set your PATH variable to include "/usr/local/bin"

export PATH="$PATH:/usr/local/bin"

b) Create a symlink to "/usr/bin" which is already in your PATH

ln -s /usr/bin/nodejs /usr/bin/node

I hope it helps.

Remove all classes that begin with a certain string

An approach I would use using simple jQuery constructs and array handling functions, is to declare an function that takes id of the control and prefix of the class and deleted all classed. The code is attached:

function removeclasses(controlIndex,classPrefix){
    var classes = $("#"+controlIndex).attr("class").split(" ");
    $.each(classes,function(index) {
        if(classes[index].indexOf(classPrefix)==0) {
            $("#"+controlIndex).removeClass(classes[index]);
        }
    });
}

Now this function can be called from anywhere, onclick of button or from code:

removeclasses("a","bg");

Convert string to Color in C#

It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:

System.Windows.Media.Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("Red");//or hexadecimal color, e.g. #131A84

How can I make a horizontal ListView in Android?

You know, it might be possible to use an existing ListView with some judicious overriding of dispatchDraw() (to rotate the Canvas by 90 degrees), onTouch() (to swap the X and Y of the MotionEvent coords) and maybe onMeasure() or whatever to fool it into thinking it's y by x rather than x by y...

I have no idea if this would actually work but it'd be fun to find out. :)

Programmatically getting the MAC of an Android device

As was already pointed out in the comment, the MAC address can be received via the WifiManager.

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();

Also do not forget to add the appropriate permissions into your AndroidManifest.xml

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

Please refer to Android 6.0 Changes.

To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.

MySQL ORDER BY rand(), name ASC

Instead of using a subquery, you could use two separate queries, one to get the number of rows and the other to select the random rows.

SELECT COUNT(id) FROM users; #id is the primary key

Then, get a random twenty rows.

$start_row = mt_rand(0, $total_rows - 20);

The final query:

SELECT * FROM users ORDER BY name ASC LIMIT $start_row, 20;

How does one get started with procedural generation?

(More than 10 years later ...)

Procedural generation only means that code is used to generate the data instead of it being hand made. For example if you want to generate a forest with various trees you are not going to design each tree by hand, thus coding is more efficient to generate the variations. It could be the generation of the tree graphics, size, structure, placement ...

In general there is some kind of interation with a few rules, in addition to that you can add some randomness and logic of your own, combine all of these techniques ... Anything somewhat chaotic but not too chaotic can yield interesting results.

Here are a few notable techniques:

A few games famous for their procedural generation:

Video tutorial about Procedural Landmass Generation.

Conference on procedural content generation for games, has a lot of videos on the topic: everythingprocedural

Have fun.

PHP cURL, extract an XML response

no, CURL does not have anything with parsing XML, it does not know anything about the content returned. it serves as a proxy to get content. it's up to you what to do with it.

use JSON if possible (and json_decode) - it's easier to work with, if not possible, use any XML library for parsin such as DOMXML: http://php.net/domxml

jsPDF multi page PDF with HTML renderer

         html2canvas(element[0], {
                    onrendered: function (canvas) {
                        pages = Math.ceil(element[0].clientHeight / 1450);
                        for (i = 0; i <= pages; i += 1) {
                            if (i > 0) {
                                pdf.addPage();
                            }
                            srcImg = canvas;
                            sX = 0;
                            sY = 1450 * i;
                            sWidth = 1100;
                            sHeight = 1450;
                            dX = 0;
                            dY = 0;
                            dWidth = 1100;
                            dHeight = 1450;
                            window.onePageCanvas = document.createElement("canvas");
                            onePageCanvas.setAttribute('width', 1100);
                            onePageCanvas.setAttribute('height', 1450);
                            ctx = onePageCanvas.getContext('2d');
                            ctx.drawImage(srcImg, sX, sY, sWidth, sHeight, dX, dY, dWidth, dHeight);
                            canvasDataURL = onePageCanvas.toDataURL("image/png");
                            width = onePageCanvas.width;
                            height = onePageCanvas.clientHeight;
                            pdf.setPage(i + 1);
                            pdf.addImage(canvasDataURL, 'PNG', 35, 30, (width * 0.5), (height * 0.5));
                        }
                        pdf.save('testfilename.pdf');
                    }
                });

How to add and remove item from array in components in Vue 2

There are few mistakes you are doing:

  1. You need to add proper object in the array in addRow method
  2. You can use splice method to remove an element from an array at particular index.
  3. You need to pass the current row as prop to my-item component, where this can be modified.

You can see working code here.

addRow(){
   this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
   this. itemList.splice(index, 1)
}

How to access the first property of a Javascript object?

A one-rule version:

var val = example[function() { for (var k in example) return k }()];

How to implement a queue using two stacks?

Two stacks in the queue are defined as stack1 and stack2.

Enqueue: The euqueued elements are always pushed into stack1

Dequeue: The top of stack2 can be popped out since it is the first element inserted into queue when stack2 is not empty. When stack2 is empty, we pop all elements from stack1 and push them into stack2 one by one. The first element in a queue is pushed into the bottom of stack1. It can be popped out directly after popping and pushing operations since it is on the top of stack2.

The following is same C++ sample code:

template <typename T> class CQueue
{
public:
    CQueue(void);
    ~CQueue(void);

    void appendTail(const T& node); 
    T deleteHead();                 

private:
    stack<T> stack1;
    stack<T> stack2;
};

template<typename T> void CQueue<T>::appendTail(const T& element) {
    stack1.push(element);
} 

template<typename T> T CQueue<T>::deleteHead() {
    if(stack2.size()<= 0) {
        while(stack1.size()>0) {
            T& data = stack1.top();
            stack1.pop();
            stack2.push(data);
        }
    }


    if(stack2.size() == 0)
        throw new exception("queue is empty");


    T head = stack2.top();
    stack2.pop();


    return head;
}

This solution is borrowed from my blog. More detailed analysis with step-by-step operation simulations is available in my blog webpage.

Tomcat in Intellij Idea Community Edition

For Intellij 14.0.0 the Application server option is available under View > Tools window > Application Server (But if it is enable, i mean if you have any plugin installed)

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

Have you tried this http://tools.android.com/preview-channel ? Download preview channel. After that, install ADT Preview.

How can I test an AngularJS service from the console?

Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.

You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.

angular.element('*[ng-app]').injector()

In chrome, however, you can point to target ng-app as shown below. and use the $0 hack and issue angular.element($0).injector()

Once you have the injector, get any dependency injected service as below

injector = angular.element($0).injector();
injector.get('$mdToast');

enter image description here

Press Keyboard keys using a batch file

Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)

The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.

@if (@CodeSection == @Batch) @then


@echo off

rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem Start the other program in the same Window
start "" /B cmd

%SendKeys% "echo off{ENTER}"

set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"

set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"

set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"

%SendKeys% "exit{ENTER}"

goto :EOF


@end


// JScript section

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx

For example:

LEFT ARROW    {LEFT}
RIGHT ARROW   {RIGHT}

For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs

Find if variable is divisible by 2

var x = 2;
x % 2 ? oddFunction() : evenFunction();

How to decrease prod bundle size?

If you have run ng build --prod - you shouldn't have vendor files at all.

If I run just ng build - I get these files:

enter image description here

The total size of the folder is ~14MB. Waat! :D

But if I run ng build --prod - I get these files:

enter image description here

The total size of the folder is 584K.

One and the same code. I have enabled Ivy in both cases. Angular is 8.2.13.

So - I guess you didn't add --prod to your build command?

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

Check if string begins with something?

You can use string.match() and a regular expression for this too:

if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes

string.match() will return an array of matching substrings if found, otherwise null.

C++ IDE for Macs

Xcode is free and good, which is lucky because it's pretty much the only option on the Mac.

Django Cookies, how can I set them?

Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).

Setting a cookie:

def view(request):
  response = HttpResponse('blah')
  response.set_cookie('cookie_name', 'cookie_value')

Retrieving a cookie:

def view(request):
  value = request.COOKIES.get('cookie_name')
  if value is None:
    # Cookie is not set

  # OR

  try:
    value = request.COOKIES['cookie_name']
  except KeyError:
    # Cookie is not set

How can I access an internal class from an external assembly?

I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)] to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.

 Install-Package Mono.Cecil

And the code like:

static readonly string[] s_toInject = {
  // alternatively "MyAssembly, PublicKey=0024000004800000... etc."
  "MyAssembly"
};

static void Main(string[] args) {
  const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";

   var parameters = new ReaderParameters();
   var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
   foreach (var toInject in s_toInject) {
     var ca = new CustomAttribute(
       asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
                      typeof(string)})));
     ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
     asm.Assembly.CustomAttributes.Add(ca);
   }
   asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
   // note if the assembly is strongly-signed you need to resign it like
   // asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
   //   StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
   // });
}

How to toggle a boolean?

Let's see this in action:

_x000D_
_x000D_
var b = true;_x000D_
_x000D_
console.log(b); // true_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // false_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // true
_x000D_
_x000D_
_x000D_

Anyways, there is no shorter way than what you currently have.

How to print to stderr in Python?

I found this to be the only one short + flexible + portable + readable:

from __future__ import print_function
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

The function eprint can be used in the same way as the standard print function:

>>> print("Test")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz

Jenkins / Hudson environment variables

This is how I solved this annoying issue:

I changed the PATH variable as @sagar suggested in his 2nd option, but still I got different PATH value than I expected.

Eventually I found out that it was the EnvInject plugin that replaced my PATH variable!

So I could either uninstall EnvInject or just use it to inject the PATH variable.

As many of our Jenkins jobs use that plugin, I didn't want to uninstall it...

So I created a file: environment_variables.properties under my Jenkins home directory.

This file contained the path environment value that I needed: PATH=$PATH:/usr/local/git/bin/.

From the Jenkins web interface: Manage Jenkins -> Configure System. In that screen - I ticked the Prepare jobs environment option, and in the Properties File Path field I entered the path to my file: /var/lib/jenkins/environment_variables.properties.

This way every Jenkins job we have receive whatever variables I put in this environment_variables.properties file.

PHP unable to load php_curl.dll extension

Insert to file httpd.conf

LoadFile "D:/DevKit/PHP7.1/libeay32.dll"
LoadFile "D:/DevKit/PHP7.1/libssh2.dll"
LoadFile "D:/DevKit/PHP7.1/ssleay32.dll"

Get random item from array

Use PHP Rand function

<?php
  $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
  $rand_keys = array_rand($input, 2);
  echo $input[$rand_keys[0]] . "\n";
  echo $input[$rand_keys[1]] . "\n";
?>

More Help

What's the difference between a null pointer and a void pointer?

Usually a null pointer (which can be of any type, including a void pointer !) points to:

  • the address 0, against which most CPU instructions sets can do a very fast compare-and-branch (to check for uninitialized or invalid pointers, for instance) with optimal code size/performance for the ISA.

  • an address that's illegal for user code to access (such as 0x00000000 in many cases), so that if a code actually tries to access data at or near this address, the OS or debugger can easily stop or trap a program with this bug.

A void pointer is usually a method of cheating or turning-off compiler type checking, for instance if you want to return a pointer to one type, or an unknown type, to use as another type. For instance malloc() returns a void pointer to a type-less chunk of memory, the type of which you can cast to later use as a pointer to bytes, short ints, double floats, typePotato's, or whatever.

Multiple github accounts on the same computer?

You should and must not push to the project with some common credentials. Once starting on a new machine use the following steps to setup and use correctly your gitlab credentials:

  • create the pubic / private ssh keys on the machine
  • copy paste the public key to the gitlab/github ui interface ( anyone hinting how-to do via the cmd line gets a free beer ... )
  • make sure you clone the repo via the git and not http url
  • set the git alias to avoid constant typing of the same prefix to the git command
  • during git commit ALWAYS use the author and e-mail flags
  • use git as normal you would do it

All this as follows:

 # create the public / private key credentials on that specific machine
 ssh-keygen -t rsa -b 4096 -C "<<you>>@org.net" -f ~/.ssh/id_rsa.<<you>>.`hostname -s`

 # setup your public key in the gitlab ui 
 cat ~/.ssh/id_rsa.<<you>>.`hostname -s`

 # make sure you clone the repo via the git and not http url
 git clone [email protected]:org/some-repo.git

 # set the git alias to avoid constant typing of the repeating prefix to the git cmd
 alias git='GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa.<<you>>.`hostname -s`" git'

 # during git commit ALWAYS use the author and e-mail flags
 git add --all ; git commit -nm "$git_msg" --author "YourFirstName YourLastName <[email protected]>"

 # use git as normal
 git fetch --all; git pull --all 

How to write a foreach in SQL Server?

The following line is wrong in your version:

WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))

(Missing the @)

Might be an idea to change your naming convention so that the tables are more different.

MVC Razor view nested foreach's model

It is clear from the error.

The HtmlHelpers appended with "For" expects lambda expression as a parameter.

If you are passing the value directly, better use Normal one.

e.g.

Instead of TextboxFor(....) use Textbox()

syntax for TextboxFor will be like Html.TextBoxFor(m=>m.Property)

In your scenario you can use basic for loop, as it will give you index to use.

@for(int i=0;i<Model.Theme.Count;i++)
 {
   @Html.LabelFor(m=>m.Theme[i].name)
   @for(int j=0;j<Model.Theme[i].Products.Count;j++) )
     {
      @Html.LabelFor(m=>m.Theme[i].Products[j].name)
      @for(int k=0;k<Model.Theme[i].Products[j].Orders.Count;k++)
          {
           @Html.TextBoxFor(m=>Model.Theme[i].Products[j].Orders[k].Quantity)
           @Html.TextAreaFor(m=>Model.Theme[i].Products[j].Orders[k].Note)
           @Html.EditorFor(m=>Model.Theme[i].Products[j].Orders[k].DateRequestedDeliveryFor)
      }
   }
}

Is there a goto statement in Java?

So they could be used one day if the language designers felt the need.

Also, if programmers from languages that do have these keywords (eg. C, C++) use them by mistake, then the Java compiler can give a useful error message.

Or maybe it was just to stop programmers using goto :)

How do you build a Singleton in Dart?

Singleton that can't change the object after the instantiation

class User {
  final int age;
  final String name;
  
  User({
    this.name,
    this.age
    });
  
  static User _instance;
  
  static User getInstance({name, age}) {
     if(_instance == null) {
       _instance = User(name: name, age: age);
       return _instance;
     }
    return _instance;
  }
}

  print(User.getInstance(name: "baidu", age: 24).age); //24
  
  print(User.getInstance(name: "baidu 2").name); // is not changed //baidu

  print(User.getInstance()); // {name: "baidu": age 24}

How to prevent form from being submitted?

var form = document.getElementById("idOfForm");
form.onsubmit = function() {
  return false;
}

Count number of rows per group and add result to original data frame

You can do this:

> ddply(df,.(name,type),transform,count = NROW(piece))
   name  type num count
1 black chair   4     2
2 black chair   5     2
3 black  sofa  12     1
4   red plate   3     1
5   red  sofa   4     1

or perhaps more intuitively,

> ddply(df,.(name,type),transform,count = length(num))
   name  type num count
1 black chair   4     2
2 black chair   5     2
3 black  sofa  12     1
4   red plate   3     1
5   red  sofa   4     1

In C#, how to check whether a string contains an integer?

Maybe this can help

string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));

answer from msdn.

Python executable not finding libpython shared library

This answer would be helpful to those who have limited auth access on the server.

I had a similar problem for python3.5 in HostGator's shared hosting. Python3.5 had to be enabled every single damn time after login. Here are my 10 steps for resolution:

  1. Enable the python through scl script python_enable_3.5 or scl enable rh-python35 bash.

  2. Verify that it's enabled by executing python3.5 --version. This should give you your python version.

  3. Execute which python3.5 to get its path. In my case, it was /opt/rh/rh-python35/root/usr/bin/python3.5. You can use this path get the version again (just to verify that this path is working for you.)

  4. Awesome, now please exit out of current shell by scl.

  5. Now, lets get the version again through this complete python3.5 path /opt/rh/rh-python35/root/usr/bin/python3.5 --version.

    It won't give you the version but an error. In my case, it was

/opt/rh/rh-python35/root/usr/bin/python3.5: error while loading shared libraries: libpython3.5m.so.rh-python35-1.0: cannot open shared object file: No such file or directory
  1. As mentioned in Tamas' answer, we gotta find that so file. locate doesn't work in shared hosting and you can't install that too.

    Use the following command to find where that file is located:

find /opt/rh/rh-python35 -name "libpython3.5m.so.rh-python35-1.0"
  1. Above command would print the complete path (second line) of the file once located. In my case, output was
find: `/opt/rh/rh-python35/root/root': Permission denied
/opt/rh/rh-python35/root/usr/lib64/libpython3.5m.so.rh-python35-1.0
  1. Here is the complete command for the python3.5 to work in such shared hosting which would give the version,
LD_LIBRARY_PATH=/opt/rh/rh-python35/root/usr/lib64 /opt/rh/rh-python35/root/usr/bin/python3.5 --version
  1. Finally, for shorthand, append the following alias in your ~/.bashrc
alias python351='LD_LIBRARY_PATH=/opt/rh/rh-python35/root/usr/lib64 /opt/rh/rh-python35/root/usr/bin/python3.5'
  1. For verification, reload the .bashrc by source ~/.bashrc and execute python351 --version.

Well, there you go, now whenever you login again, you have got python351 to welcome you.

This is not just limited to python3.5, but can be helpful in case of other scl installed softwares.

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

In CSS what is the difference between "." and "#" when declaring a set of styles?

The # is an id selector. It matches only elements with a matching id. Next style rule will match the element that has an id attribute with a value of "green":

#green {color: green}

See http://www.w3schools.com/css/css_syntax.asp for more information

How to use a filter in a controller?

There are three possible ways to do this.

Let's assume you have the following simple filter, which converts a string to uppercase, with a parameter for the first character only.

app.filter('uppercase', function() {
    return function(string, firstCharOnly) {
        return (!firstCharOnly)
            ? string.toUpperCase()
            : string.charAt(0).toUpperCase() + string.slice(1);
    }
});

Directly through $filter

app.controller('MyController', function($filter) {

    // HELLO
    var text = $filter('uppercase')('hello');

    // Hello
    var text = $filter('uppercase')('hello', true);

});

Note: this gives you access to all your filters.


Assign $filter to a variable

This option allows you to use the $filter like a function.

app.controller('MyController', function($filter) {

    var uppercaseFilter = $filter('uppercase');

    // HELLO
    var text = uppercaseFilter('hello');

    // Hello
    var text = uppercaseFilter('hello', true);

});

Load only a specific Filter

You can load only a specific filter by appending the filter name with Filter.

app.controller('MyController', function(uppercaseFilter) {

    // HELLO
    var text = uppercaseFilter('hello');

    // Hello
    var text = uppercaseFilter('hello', true);

});

Which one you use comes to personal preference, but I recommend using the third, because it's the most readable option.

Create PostgreSQL ROLE (user) if it doesn't exist

Some answers suggested to use pattern: check if role does not exist and if not then issue CREATE ROLE command. This has one disadvantage: race condition. If somebody else creates a new role between check and issuing CREATE ROLE command then CREATE ROLE obviously fails with fatal error.

To solve above problem, more other answers already mentioned usage of PL/pgSQL, issuing CREATE ROLE unconditionally and then catching exceptions from that call. There is just one problem with these solutions. They silently drop any errors, including those which are not generated by fact that role already exists. CREATE ROLE can throw also other errors and simulation IF NOT EXISTS should silence only error when role already exists.

CREATE ROLE throw duplicate_object error when role already exists. And exception handler should catch only this one error. As other answers mentioned it is a good idea to convert fatal error to simple notice. Other PostgreSQL IF NOT EXISTS commands adds , skipping into their message, so for consistency I'm adding it here too.

Here is full SQL code for simulation of CREATE ROLE IF NOT EXISTS with correct exception and sqlstate propagation:

DO $$
BEGIN
CREATE ROLE test;
EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
END
$$;

Test output (called two times via DO and then directly):

$ sudo -u postgres psql
psql (9.6.12)
Type "help" for help.

postgres=# \set ON_ERROR_STOP on
postgres=# \set VERBOSITY verbose
postgres=# 
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
DO
postgres=# 
postgres=# DO $$
postgres$# BEGIN
postgres$# CREATE ROLE test;
postgres$# EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
postgres$# END
postgres$# $$;
NOTICE:  42710: role "test" already exists, skipping
LOCATION:  exec_stmt_raise, pl_exec.c:3165
DO
postgres=# 
postgres=# CREATE ROLE test;
ERROR:  42710: role "test" already exists
LOCATION:  CreateRole, user.c:337

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

Remove all whitespaces from NSString

I strongly suggest placing this somewhere in your project:

extension String {
    func trim() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }

    func trim(withSet: NSCharacterSet) -> String {
        return self.stringByTrimmingCharactersInSet(withSet)
    }
}

Where do I find the bashrc file on Mac?

I would think you should add it to ~/.bash_profile instead of .bashrc, (creating .bash_profile if it doesn't exist.) Then you don't have to add the extra step of checking for ~/.bashrc in your .bash_profile

Are you comfortable working and editing in a terminal? Just in case, ~/ means your home directory, so if you open a new terminal window that is where you will be "located". And the dot at the front makes the file invisible to normal ls command, unless you put -a or specify the file name.

Check this answer for more detail.

How to read attribute value from XmlNode in C#?

If you use chldNode as XmlElement instead of XmlNode, you can use

var attributeValue = chldNode.GetAttribute("Name");

The return value will just be an empty string, in case the attribute name does not exist.

So your loop could look like this:

XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");

foreach (XmlElement node in nodes)
{
    var attributeValue = node.GetAttribute("Name");
}

This will select all nodes <node> surrounded by <Node><N0de></N0de><Node> tags and subsequently loop through them and read the attribute "Name".

How do I set the default value for an optional argument in Javascript?

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

First go to Wamp->Apache->Service->Test Port 80

If its being user by Microsoft HTTPAPI / 2.0

Then the solution is to manually stop the service named web deployment agent service

If you have Microsoft Sql Server installed, even though the IIS service is disabled, it keeps a web service named httpapi2.0 running.

How can I get my Android device country code without using GPS?

Use the link http://ip-api.com/json. This will provide all the information as JSON. From this JSON content you can get the country easily. This site works using your current IP address. It automatically detects the IP address and sendback details.

Documentation

This is what I got:

{
"as": "AS55410 C48 Okhla Industrial Estate, New Delhi-110020",
"city": "Kochi",
"country": "India",
"countryCode": "IN",
"isp": "Vodafone India",
"lat": 9.9667,
"lon": 76.2333,
"org": "Vodafone India",
"query": "123.63.81.162",
"region": "KL",
"regionName": "Kerala",
"status": "success",
"timezone": "Asia/Kolkata",
"zip": ""
}

N.B. - As this is a third-party API, do not use it as the primary solution. And also I am not sure whether it's free or not.

htaccess "order" Deny, Allow, Deny

As Gerben suggested, just change:

order deny,allow
deny from all

to

order allow,deny

And the restrictions will work as you want them to.

Details can be found in Apache's docs.

how to customise input field width in bootstrap 3

i solved with a max-width in my main css-file.

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

It's a simple solution with little "code"

Get generic type of java.util.List

Short answer: no.

This is probably a duplicate, can't find an appropriate one right now.

Java uses something called type erasure, which means at runtime both objects are equivalent. The compiler knows the lists contain integers or strings, and as such can maintain a type safe environment. This information is lost (on an object instance basis) at runtime, and the list only contain 'Objects'.

You CAN find out a little about the class, what types it might be parametrized by, but normally this is just anything that extends "Object", i.e. anything. If you define a type as

class <A extends MyClass> AClass {....}

AClass.class will only contain the fact that the parameter A is bounded by MyClass, but more than that, there's no way to tell.

The module was expected to contain an assembly manifest

Check if the manifest is a valid xml file. I had the same problem by doing a DOS copy command at the end of the build, and it turns out that for some reason I can not understand "copy" was adding a strange character (->) at the end of the manifest files. The problem was solved by adding "/b" switch to force binary copy.

How do you clear the SQL Server transaction log?

First check the database recovery model. By default, SQL Server Express Edition creates a database for the simple recovery model (if I am not mistaken).

Backup log DatabaseName With Truncate_Only:

DBCC ShrinkFile(yourLogical_LogFileName, 50)

SP_helpfile will give you the logical log file name.

Refer to:

Recover from a full transaction log in a SQL Server database

If your database is in Full Recovery Model and if you are not taking TL backup, then change it to SIMPLE.

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

When we use CommandObj.Parameter.Add() it takes 2 parameters, the first is procedure parameter and the second is its data type, while .AddWithValue() takes 2 parameters, the first is procedure parameter and the second is the data variable

CommandObj.Parameter.Add("@ID",SqlDbType.Int).Value=textBox1.Text;

for .AddWithValue

CommandObj.Parameter.AddWitheValue("@ID",textBox1.Text);

where ID is the parameter of stored procedure which data type is Int

How to get a jqGrid selected row cells value

yo have to declarate de vars...

var selectedRowId = $('#list').jqGrid ('getGridParam', 'selrow');
var columnName = $('#list').jqGrid('getCell', selectedRowId, 'columnName');

var nombre_img_articulo = $('#list').jqGrid('getCell', selectedRowId, 'img_articulo');

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

Another alternative would be to set environment variable ANDROID_SERIAL to the relevant serial, here assuming you are using Windows:

set ANDROID_SERIAL=7f1c864e
echo %ANDROID_SERIAL%
"7f1c864e"

Then you can use adb.exe shell without any issues.

top nav bar blocking top content of the page

As seen on this example from Twitter, add this before the line that includes the responsive styles declarations:

<style> 
    body {
        padding-top: 60px;
    }
</style>

Like so:

<link href="Z/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
    body {
        padding-top: 60px;
    }
</style>
<link href="Z/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Why should hash functions use a prime number modulus?

I would say the first answer at this link is the clearest answer I found regarding this question.

Consider the set of keys K = {0,1,...,100} and a hash table where the number of buckets is m = 12. Since 3 is a factor of 12, the keys that are multiples of 3 will be hashed to buckets that are multiples of 3:

  • Keys {0,12,24,36,...} will be hashed to bucket 0.
  • Keys {3,15,27,39,...} will be hashed to bucket 3.
  • Keys {6,18,30,42,...} will be hashed to bucket 6.
  • Keys {9,21,33,45,...} will be hashed to bucket 9.

If K is uniformly distributed (i.e., every key in K is equally likely to occur), then the choice of m is not so critical. But, what happens if K is not uniformly distributed? Imagine that the keys that are most likely to occur are the multiples of 3. In this case, all of the buckets that are not multiples of 3 will be empty with high probability (which is really bad in terms of hash table performance).

This situation is more common that it may seem. Imagine, for instance, that you are keeping track of objects based on where they are stored in memory. If your computer's word size is four bytes, then you will be hashing keys that are multiples of 4. Needless to say that choosing m to be a multiple of 4 would be a terrible choice: you would have 3m/4 buckets completely empty, and all of your keys colliding in the remaining m/4 buckets.

In general:

Every key in K that shares a common factor with the number of buckets m will be hashed to a bucket that is a multiple of this factor.

Therefore, to minimize collisions, it is important to reduce the number of common factors between m and the elements of K. How can this be achieved? By choosing m to be a number that has very few factors: a prime number.

FROM THE ANSWER BY Mario.

How to change an application icon programmatically in Android?

As mentioned before you need use <activity-alias> to change the application icon. To avoid killing the application after enabling appropriate activity-alias you need to do this after the application is killed. To find out if the application was killed you can use this method

  1. Create activity aliases in AndroidManifest.xml
<activity android:name=".ui.MainActivity"/>

<activity-alias
    android:name=".one"
    android:icon="@mipmap/ic_launcher_one"
    android:targetActivity=".ui.MainActivity"
    android:enabled="true">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>

<activity-alias
    android:name=".two"
    android:icon="@mipmap/ic_launcher_two"
    android:targetActivity=".ui.MainActivity"
    android:enabled="false">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>
  1. ?reate a service that will change the active activity-alias after killing the application. You need store the name of new active activity-alias somewhere (e.g. SharedPreferences)
class ChangeAppIconService: Service() {
    private val aliases = arrayOf(".one", ".two")

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onTaskRemoved(rootIntent: Intent?) {
        changeAppIcon()
        stopSelf()
    }

    fun changeAppIcon() {
        val sp = getSharedPreferences("appSettings", Context.MODE_PRIVATE)

        sp.getString("activeActivityAlias", ".one").let { aliasName ->
            if (!isAliasEnabled(aliasName)) {
                setAliasEnabled(aliasName)
            }
        }
    }

    private fun isAliasEnabled(aliasName: String): Boolean {
        return packageManager.getComponentEnabledSetting(
            ComponentName(
                this,
                "${BuildConfig.APPLICATION_ID}$aliasName"
            )
        ) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
    }

    private fun setAliasEnabled(aliasName: String) {
        aliases.forEach {
            val action = if (it == aliasName)
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            else
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                
            packageManager.setComponentEnabledSetting(
                ComponentName(
                    this,
                    "${BuildConfig.APPLICATION_ID}$aliasName"
                ),
                action,
                PackageManager.DONT_KILL_APP
            )
        }
    }
}
  1. Add service to AndroidManifest.xml
<service 
    android:name=".ChangeAppIconService"
    android:stopWithTask="false"
    />
  1. Start ChangeAppIconService in MainActivity.onCreate
class MainActivity: Activity {

    ...

    override fun onCreate(savedInstanceState: Bundle?) {
       ...

       startService(Intent(this, ChangeAppIconService::class.java))

       ...
    }

    ...

}

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

The 'Continue' button is under the error message. Just hit 'Enter'

You should confirm that the device was listed on my 'Managed Devices' on Apple @ https://appleid.apple.com/account/manage

SQL conditional SELECT

In SQL, you do it this way:

SELECT  CASE WHEN @selectField1 = 1 THEN Field1 ELSE NULL END,
        CASE WHEN @selectField2 = 1 THEN Field2 ELSE NULL END
FROM    Table

Relational model does not imply dynamic field count.

Instead, if you are not interested in a field value, you just select a NULL instead and parse it on the client.

react-router scroll to top on every transition

If you are running React 16.8+ this is straightforward to handle with a component that will scroll the window up on every navigation:
Here is in scrollToTop.js component

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

Then render it at the top of your app, but below Router
Here is in app.js

import ScrollToTop from "./scrollToTop";

function App() {
  return (
    <Router>
      <ScrollToTop />
      <App />
    </Router>
  );
}

or in index.js

import ScrollToTop from "./scrollToTop";

ReactDOM.render(
    <BrowserRouter>
        <ScrollToTop />
        <App />
    </BrowserRouter>
    document.getElementById("root")
);

NodeJS w/Express Error: Cannot GET /

You need to restart the process if app.get not working. Press ctl+c and then restart node app.

Converting Pandas dataframe into Spark dataframe error

I received a similar error message once, in my case it was because my pandas dataframe contained NULLs. I will recommend to try & handle this in pandas before converting to spark (this resolved the issue in my case).

javascript: calculate x% of a number

Your percentage divided by 100 (to get the percentage between 0 and 1) times by the number

35.8/100*10000

What's the meaning of exception code "EXC_I386_GPFLT"?

In my case EXC_I386_GPFLT was caused by missing return value in the property getter. Like this:

- (CppStructure)cppStructure
{
    CppStructure data;
    data.a = self.alpha;
    data.b = self.beta;

    return data; // this line was missing
}

Xcode 12.2

TypeError: not all arguments converted during string formatting python

There is a combination of issues as pointed out in a few of the other answers.

  1. As pointed out by nneonneo you are mixing different String Formatting methods.
  2. As pointed out by GuyP your indentation is off as well.

I've provided both the example of .format as well as passing tuples to the argument specifier of %s. In both cases the indentation has been fixed so greater/less than checks are outside of when length matches. Also changed subsequent if statements to elif's so they only run if the prior same level statement was False.

String Formatting with .format

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
    print ("{0} is longer than {1}".format(name2, name1))

String Formatting with %s and a tuple

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("%s is longer than %s" % (name1, name2))
elif len(name1) < len(name2):
    print ("%s is longer than %s" % (name2, name1))

How to Replace dot (.) in a string in Java

return sentence.replaceAll("\s",".");

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

How do I select which GPU to run a job on?

The problem was caused by not setting the CUDA_VISIBLE_DEVICES variable within the shell correctly.

To specify CUDA device 1 for example, you would set the CUDA_VISIBLE_DEVICES using

export CUDA_VISIBLE_DEVICES=1

or

CUDA_VISIBLE_DEVICES=1 ./cuda_executable

The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.

If you want to specify more than one device, use

export CUDA_VISIBLE_DEVICES=0,1

or

CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable

Using sed to mass rename files

I wrote a small post with examples on batch renaming using sed couple of years ago:

http://www.guyrutenberg.com/2009/01/12/batch-renaming-using-sed/

For example:

for i in *; do
  mv "$i" "`echo $i | sed "s/regex/replace_text/"`";
done

If the regex contains groups (e.g. \(subregex\) then you can use them in the replacement text as \1\,\2 etc.

Standardize data columns in R

Use the package "recommenderlab". Download and install the package. This package has a command "Normalize" in built. It also allows you to choose one of the many methods for normalization namely 'center' or 'Z-score' Follow the following example:

## create a matrix with ratings
m <- matrix(sample(c(NA,0:5),50, replace=TRUE, prob=c(.5,rep(.5/6,6))),nrow=5, ncol=10, dimnames = list(users=paste('u', 1:5, sep=&rdquo;), items=paste('i', 1:10, sep=&rdquo;)))

## do normalization
r <- as(m, "realRatingMatrix")
#here, 'centre' is the default method
r_n1 <- normalize(r) 
#here "Z-score" is the used method used
r_n2 <- normalize(r, method="Z-score")

r
r_n1
r_n2

## show normalized data
image(r, main="Raw Data")
image(r_n1, main="Centered")
image(r_n2, main="Z-Score Normalization")

Have bash script answer interactive prompts

I found the best way to send input is to use cat and a text file to pass along whatever input you need.

cat "input.txt" | ./Script.sh

How to add app icon within phonegap projects?

in some cases the internal skripts of cordova don´t put the icons in the right folder, therfore you can see the f*** cordova robot instead of your own icon.

Make use of hook script.;)

three-hooks-your-cordovaphonegap-project-needs

Create a folder "after_platform_add" in the hook folder and put/change the last skript from devgirl.

Don´t forget to set executive rights for the script, in linux "chmod 777 <script>"

good luck!

How do you check if a string is not equal to an object or other string value in java?

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

removing bold styling from part of a header

<ul>
    <li><strong>This text will be bold.</strong>This text will NOT be bold.
    </li>
</ul>

How can I split a text file using PowerShell?

There's also this quick (and somewhat dirty) one-liner:

$linecount=0; $i=0; Get-Content .\BIG_LOG_FILE.txt | %{ Add-Content OUT$i.log "$_"; $linecount++; if ($linecount -eq 3000) {$I++; $linecount=0 } }

You can tweak the number of first lines per batch by changing the hard-coded 3000 value.

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

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

What is parsing in terms that a new programmer would understand?

Parsing is the process of analyzing text made of a sequence of tokens to determine its grammatical structure with respect to a given (more or less) formal grammar.

The parser then builds a data structure based on the tokens. This data structure can then be used by a compiler, interpreter or translator to create an executable program or library.

alt text
(source: wikimedia.org)

If I gave you an english sentence, and asked you to break down the sentence into its parts of speech (nouns, verbs, etc.), you would be parsing the sentence.

That's the simplest explanation of parsing I can think of.

That said, parsing is a non-trivial computational problem. You have to start with simple examples, and work your way up to the more complex.

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Change Circle color of radio button

For under API 21

Create custom style RadioButton style.xml

 <style name="RadioButton" parent="Theme.AppCompat.Light">
     <item name="colorAccent">@color/green</item>
     <item name="android:textColorSecondary">@color/mediumGray</item>
     <item name="colorControlNormal">@color/red</item>
 </style>

In layout use theme:

<RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:theme="@style/RadioButton" />

For API 21 and more

Just use buttonTint

 <RadioButton
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:buttonTint="@color/green" />

javax.faces.application.ViewExpiredException: View could not be restored

I ran into this problem myself and realized that it was because of a side-effect of a Filter that I created which was filtering all requests on the appliation. As soon as I modified the filter to pick only certain requests, this problem did not occur. It maybe good to check for such filters in your application and see how they behave.

Why Maven uses JDK 1.6 but my java -version is 1.7

add the following to your ~/.mavenrc:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/{jdk-version}/Contents/Home

Second Solution:

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile

How to run multiple DOS commands in parallel?

You can execute commands in parallel with start like this:

start "" ping myserver
start "" nslookup myserver
start "" morecommands

They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.

Hope this helps!

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

I did all of them but didn't work, I find out should stop php artisan serve(Ctrl + C) and start php artisan serve again.

How to change node.js's console font color?

var colorSet = {
    Reset: "\x1b[0m",
    Red: "\x1b[31m",
    Green: "\x1b[32m",
    Yellow: "\x1b[33m",
    Blue: "\x1b[34m",
    Magenta: "\x1b[35m"
};

var funcNames = ["info", "log", "warn", "error"];
var colors = [colorSet.Green, colorSet.Blue, colorSet.Yellow, colorSet.Red];

for (var i = 0; i < funcNames.length; i++) {
    let funcName = funcNames[i];
    let color = colors[i];
    let oldFunc = console[funcName];
    console[funcName] = function () {
        var args = Array.prototype.slice.call(arguments);
        if (args.length) {
            args = [color + args[0]].concat(args.slice(1), colorSet.Reset);
        }
        oldFunc.apply(null, args);
    };
}

// Test:
console.info("Info is green.");
console.log("Log is blue.");
console.warn("Warn is orange.");
console.error("Error is red.");
console.info("--------------------");
console.info("Formatting works as well. The number = %d", 123);

Merge or combine by rownames

Using merge and renaming your t vector as tt (see the PS of Andrie) :

merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]

Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :

z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Documentation for crypto: http://nodejs.org/api/crypto.html

const crypto = require('crypto')

const text = 'I love cupcakes'
const key = 'abcdeg'

crypto.createHmac('sha1', key)
  .update(text)
  .digest('hex')

Does C# support multiple inheritance?

Multiple inheritance is not supported in C#.

But if you want to "inherit" behavior from two sources why not use the combination of:

  • Composition
  • Dependency Injection

There is a basic but important OOP principle that says: "Favor composition over inheritance".

You can create a class like this:

public class MySuperClass
{
    private IDependencyClass1 mDependency1;
    private IDependencyClass2 mDependency2;

    public MySuperClass(IDependencyClass1 dep1, IDependencyClass2 dep2)
    {
        mDependency1 = dep1;
        mDependency2 = dep2;
    }

    private void MySuperMethodThatDoesSomethingComplex()
    {
        string s = mDependency1.GetMessage();
        mDependency2.PrintMessage(s);
    }
}

As you can see the dependecies (actual implementations of the interfaces) are injected via the constructor. You class does not know how each class is implemented but it knows how to use them. Hence, a loose coupling between the classes involved here but the same power of usage.

Today's trends show that inheritance is kind of "out of fashion".

How to compare two strings are equal in value, what is the best method?

You can either use the == operator or the Object.equals(Object) method.

The == operator checks whether the two subjects are the same object, whereas the equals method checks for equal contents (length and characters).

if(objectA == objectB) {
   // objects are the same instance. i.e. compare two memory addresses against each other.
}

if(objectA.equals(objectB)) {
   // objects have the same contents. i.e. compare all characters to each other 
}

Which you choose depends on your logic - use == if you can and equals if you do not care about performance, it is quite fast anyhow.

String.intern() If you have two strings, you can internate them, i.e. make the JVM create a String pool and returning to you the instance equal to the pool instance (by calling String.intern()). This means that if you have two Strings, you can call String.intern() on both and then use the == operator. String.intern() is however expensive, and should only be used as an optimalization - it only pays off for multiple comparisons.

All in-code Strings are however already internated, so if you are not creating new Strings, you are free to use the == operator. In general, you are pretty safe (and fast) with

if(objectA == objectB || objectA.equals(objectB)) {

}

if you have a mix of the two scenarios. The inline

if(objectA == null ? objectB == null : objectA.equals(objectB)) {

}

can also be quite useful, it also handles null values since String.equals(..) checks for null.

C/C++ line number

Since i'm also facing this problem now and i cannot add an answer to a different but also valid question asked here, i'll provide an example solution for the problem of: getting only the line number of where the function has been called in C++ using templates.

Background: in C++ one can use non-type integer values as a template argument. This is different than the typical usage of data types as template arguments. So the idea is to use such integer values for a function call.

#include <iostream>

class Test{
    public:
        template<unsigned int L>
        int test(){
            std::cout << "the function has been called at line number: " << L << std::endl;
            return 0;
        }
        int test(){ return this->test<0>(); }
};

int main(int argc, char **argv){
    Test t;
    t.test();
    t.test<__LINE__>();
    return 0;
}

Output:

the function has been called at line number: 0

the function has been called at line number: 16

One thing to mention here is that in C++11 Standard it's possible to give default template values for functions using template. In pre C++11 default values for non-type arguments seem to only work for class template arguments. Thus, in C++11, there would be no need to have duplicate function definitions as above. In C++11 its also valid to have const char* template arguments but its not possible to use them with literals like __FILE__ or __func__ as mentioned here.

So in the end if you're using C++ or C++11 this might be a very interesting alternative than using macro's to get the calling line.

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();

Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?

Bootstrap close responsive menu "on click"

If for example your toggle-able icon is visible only for extra small devices, then you could do something like this:

$('[data-toggle="offcanvas"]').click(function () {
    $('#side-menu').toggleClass('hidden-xs');
});

Clicking [data-toggle="offcanvas"] will add bootstrap's .hidden-xs to my #side-menu which will hide the side-menu content, but will become visible again if you increase the window size.

Using BigDecimal to work with currencies

Here are a few hints:

  1. Use BigDecimal for computations if you need the precision that it offers (Money values often need this).
  2. Use the NumberFormat class for display. This class will take care of localization issues for amounts in different currencies. However, it will take in only primitives; therefore, if you can accept the small change in accuracy due to transformation to a double, you could use this class.
  3. When using the NumberFormat class, use the scale() method on the BigDecimal instance to set the precision and the rounding method.

PS: In case you were wondering, BigDecimal is always better than double, when you have to represent money values in Java.

PPS:

Creating BigDecimal instances

This is fairly simple since BigDecimal provides constructors to take in primitive values, and String objects. You could use those, preferably the one taking the String object. For example,

BigDecimal modelVal = new BigDecimal("24.455");
BigDecimal displayVal = modelVal.setScale(2, RoundingMode.HALF_EVEN);

Displaying BigDecimal instances

You could use the setMinimumFractionDigits and setMaximumFractionDigits method calls to restrict the amount of data being displayed.

NumberFormat usdCostFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdCostFormat.setMinimumFractionDigits( 1 );
usdCostFormat.setMaximumFractionDigits( 2 );
System.out.println( usdCostFormat.format(displayVal.doubleValue()) );

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I have faced same problem since I have updated the latest react version. Solved like below.

My code was

async componentDidMount() {
  const { default: Component } = await importComponent();
  Nprogress.done();
  this.setState({
    component: <Component {...this.props} />
  });
}

Changed to

componentWillUnmount() {
  this.mounted = false;
}
async componentDidMount() {
  this.mounted = true;
  const { default: Component } = await importComponent();
  if (this.mounted) {
    this.setState({
      component: <Component {...this.props} />
    });
  }
}

How to analyze a JMeter summary report?

There are lots of explanation of Jmeter Summary, I have been using this tool from quite some time for generating performance testing report with relevant data. The explanation available on below link is right from the field experience:

Jmeter:Understanding Summary Report

This is one of the most useful report generated by Jmeter to undertstand the load test result.

# Label: Name of HTTP sample request send to server

# Samples : This Captures the total number of samples pushed to server. Suppose you put a Loop Controller to run it 5 times this particular request and then 2 iteration(Called Loop Count in Thread Group)is set and load test is run for 100 users, then the count that will be displayed here .... 1*5*2 * 100 =1000. Total = total number of samples send to server during entire run.

# Average : It's an average response time for a particular http request. This response time is in millisecond, and an average for 5 loops in two iteration for 100 users. Total = Average of total average of samples, means add all averages for all samples and divide by number of samples

# Min : Minmum time spend by sample requests send for this label. The total equals to the minimum time across all samples.

# Max : Maximum tie spend by sample requests send for this label The total equals to the maxmimum time across all samples.

# Std. Dev. : Knowing the standard deviation of your data set tells you how densely the data points are clustered around the mean. The smaller the standard deviation, the more consistent the data. Standard deviation should be less than or equal to half of the average time for a label. If it is more than that, then it means that something is wrong. you need to figure out the problem and fix it. https://en.wikipedia.org/wiki/Standard_deviation Total is euqals to highest deviation across all samples.

# Error: Total percentage of erros found for a particular sample request. 0.0% shows that all requests completed successfully. Total equals to percentage of errors samples in all samples (Total Samples)

# Throughput: Hits/sec, or total number of request per unit of time(sec, mins, hr) send to server during test.

endTime = lastSampleStartTime + lastSampleLoadTime
startTime = firstSampleStartTime
converstion = unit time conversion value
Throughput = Numrequests / ((endTime - startTime)*conversion)

# KB/sec : Its mesuring throughput rate in Kilobytes per second.

# Avg. Bytes: Avegare of total bytes of data downloaded from server. Totals is average bytes across all samples.

How do I insert an image in an activity with android studio?

I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below

enter image description here


Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.

enter image description here

It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below

enter image description here

Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/homepage"
        tools:layout_editor_absoluteX="55dp"
        tools:layout_editor_absoluteY="130dp" />

You need to give image location using

app:srcCompat="@drawable/imagename"

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

Turn a single number into single digits Python

Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n first):

>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]

Updating this after many years in response to comments of this not working for powers of 10:

[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]

The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.

In [32]: n = 43

In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]

In [34]: n = 1000

In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]

Regex for empty string or white space

The \ (backslash) in the .match call is not properly escaped. It would be easier to use a regex literal though. Either will work:

var regex = "^\\s+$";
var regex = /^\s+$/;

Also note that + will require at least one space. You may want to use *.

How can I update npm on Windows?

I followed @josh3737 and installed the latest MSI from the node.js homepage.

But I had the additional problem that I still had the old node and npm on the command line. The problem was caused by the new installation, that it was installed into

C:\Program Files (x86)\nodejs\

instead of the previous installation in

C:\Program Files\nodejs\

The new installation added the new directory into my path variable after the old one. So the old installation was still the active one in the path. After removing C:\Program Files\nodejs\ from system path and C:\Users\...\AppData\Roaming\npm from user path and restarting the command line the new installation was active.

Maybe the least path was a local problem that has nothing to do with the new installation, I had two links to AppData\Roaming\npm in it. And maybe this can also be fixed by first uninstalling node.js and installing the new version afterwards.

Spring Boot @autowired does not work, classes in different package

When you use @SpringBootApplication annotation in for example package

com.company.config

it will automatically make component scan like this:

@ComponentScan("com.company.config") 

So it will NOT scan packages like com.company.controller etc.. Thats why you have to declare your @SpringBootApplication in package one level prior to your normal packages like this: com.company OR use scanBasePackages property, like this:

@SpringBootApplication(scanBasePackages = { "com.company" })

OR componentScan:

@SpringBootApplication
@ComponentScan("com.company")


How to establish ssh key pair when "Host key verification failed"

Task Passwordless authentication for suer.

Error : Host key verification failed.

Source :10.13.1.11 Target : 10.13.1.35

Temporary workaround :

[user@server~]$ ssh [email protected] The authenticity of host '10.13.1.35 (10.13.1.35)' can't be established. RSA key fingerprint is b8:ba:30:46:a9:ab:70:12:1a:f2:f1:61:69:73:0a:19. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '10.13.1.35' (RSA) to the list of known hosts.

Try to authenticate user again...it will work.

PHP Get Highest Value from Array

<?php 
$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5); 

foreach ($array as $key => $value) {
   if ($value >= $max) 
    $max = $key;     
}
echo " The array in largest number :".$max."<br/>";
?> 

How can I capitalize the first letter of each word in a string?

Why do you complicate your life with joins and for loops when the solution is simple and safe??

Just do this:

string = "the brown fox"
string[0].upper()+string[1:]

Checking if a key exists in a JS object

the simplest way is

_x000D_
_x000D_
const obj = {_x000D_
  a: 'value of a',_x000D_
  b: 'value of b',_x000D_
  c: 'value of c'_x000D_
};_x000D_
_x000D_
if(obj.a){_x000D_
  console.log(obj.a);_x000D_
}else{_x000D_
  console.log('obj.a does not exist');_x000D_
}
_x000D_
_x000D_
_x000D_

What is a reasonable length limit on person "Name" fields?

The average first name is about 6 letters. That leaves 43 for a last name. :) Seems like you could probably shorten it if you like.

The main question is how many rows do you think you will have? I don't think varchar(50) is going to kill you until you get several million rows.

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

From the composer site (it's clear enough)

require#

Lists packages required by this package. The package will not be installed unless those requirements can be met.

require-dev (root-only)#

Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

Using require-dev in Composer you can declare the dependencies you need for development/testing the project but don't need in production. When you upload the project to your production server (using git) require-dev part would be ignored.

Also check this answer posted by the author and this post as well.

Run PowerShell command from command prompt (no ps1 script)

Maybe powershell -Command "Get-AppLockerFileInformation....."

Take a look at powershell /?

How to set up ES cluster?

It is usually handled automatically.

If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery

Node 1:

    cluster.name: mycluster
    node.name: "node1"
    node.master: true
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2:

    cluster.name: mycluster
    node.name: "node2"
    node.master: false
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.

Edit: Please note that by ES rule, if you have N nodes, then by convention, N/2+1 nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.

Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.

For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.

linux shell script: split string, put them in an array then loop through them

Here's a variation on ashirazi's answer which doesn't rely on $IFS. It does have its own issues which I ouline below.

sentence="one;two;three"
sentence=${sentence//;/$'\n'}  # change the semicolons to white space
for word in $sentence
do
    echo "$word"
done

Here I've used a newline, but you could use a tab "\t" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS - it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.

How to do paging in AngularJS?

For anyone who find it difficult like me to create a paginator for a table I post this. So, in your view :

          <pagination total-items="total" items-per-page="itemPerPage"    ng-model="currentPage" ng-change="pageChanged()"></pagination>    
        <!-- To specify your choice of items Per Pages-->
     <div class="btn-group">
                <label class="btn btn-primary" ng-model="radioModel"  btn-radio="'Left'" data-ng-click="setItems(5)">5</label>
                <label class="btn btn-primary" ng-model="radioModel" btn-radio="'Middle'" data-ng-click="setItems(10)">10</label>
                <label class="btn btn-primary" ng-model="radioModel" btn-radio="'Right'" data-ng-click="setItems(15)">15</label>
            </div>
     //And don't forget in your table:
      <tr data-ng-repeat="p in profiles | offset: (currentPage-1)*itemPerPage | limitTo: itemPerPage" >

In your angularJs:

  var module = angular.module('myapp',['ui.bootstrap','dialogs']);
  module.controller('myController',function($scope,$http){
   $scope.total = $scope.mylist.length;     
   $scope.currentPage = 1;
   $scope.itemPerPage = 2;
   $scope.start = 0;

   $scope.setItems = function(n){
         $scope.itemPerPage = n;
   };
   // In case you can replace ($scope.currentPage - 1) * $scope.itemPerPage in <tr> by "start"
   $scope.pageChanged = function() {
        $scope.start = ($scope.currentPage - 1) * $scope.itemPerPage;
            };  
});
   //and our filter
     module.filter('offset', function() {
              return function(input, start) {
                start = parseInt(start, 10);
                return input.slice(start);
              };
            });     

What are NR and FNR and what does "NR==FNR" imply?

Look up NR and FNR in the awk manual and then ask yourself what is the condition under which NR==FNR in the following example:

$ cat file1
a
b
c

$ cat file2
d
e

$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e

splitting a number into the integer and decimal parts

Use math.modf:

import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)

"End of script output before headers" error in Apache

Internal error is due to a HIDDEN character at end of shebang line !! ie line #!/usr/bin/perl

By adding - or -w at end moves the character away from "perl" allowing the path to the perl processor to be found and script to execute.

HIDDEN character is created by the editor used to create the script

How do I disable fail_on_empty_beans in Jackson?

In my case I didnt need to disable it , rather I had to put this code on top of my class : (and this solved my issue)

    @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)//this is what was added
    @Value //this was there already
    @Builder//this was there already

public class NameOfClass {
     //some code in here.
}

Error during installing HAXM, VT-X not working

If your emulators were working and now they aren't due to Avast...

Avast no longer has the option for "Enable Hardware-assisted Virtualization" in Troubleshooting. (it's now March 2017)

Avast captures "emulator.exe", which disables emulators,and stows it in the Virus chest. Open the chest, "Restore and add to exclusions" and your emulator works again...

Pictorial on Avast fix

How can I edit a .jar file?

This is a tool to open Java class file binaries, view their internal structure, modify portions of it if required and save the class file back. It also generates readable reports similar to the javap utility. Easy to use Java Swing GUI. The user interface tries to display as much detail as possible and tries to present a structure as close as the actual Java class file structure. At the same time ease of use and class file consistency while doing modifications is also stressed. For example, when a method is deleted, the associated constant pool entry will also be deleted if it is no longer referenced. In built verifier checks changes before saving the file. This tool has been used by people learning Java class file internals. This tool has also been used to do quick modifications in class files when the source code is not available." this is a quote from the website.

http://classeditor.sourceforge.net/

How can I find the length of a number?

You have to make the number to string in order to take length

var num = 123;

alert((num + "").length);

or

alert(num.toString().length);

MVC 4 Razor adding input type date

If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.

@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

<script>

    $(document).ready(function(){

      $('.datepicker').datepicker();

     });

</script>

}

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

It means:

Initialization error occurred. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line.

So basically it could be just about anything haha...try running the command one at a time from the command prompt to figure out which part of which command is giving you trouble.

socket.error:[errno 99] cannot assign requested address and namespace in python

Stripping things down to basics this is what you would want to test with:

import socket
server = socket.socket() 
server.bind(("10.0.0.1", 6677)) 
server.listen(4) 
client_socket, client_address = server.accept()
print(client_address, "has connected")
while 1==1:
    recvieved_data = client_socket.recv(1024)
    print(recvieved_data)

This works assuming a few things:

  1. Your local IP address (on the server) is 10.0.0.1 (This video shows you how)
  2. No other software is listening on port 6677

Also note the basic concept of IP addresses:

Try the following, open the start menu, in the "search" field type cmd and press enter. Once the black console opens up type ping www.google.com and this should give you and IP address for google. This address is googles local IP and they bind to that and obviously you can not bind to an IP address owned by google.

With that in mind, you own your own set of IP addresses. First you have the local IP of the server, but then you have the local IP of your house. In the below picture 192.168.1.50 is the local IP of the server which you can bind to. You still own 83.55.102.40 but the problem is that it's owned by the Router and not your server. So even if you visit http://whatsmyip.com and that tells you that your IP is 83.55.102.40 that is not the case because it can only see where you're coming from.. and you're accessing your internet from a router.

enter image description here

In order for your friends to access your server (which is bound to 192.168.1.50) you need to forward port 6677 to 192.168.1.50 and this is done in your router. Assuming you are behind one.

If you're in school there's other dilemmas and routers in the way most likely.

multiple axis in matplotlib with different scales

if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True, like this:

df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)

This would look something like below:

enter image description here

You can do few more things as well. Take a look at Pandas plotting doc.

How to find nth occurrence of character in a string?

//scala

// throw's -1 if the value isn't present for nth time, even if it is present till n-1 th time. // throw's index if the value is present for nth time

def indexOfWithNumber(tempString:String,valueString:String,numberOfOccurance:Int):Int={
var stabilizeIndex=0 
var tempSubString=tempString 
var tempIndex=tempString.indexOf(valueString) 
breakable
{
for ( i <- 1 to numberOfOccurance)
if ((tempSubString.indexOf(valueString) != -1) && (tempIndex != -1))
{
tempIndex=tempSubString.indexOf(valueString)
tempSubString=tempSubString.substring(tempIndex+1,tempSubString.size) // ADJUSTING FOR 0
stabilizeIndex=stabilizeIndex+tempIndex+1 // ADJUSTING FOR 0
}
else
{ 
stabilizeIndex= -1
tempIndex= 0
break
}
}
stabilizeIndex match { case value if value <= -1 => -1 case _ => stabilizeIndex-1 } // reverting for adjusting 0 previously
}


indexOfWithNumber("bbcfgtbgft","b",3) // 6
indexOfWithNumber("bbcfgtbgft","b",2) //1
indexOfWithNumber("bbcfgtbgft","b",4) //-1

indexOfWithNumber("bbcfgtbcgft","bc",1)  //1
indexOfWithNumber("bbcfgtbcgft","bc",4) //-1
indexOfWithNumber("bbcfgtbcgft","bc",2) //6

Best way to disable button in Twitter's Bootstrap

Building off jeroenk's answer, here's the rundown:

$('button').addClass('disabled'); // Disables visually
$('button').prop('disabled', true); // Disables visually + functionally

$('input[type=button]').addClass('disabled'); // Disables visually
$('input[type=button]').prop('disabled', true); // Disables visually + functionally

$('a').addClass('disabled'); // Disables visually
$('a').prop('disabled', true); // Does nothing
$('a').attr('disabled', 'disabled'); // Disables visually

See fiddle

Vim multiline editing like in sublimetext?

Do yourself a favor by dropping the Windows compatibility layer.

The normal shortcut for entering Visual-Block mode is <C-v>.

Others have dealt with recording macros, here are a few other ideas:

Using only visual-block mode.

  1. Put the cursor on the second word:

    asd |a|sd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    
  2. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom:

    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    asd [a]sd asd asd asd;
    
  3. Hit I"<Esc> to obtain:

    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    
  4. Put the cursor on the last char of the third word:

    asd "asd as|d| asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    asd "asd asd asd asd;
    
  5. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom:

    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    asd "asd as[d] asd asd;
    
  6. Hit A"<Esc> to obtain:

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    

With visual-block mode and Surround.vim.

  1. Put the cursor on the second word:

    asd |a|sd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    asd asd asd asd asd;
    
  2. Hit <C-v> to enter visual-block mode and expand your selection toward the bottom and the right:

    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    asd [asd asd] asd asd;
    
  3. Hit S" to surround your selection with ":

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    

With visual-line mode and :normal.

  1. Hit V to select the whole line and expand it toward the bottom:

    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    [asd asd asd asd asd;]
    
  2. Execute this command: :'<,'>norm ^wi"<C-v><Esc>eea"<CR> to obtain:

    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    asd "asd asd" asd asd;
    
    • :norm[al] allows you to execute normal mode commands on a range of lines (the '<,'> part is added automatically by Vim and means "act on the selected area")

    • ^ puts the cursor on the first char of the line

    • w moves to the next word

    • i" inserts a " before the cursor

    • <C-v><Esc> is Vim's way to input a control character in this context, here it's <Esc> used to exit insert mode

    • ee moves to the end of the next word

    • a" appends a " after the cursor

    • <CR> executes the command

    Using Surround.vim, the command above becomes

    :'<,'>norm ^wvees"<CR>
    

Codesign error: Provisioning profile cannot be found after deleting expired profile

Just spent a hour or so doing this and with the help of Brad's advice and a few additional changes it all worked.

I've done this using the following: 10.7.3, Xcode 4.3.2, iOS 5.1 btw.

1) Right click on your myapp.xcodeproj and select package contents

2) open project.pbxproj with a text editor (don't recommend textedit as it may screw up the formatting)

3) Scroll all the way down until you find /* Begin XCBuildConfiguration section */

4) Notice that you have a debug and release sections

5) In the release section take a look at CODE_SIGN_IDENTITY & "CODE_SIGN_IDENTITY[sdk=iphoneos*]" it should look something like this:

CODE_SIGN_IDENTITY = "iPhone Distribution: MyCompany LLC";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution: MyCompany LLC";

6) Take a look at PROVISIONING_PROFILE and "PROVISIONING_PROFILE[sdk=iphoneos*]" they should look like this:

PROVISIONING_PROFILE = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";

This should match your provisioning profile in Xcode. To see if they match open Xcode > Window > Organizer > Devices > Provisioning Profiles > Right click on the profile > Reveal in Finder > The filename of the .mobileprovision is your profile id.

7) Scroll down in the project.pbxproj and find a second instance of the release section. The second instance of the release section should end with a comment saying /* End XCBuildConfiguration section */

8) make sure that the second section matches the first section so that CODE_SIGN_IDENTITY, "CODE_SIGN_IDENTITY[sdk=iphoneos*], and PROVISIONING_PROFILE are all filled in.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Error occurred here was due to the use of single quotes ('). You can put your query like this:

mysql_query("
SELECT * FROM Users 
WHERE UserName 
LIKE '".mysql_real_escape_string ($username)."'
");

It's using mysql_real_escape_string for prevention of SQL injection. Though we should use MySQLi or PDO_MYSQL extension for upgraded version of PHP (PHP 5.5.0 and later), but for older versions mysql_real_escape_string will do the trick.

Xcode 6.1 Missing required architecture X86_64 in file

One other thing to look out for is that XCode is badly handling the library imports, and in many cases the solution is to find the imported file in your project, delete it in Finder or from the command line and add it back again, otherwise it won't get properly updated by XCode. By XCode leaving there the old file you keep running in circles not understanding why it is not compiling, missing the architecture etc.

How to pass a textbox value from view to a controller in MVC 4?

You can use simple form:

@using(Html.BeginForm("Update", "Shopping"))
{
    <input type="text" id="ss" name="qty" value="@item.Quantity"/>
    ...
    <input type="submit" value="Update" />
}

And add here attribute:

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)

Is it ok to run docker from inside docker?

I answered a similar question before on how to run a Docker container inside Docker.

To run docker inside docker is definitely possible. The main thing is that you run the outer container with extra privileges (starting with --privileged=true) and then install docker in that container.

Check this blog post for more info: Docker-in-Docker.

One potential use case for this is described in this entry. The blog describes how to build docker containers within a Jenkins docker container.

However, Docker inside Docker it is not the recommended approach to solve this type of problems. Instead, the recommended approach is to create "sibling" containers as described in this post

So, running Docker inside Docker was by many considered as a good type of solution for this type of problems. Now, the trend is to use "sibling" containers instead. See the answer by @predmijat on this page for more info.

Why is “while ( !feof (file) )” always wrong?

No it's not always wrong. If your loop condition is "while we haven't tried to read past end of file" then you use while (!feof(f)). This is however not a common loop condition - usually you want to test for something else (such as "can I read more"). while (!feof(f)) isn't wrong, it's just used wrong.

How to Convert JSON object to Custom C# object?

To keep your options open, if you're using .NET 3.5 or later, here is a wrapped up example you can use straight from the framework using Generics. As others have mentioned, if it's not just simple objects you should really use JSON.net.

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

You'll need:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;

Remove Duplicates from range of cells in excel vba

To remove duplicates from a single column

 Sub removeDuplicate()
 'removeDuplicate Macro
 Columns("A:A").Select
 ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _ 
 Header:=xlNo 
 Range("A1").Select
 End Sub

if you have header then use Header:=xlYes

Increase your range as per your requirement.
you can make it to 1000 like this :

ActiveSheet.Range("$A$1:$A$1000")

More info here here

SelectSingleNode returning null for known good xml node path using XPath

If you want to ignore namespaces completely, you can use this:

static void Main(string[] args)
{
    string xml =
        "<My_RootNode xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"\">\n" +
        "    <id root=\"2.16.840.1.113883.3.51.1.1.1\" extension=\"someIdentifier\" xmlns=\"urn:hl7-org:v3\" />\n" +
        "    <creationTime xsi:nil=\"true\" xmlns=\"urn:hl7-org:v3\" />\n" +
        "</My_RootNode>";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    XmlNode idNode = doc.SelectSingleNode("/*[local-name()='My_RootNode']/*[local-name()='id']");
}

How to programmatically get iOS status bar height

    var statusHeight: CGFloat!
    if #available(iOS 13.0, *) {
         statusHeight = UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame.height
    } else {
        // Fallback on earlier versions
        statusHeight = UIApplication.shared.statusBarFrame.height
    }

How to take the nth digit of a number in python

Ok, first of all, use the str() function in python to turn 'number' into a string

number = 9876543210 #declaring and assigning
number = str(number) #converting

Then get the index, 0 = 1, 4 = 3 in index notation, use int() to turn it back into a number

print(int(number[3])) #printing the int format of the string "number"'s index of 3 or '6'

if you like it in the short form

print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number'

Convert string to binary then back again using PHP

easiest way I found was to convert to HEX instead of a string. If it works for you:

$hex = bin2hex($bin); // It will convert a binary data to its hex representation

$bin = pack("H*" , $hex); // It will convert a hex to binary

OR

$bin = hex2bin($hex); // Available only on PHP 5.4

Automatically open Chrome developer tools when new tab/new window is opened

You can open Dev Tools (F12 in Chrome) in new window by clicking three, vertical dots on the right bottom corner, and choose Open as Separate Window.

How do I insert values into a Map<K, V>?

The syntax is

data.put("John","Taxi driver");

String Concatenation in EL

Mc Dowell's answer is right. I just want to add an improvement if in case you may need to return the variable's value as:

${ empty variable ? '<variable is empty>' : variable }

Find CRLF in Notepad++

[\r\n]+ should work too

Update March, 26th 2012, release date of Notepad++ 6.0:

OMG, it actually does work now!!!

PCRE regexp in Notepad++


Original answer 2008 (Notepad++ 4.x) - 2009-2010-2011 (Notepad++ 5.x)

Actually no, it does not seem to work with regexp...

But if you have Notepad++ 5.x, you can use the 'extended' search mode and look for \r\n. That does find all your CRLF.

(I realize this is the same answer than the others, but again, 'extended mode' is only available with Notepad++ 4.9, 5.x and more)


Since April 2009, you have a wiki article on the Notepad++ site on this topic:
"How To Replace Line Ends, thus changing the line layout".
(mentioned by georgiecasey in his/her answer below)

Some relevant extracts includes the following search processes:

Simple search (Ctrl+F), Search Mode = Normal

You can select an EOL in the editing window.

  • Just move the cursor to the end of the line, and type Shift+Right Arrow.
  • or, to select EOL with the mouse, start just at the line end and drag to the start of the next line; dragging to the right of the EOL won't work. You can manually copy the EOL and paste it into the field for Unix files (LF-only).

Simple search (Ctrl+F), Search Mode = Extended

The "Extended" option shows \n and \r as characters that could be matched.
As with the Normal search mode, Notepad++ is looking for the exact character.
Searching for \r in a UNIX-format file will not find anything, but searching for \n will. Similarly, a Macintosh-format file will contain \r but not \n.

Simple search (Ctrl+F), Search Mode = Regular expression

Regular expressions use the characters ^ and $ to anchor the match string to the beginning or end of the line. For instance, searching for return;$ will find occurrences of "return;" that occur with no subsequent text on that same line. The anchor characters work identically in all file formats.
The '.' dot metacharacter does not match line endings.

[Tested in Notepad++ 5.8.5]: a regular expression search with an explicit \r or \n does not work (contrary to the Scintilla documentation).
Neither does a search on an explicit (pasted) LF, or on the (invisible) EOL characters placed in the field when an EOL is selected. Advanced search (Ctrl+R) without regexp

Ctrl+M will insert something that matches newlines. They will be replaced by the replace string.
I recommend this method as the most reliable, unless you really need to use regex.
As an example, to remove every second newline in a double spaced file, enter Ctrl+M twice in the search string box, and once in the replace string box.

Advanced search (Ctrl+R) with Regexp.

Neither Ctrl+M, $ nor \r\n are matched.


The same wiki also mentions the Hex editor alternative:

  • Type the new string at the beginning of the document.
  • Then select to view the document in Hex mode.
  • Select one of the new lines and hit Ctrl+H.
  • While you have the Replace dialog box up, select on the background the new replacement string and Ctrl+C copy it to paste it in the Replace with text input.
  • Then Replace or Replace All as you wish.

Note: the character selected for new line usually appears as 0a.
It may have a different value if the file is in Windows Format. In that case you can always go to Edit -> EOL Conversion -> Convert to Unix Format, and after the replacement switch it back and Edit -> EOL Conversion -> Convert to Windows Format.

Insert HTML with React Variable Statements (JSX)

To avoid linter errors, I use it like this:

  render() {
    const props = {
      dangerouslySetInnerHTML: { __html: '<br/>' },
    };
    return (
        <div {...props}></div>
    );
  }

Detect end of ScrollView

All of these answers are so complicated, but there is a simple built-in method that accomplishes this: canScrollVertically(int)

For example:

@Override
public void onScrollChanged() {
    if (!scrollView.canScrollVertically(1)) {
        // bottom of scroll view
    }
    if (!scrollView.canScrollVertically(-1)) {
        // top of scroll view
    }
}

This also works with RecyclerView, ListView, and actually any other view since the method is implemented on View.

If you have a horizontal ScrollView, the same can be achieved with canScrollHorizontally(int)

What is the easiest way to push an element to the beginning of the array?

Since Ruby 2.5.0, Array ships with the prepend method (which is just an alias for the unshift method).

How to include route handlers in multiple files in Express?

index.js

const express = require("express");
const app = express();
const http = require('http');
const server = http.createServer(app).listen(3000);
const router = (global.router = (express.Router()));
app.use('/books', require('./routes/books'))
app.use('/users', require('./routes/users'))
app.use(router);

routes/users.js

const router = global.router
router.get('/', (req, res) => {
    res.jsonp({name: 'John Smith'})
}

module.exports = router

routes/books.js

const router = global.router
router.get('/', (req, res) => {
    res.jsonp({name: 'Dreams from My Father by Barack Obama'})
}

module.exports = router

if you have your server running local (http://localhost:3000) then

// Users
curl --request GET 'localhost:3000/users' => {name: 'John Smith'}

// Books
curl --request GET 'localhost:3000/users' => {name: 'Dreams from My Father by Barack Obama'}

How to force input to only allow Alpha Letters?

The property event.key gave me an undefined value. Instead, I used event.keyCode:

function alphaOnly(event) {
  var key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

Note that the value of 8 is for the backspace key.

How do I output coloured text to a Linux terminal?

As others have stated, you can use escape characters. You can use my header in order to make it easier:

#ifndef _COLORS_
#define _COLORS_

/* FOREGROUND */
#define RST  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST

#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST

#endif  /* _COLORS_ */

An example using the macros of the header could be:

#include <iostream>
#include "colors.h"
using namespace std;

int main()
{
    cout << FBLU("I'm blue.") << endl;
    cout << BOLD(FBLU("I'm blue-bold.")) << endl;
    return 0;
}

enter image description here

Failed to decode downloaded font

Sometimes this problem happens when you upload/download the fonts using the wrong FTP method. Fonts must be FTP-ed using binary method, not ASCII. (Depending on your mood, it may feel counterintuitive, lol). If you ftp the font files using ASCII method, you can get this error message. If you ftp your files with an 'auto' method, and you get this error message, try ftp forcing the binary method.

"Auth Failed" error with EGit and GitHub

For you who, like me, already did setup you ssh-keys but still get the errors:

Make sure you did setup a push remote. It worked for me when I got both the Cannot get remote repository refs-problems ("... Passphrase for..." and "Auth fail" in the "Push..." dialog).

Provided that you already:

  1. Setup your SSH keys with Github (Window > Preferences > General > Network Connections > SSH2)

  2. Setup your local repository (you can follow this guide for that)

  3. Created a Github repository (same guide)

... here's how you do it:

  • Go to the Git Repositories view (Window > Show View > Other > Git Repositories)
  • Expand your Repository and right click Remotes --> "Create Remote"
  • "Remote Name": origin, "Configure push": checked --> click "OK"
  • Click the "Change..." button
  • Paste your git URI and select protocol ssh --> click "Finish"
  • Now, click "Save and Push" and NOW you should get a password prompt --> enter the public key passphrase here (provided that you DID (and you should) setup a passphrase to your public key) --> click "OK"
  • Now you should get a confirmation window saying "Pushed to YourRepository - origin" --> click "OK"
  • Push to upstream, but this time use "Configured remote repository" as your Destination Git repository
  • Go get yourself a well earned cup of coffee!

How do I make an auto increment integer field in Django?

You can override Django save method official doc about it.

The modified version of your code:

class Order(models.Model):
    cart = models.ForeignKey(Cart)
    add_date = models.DateTimeField(auto_now_add=True)
    order_number = models.IntegerField(default=0)  # changed here
    enable = models.BooleanField(default=True)

    def save(self, *args, **kwargs):
        self.order_number = self.order_number + 1
        super().save(*args, **kwargs)  # Call the "real" save() method.

Another way is to use signals. More one:

  1. official Django docs about pre-save
  2. stackoverflow example about using pre-save signal

What is token-based authentication?

The question is old and the technology has advanced, here is the current state:

JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for passing claims between parties in web application environment. The tokens are designed to be compact, URL-safe and usable especially in web browser single sign-on (SSO) context.

https://en.wikipedia.org/wiki/JSON_Web_Token

In PowerShell, how can I test if a variable holds a numeric value?

-is and -as operators requires a type you can compare against. If you're not sure what the type might be, try to evaluate the content (partial type list):

(Invoke-Expression '1.5').GetType().Name -match 'byte|short|int32|long|sbyte|ushort|uint32|ulong|float|double|decimal'

Good or bad, it can work against hex values as well (Invoke-Expression '0xA' ...)

How to set delay in vbscript

If you're trying to simulate a sleep delay in VBScript but WScript is not available (eg: your script is called from Microsoft's BGInfo tool), then try the following approach.

The example below will delay until 10 seconds from the moment the instruction is processed:

Dim dteWait
dteWait = DateAdd("s", 10, Now())
Do Until (Now() > dteWait)
Loop

Javascript add method to object

you need to add it to Foo's prototype:

function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()

Rails: How does the respond_to block work?

I'd like to understand how the respond_to block actually works. What type of variable is format? Are .html and .json methods of the format object?

In order to understand what format is, you could first look at the source for respond_to, but quickly you'll find that what really you need to look at is the code for retrieve_response_from_mimes.

From here, you'll see that the block that was passed to respond_to (in your code), is actually called and passed with an instance of Collector (which within the block is referenced as format). Collector basically generates methods (I believe at Rails start-up) based on what mime types rails knows about.

So, yes, the .html and .json are methods defined (at runtime) on the Collector (aka format) class.

Object Library Not Registered When Adding Windows Common Controls 6.0

I have been having the same problem. VB6 Win7 64 bit and have come across a very simple solution, so I figured it would be a good idea to share it here in case it helps anyone else.

First I have tried the following with no success:

  • unregistered and re-registering MSCOMCTL, MSCOMCTL2 and the barcode active X controls in every directory I could think of trying (VB98, system 32, sysWOW64, project folder.)

  • Deleting working folder and getting everything again. (through source safe)

  • Copying the OCX files from a machine with no problems and registering those.

  • Installing service pack 6

  • Installing MZ tools - it was worth a try

  • Installing the distributable version of the project.

  • Manually editing the vbp file (after making it writeable) to amend/remove the references and generally fiddling.

  • Un-Installing VB6 and re-Installing (this I thought was a last resort) The problem was occurring on a new project and not just existing ones.

NONE of the above worked but the following did

Open VB6
New project
>Project
    >Components
        Tick the following:
            Microsoft flexigrid control 6.0 (sp6)
            Microsoft MAPI controls 6.0
            Microsoft Masked Edit Control 6.0 (sp3)
            Microsoft Tabbed Dialog Control 6.0 (sp6)
        >Apply

After this I could still not tick the Barcode Active X or the windows common contols 6.0 and windows common controls 2 6.0, but when I clicked apply, the message changed from unregistered, to that it was already in the project.

>exit the components dialog and then load project. 

This time it worked. Tried the components dialog again and the missing three were now ticked. Everything seems fine now.

How to turn off caching on Firefox?

The Web Developer Toolbar has an option to disable caching which makes it very easy to turn it on and off when you need it.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

If you are using jsvc to run tomcat as tomcat (run /etc/init.d/tomcat as root), edit /etc/init.d/tomcat and add $CATALINA_HOME/bin/tomcat-juli.jar to CLASSPATH.

How to change title of Activity in Android?

This worked for me.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment, container, false);
    getActivity().setTitle("My Title");
//...
}

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

Android screen size HDPI, LDPI, MDPI

The documentation is quite sketchy as far as definitive resolutions go. After some research, here's the solution I came to: Android splash screen image sizes to fit all devices

It's basically guided towards splash screens, but it's perfectly applicable to images that should occupy full screen.

How do I make a <div> move up and down when I'm scrolling the page?

using position:fixed alone is just fine when you don't have a header or logo at the top of your page. This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. It will then lock it back into place when you get to the top again.

if($(window).scrollTop() > Height_of_Header){
    //begin to scroll
    $("#div").css("position","fixed");
    $("#div").css("top",0);
}
else{
    //lock it back into place
    $("#div").css("position","relative");
}

Filter element based on .data() key/value

your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.

var $previous = $('.navlink').filter(function() { 
  return $(this).data("selected") == true 
});

How to recover closed output window in netbeans?

If you run the server in normal mode you can recover the log by restarting the main project in debug mode. It seems that NB opens a new server log when the server run mode changes.

Direct casting vs 'as' operator?

  1. string s = (string)o; Use when something should definitely be the other thing.
  2. string s = o as string; Use when something might be the other thing.
  3. string s = o.ToString(); Use when you don't care what it is but you just want to use the available string representation.

How to delay the .keyup() handler until the user stops typing?

Delay Multi Function Calls using Labels

This is the solution i work with. It will delay the execution on ANY function you want. It can be the keydown search query, maybe the quick click on previous or next buttons ( that would otherwise send multiple request if quickly clicked continuously , and be not used after all). This uses a global object that stores each execution time, and compares it with the most current request.

So the result is that only that last click / action will actually be called, because those requests are stored in a queue, that after the X milliseconds is called if no other request with the same label exists in the queue!

function delay_method(label,callback,time){
    if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
    delayed_methods[label]=Date.now();
    var t=delayed_methods[label];
    setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  delayed_methods[label]=""; callback();}}, time||500);
  }

You can set your own delay time ( its optional, defaults to 500ms). And send your function arguments in a "closure fashion".

For example if you want to call the bellow function:

function send_ajax(id){console.log(id);}

To prevent multiple send_ajax requests, you delay them using:

delay_method( "check date", function(){ send_ajax(2); } ,600);

Every request that uses the label "check date" will only be triggered if no other request is made in the 600 miliseconds timeframe. This argument is optional

Label independency (calling the same target function) but run both:

delay_method("check date parallel", function(){send_ajax(2);});
delay_method("check date", function(){send_ajax(2);});

Results in calling the same function but delay them independently because of their labels being different

PHP Session timeout

first, store the last time the user made a request

<?php
  $_SESSION['timeout'] = time();
?>

in subsequent request, check how long ago they made their previous request (10 minutes in this example)

<?php
  if ($_SESSION['timeout'] + 10 * 60 < time()) {
     // session timed out
  } else {
     // session ok
  }
?>

wampserver doesn't go green - stays orange

WAMP Server may turn orange for various reason as it is not working. This is also a another type of issue. that can be due to webservices is running in services.msc This is explained in the below blog. Please try it. How to resolve HTTP Error 404 and launch localhost with WAMP Server for PHP & MySql?

How to run 'sudo' command in windows

The following vbs script allows to launch a given command with arguments with elevation and mimics the behavior of the original unix sudo command for a limited set of used cases (it will not cache credentials nor it allows to truly execute commands with different credentials). I put it on C:\Windows\System32.

Set objArgs = WScript.Arguments
exe = objArgs(0)
args = ""
IF objArgs.Count >= 2 Then
   args = args & objArgs(1)
End If
For it = 2 to objArgs.Count - 1
   args = args & " " & objArgs(it)
Next
Set objShell = CreateObject( "WScript.Shell")
windir=objShell.ExpandEnvironmentStrings("%WINDIR%")
Set objShellApp = CreateObject("Shell.Application")
objShellApp.ShellExecute exe, args, "", "runas", 1
set objShellApp = nothing

Example use on a command prompt sudo net start service

Break string into list of characters in Python

fO = open(filename, 'rU')
lst = list(fO.read())

Using Position Relative/Absolute within a TD?

Contents of table cell, variable height, could be more than 60px;

<div style="position: absolute; bottom: 0px;">
    Notice
</div>

How to use document.getElementByName and getElementByTag?

  1. The getElementsByName() method accesses all elements with the specified name. this method returns collection of elements that is an array.
  2. The getElementsByTagName() method accesses all elements with the specified tagname. this method returns collection of elements that is an array.
  3. Accesses the first element with the specified id. this method returns only a single element.

eg:

<script type="text/javascript">
    function getElements() {
        var x=document.getElementById("y");
        alert(x.value);
    }
</script>
</head>
<body>
    <input name="x" id="y" type="text" size="20" /><br />

This will return a single HTML element and display the value attribute of it.

<script type="text/javascript">
    function getElements() {
        var x=document.getElementsByName("x");
        alert(x.length);
    }
</script>
</head>
<body>
    <input name="x" id="y" type="text" size="20" /><br />
    <input name="x" id="y" type="text" size="20" /><br />

this will return an array of HTML elements and number of elements that match the name attribute.

Extracted from w3schools.

Angular-Material DateTime Picker Component?

Unfortunately, the answer to your question of whether there is official Material support for selecting the time is "No", but it's currently an open issue on the official Material2 GitHub repo: https://github.com/angular/material2/issues/5648

Hopefully this changes soon, in the mean time, you'll have to fight with the 3rd-party ones you've already discovered. There are a few people in that GitHub issue that provide their self-made workarounds that you can try.

Looping through a hash, or using an array in PowerShell

About looping through a hash:

$Q = @{"ONE"="1";"TWO"="2";"THREE"="3"}
$Q.GETENUMERATOR() | % { $_.VALUE }
1
3
2

$Q.GETENUMERATOR() | % { $_.key }
ONE
THREE
TWO

selecting rows with id from another table

You can use a subquery:

SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');

and if you need to show all columns from both tables:

SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'

Selenium Finding elements by class name in python

Use nth-child, for example: http://www.w3schools.com/cssref/sel_nth-child.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:nth-child(1)')

or http://www.w3schools.com/cssref/sel_firstchild.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:first-child')