Programs & Examples On #Axis2c

Apache Axis2/C is a Web services engine implemented in the C programming language. It is based on the extensible and flexible Axis2 architecture.

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

How to avoid HTTP error 429 (Too Many Requests) python

I've found out a nice workaround to IP blocking when scraping sites. It lets you run a Scraper indefinitely by running it from Google App Engine and redeploying it automatically when you get a 429.

Check out this article

How to get a web page's source code from Java

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

Good tool to visualise database schema?

Try PHPMyAdmin which has some really nice visualisation and editing feature. I am pretty sure you can even export to exel from it.

Disable vertical scroll bar on div overflow: auto

If you want to accomplish the same in Gecko (NS6+, Mozilla, etc) and IE4+ simultaneously, I believe this should do the trick:V

body {
overflow: -moz-scrollbars-vertical;
overflow-x: hidden;
overflow-y: auto;
}

This will be applied to entire body tag, please update it to your relevant css and apply this properties.

Get value of a string after last slash in JavaScript

light weigh

string.substring(start,end)

where

start = Required. The position where to start the extraction. First character is at index 0`.

end = Optional. The position (up to, but not including) where to end the extraction. If omitted, it extracts the rest of the string.

    var string = "var1/var2/var3";

    start   = string.lastIndexOf('/');  //console.log(start); o/p:- 9
    end     = string.length;            //console.log(end);   o/p:- 14

    var string_before_last_slash = string.substring(0, start);
    console.log(string_before_last_slash);//o/p:- var1/var2

    var string_after_last_slash = string.substring(start+1, end);
    console.log(string_after_last_slash);//o/p:- var3

OR

    var string_after_last_slash = string.substring(start+1);
    console.log(string_after_last_slash);//o/p:- var3

Check if decimal value is null

A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue

How can I find which tables reference a given table in Oracle SQL Developer?

To add to the above answer for sql developer plugin, using the below xml will help in getting the column associated with the foreign key.

    <items>
        <item type="editor" node="TableNode" vertical="true">
        <title><![CDATA[FK References]]></title>
        <query>
            <sql>
                <![CDATA[select a.owner,
                                a.constraint_name,
                                a.table_name,
                                b.column_name,
                                a.status
                         from   all_constraints a
                         join   all_cons_columns b ON b.constraint_name = a.constraint_name
                         where  a.constraint_type = 'R'
                                and exists(
                                   select 1
                                   from   all_constraints
                                   where  constraint_name=a.r_constraint_name
                                          and constraint_type in ('P', 'U')
                                          and table_name = :OBJECT_NAME
                                          and owner = :OBJECT_OWNER)
                                   order by table_name, constraint_name]]>
            </sql>
        </query>
        </item>
    </items>

IIS7 URL Redirection from root to sub directory

I think, this could be done without IIS URL Rewrite module. <httpRedirect> supports wildcards, so you can configure it this way:

  <system.webServer>
    <httpRedirect enabled="true">
      <add wildcard="/" destination="/menu_1/MainScreen.aspx" />
    </httpRedirect>
  </system.webServer>

Note that you need to have the "HTTP Redirection" feature enabled on IIS - see HTTP Redirects

Convert Pixels to Points

Surely this whole question should be:

"How do I obtain the horizontal and vertical PPI (Pixels Per Inch) of the monitor?"

There are 72 points in an inch (by definition, a "point" is defined as 1/72nd of an inch, likewise a "pica" is defined as 1/72nd of a foot). With these two bits of information you can convert from px to pt and back very easily.

How to track down a "double free or corruption" error

If you're using glibc, you can set the MALLOC_CHECK_ environment variable to 2, this will cause glibc to use an error tolerant version of malloc, which will cause your program to abort at the point where the double free is done.

You can set this from gdb by using the set environment MALLOC_CHECK_ 2 command before running your program; the program should abort, with the free() call visible in the backtrace.

see the man page for malloc() for more information

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

Return value from nested function in Javascript

Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.

var updater = {};

function geoCodeCity(goocoord) { 
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'latLng': goocoord
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            updater.currentLocation = results[1].formatted_address;
        } else {
            if (status == "ERROR") { 
                    console.log(status);
                }
        }
    });
};

Printing 1 to 1000 without loop or conditionals

Here are three solutions that I know. The second might be argued though.

// compile time recursion
template<int N> void f1()
{ 
    f1<N-1>(); 
    cout << N << '\n'; 
}

template<> void f1<1>() 
{ 
    cout << 1 << '\n'; 
}

// short circuiting (not a conditional statement)
void f2(int N)
{ 
    N && (f2(N-1), cout << N << '\n');
}

// constructors!
struct A {
    A() {
        static int N = 1;
        cout << N++ << '\n';
    }
};

int main()
{
    f1<1000>();
    f2(1000);
    delete[] new A[1000]; // (3)
    A data[1000]; // (4) added by Martin York
}

[ Edit: (1) and (4) can be used for compile time constants only, (2) and (3) can be used for runtime expressions too — end edit. ]

Soft keyboard open and close listener in an activity in Android

Jaap's answer won't work for AppCompatActivity. Instead get the height of the Status Bar and Navigation bar etc and compare to your app's window size.

Like so:

    private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // navigation bar height
        int navigationBarHeight = 0;
        int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            navigationBarHeight = getResources().getDimensionPixelSize(resourceId);
        }

        // status bar height
        int statusBarHeight = 0;
        resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }

        // display window size for the app layout
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

        // screen height - (user app height + status + nav) ..... if non-zero, then there is a soft keyboard
        int keyboardHeight = rootLayout.getRootView().getHeight() - (statusBarHeight + navigationBarHeight + rect.height());

        if (keyboardHeight <= 0) {
            onHideKeyboard();
        } else {
            onShowKeyboard(keyboardHeight);
        }
    }
};

Integrating Dropzone.js into existing HTML form with other fields

The "dropzone.js" is the most common library for uploading images. If you want to have the "dropzone.js" as just part of your form, you should do the following steps:

1) for the client side:

HTML :

    <form action="/" enctype="multipart/form-data" method="POST">
        <input type="text" id ="Username" name ="Username" />
        <div class="dropzone" id="my-dropzone" name="mainFileUploader">
            <div class="fallback">
                <input name="file" type="file" multiple />
            </div>
        </div>
    </form>
    <div>
        <button type="submit" id="submit-all"> upload </button>
    </div>

JQuery:

    <script>
        Dropzone.options.myDropzone = {
            url: "/Account/Create",
            autoProcessQueue: false,
            uploadMultiple: true,
            parallelUploads: 100,
            maxFiles: 100,
            acceptedFiles: "image/*",

            init: function () {

                var submitButton = document.querySelector("#submit-all");
                var wrapperThis = this;

                submitButton.addEventListener("click", function () {
                    wrapperThis.processQueue();
                });

                this.on("addedfile", function (file) {

                    // Create the remove button
                    var removeButton = Dropzone.createElement("<button class='btn btn-lg dark'>Remove File</button>");

                    // Listen to the click event
                    removeButton.addEventListener("click", function (e) {
                        // Make sure the button click doesn't submit the form:
                        e.preventDefault();
                        e.stopPropagation();

                        // Remove the file preview.
                        wrapperThis.removeFile(file);
                        // If you want to the delete the file on the server as well,
                        // you can do the AJAX request here.
                    });

                    // Add the button to the file preview element.
                    file.previewElement.appendChild(removeButton);
                });

                this.on('sendingmultiple', function (data, xhr, formData) {
                    formData.append("Username", $("#Username").val());
                });
            }
        };
    </script>

2) for the server side:

ASP.Net MVC

    [HttpPost]
    public ActionResult Create()
    {
        var postedUsername = Request.Form["Username"].ToString();
        foreach (var imageFile in Request.Files)
        {

        }

        return Json(new { status = true, Message = "Account created." });
    }

How do I copy an entire directory of files into an existing directory using Python?

i would assume fastest and simplest way would be have python call the system commands...

example..

import os
cmd = '<command line call>'
os.system(cmd)

Tar and gzip up the directory.... unzip and untar the directory in the desired place.

yah?

How do I get the coordinate position after using jQuery drag and drop?

None of the above worked for me.

Here's my solution- works great:

$dropTarget.droppable({
    drop: function( event, ui ) {

    // Get mouse position relative to drop target: 
    var dropPositionX = event.pageX - $(this).offset().left;
    var dropPositionY = event.pageY - $(this).offset().top;
    // Get mouse offset relative to dragged item:
    var dragItemOffsetX = event.offsetX;
    var dragItemOffsetY = event.offsetY;
    // Get position of dragged item relative to drop target:
    var dragItemPositionX = dropPositionX-dragItemOffsetX;
    var dragItemPositionY = dropPositionY-dragItemOffsetY;

    alert('DROPPED IT AT ' + dragItemPositionX + ', ' + dragItemPositionY);

(Based partly off solution given here: https://stackoverflow.com/a/10429969/165673)

How to get data by SqlDataReader.GetValue by column name

You can also do this.

//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName"); 
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);

MD5 hashing in Android

Here is an implementation you can use (updated to use more up to date Java conventions - for:each loop, StringBuilder instead of StringBuffer):

public static String md5(final String s) {
    final String MD5 = "MD5";
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest
                .getInstance(MD5);
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuilder hexString = new StringBuilder();
        for (byte aMessageDigest : messageDigest) {
            String h = Integer.toHexString(0xFF & aMessageDigest);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

Although it is not recommended for systems that involve even the basic level of security (MD5 is considered broken and can be easily exploited), it is sometimes enough for basic tasks.

Is it possible to use an input value attribute as a CSS selector?

Yes, but note: since the attribute selector (of course) targets the element's attribute, not the DOM node's value property (elem.value), it will not update while the form field is being updated.

Otherwise (with some trickery) I think it could have been used to make a CSS-only substitute for the "placeholder" attribute/functionality. Maybe that's what the OP was after? :)

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

The port is already being used by some other process as @Diego Pino said u can use lsof on unix to locate the process and kill the respective one, if you are on windows use netstat -ano to get all the pids of the process and the ports that everyone acquires. search for your intended port and kill.

to be very easy just restart your machine , if thats possible :)

Reading data from DataGridView in C#

Code Example : Reading data from DataGridView and storing it in an array

int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
    for (int j = 0; j < StartDataView.Columns.Count; j++)
    {
        if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
        {
            try
            {
                n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
            }
            catch (Exception Ee)
            { //get exception of "null"
                MessageBox.Show(Ee.ToString());
            }
        }
    }
}

Difference between .on('click') vs .click()

.click events only work when element gets rendered and are only attached to elements loaded when the DOM is ready.

.on events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).

How to format a URL to get a file from Amazon S3?

Documentation here, and I'll use the Frankfurt region as an example.

There are 2 different URL styles:

But this url does not work:

The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

I may be talking about another problem because I'm not getting NoSuchKey error but I suspect the error message has been made clearer over time.

Use success() or complete() in AJAX call

Is it that success() returns earlier than complete()?

Yes; the AJAX success() method runs before the complete() method.

Below is a diagram illustrating the process flow:

AJAX call process flow diagram.

It is important to note that

  • The success() (Local Event) is only called if the request was successful (no errors from the server, no errors with the data).

  • On the other hand, the complete() (Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

... more details on AJAX Events here.

How do I "select Android SDK" in Android Studio?

Now on Android Studio 3 and above, you can try to sync project with gradle like:

File -> Sync Project with Gradle Files

enter image description here

unable to start mongodb local server

Open the terminal and type:

mkdir -p /data/db

Then enter:

mongod

Resolving instances with ASP.NET Core DI from within ConfigureServices

Manually resolving instances involves using the IServiceProvider interface:

Resolving Dependency in Startup.ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyService, MyService>();

    var serviceProvider = services.BuildServiceProvider();
    var service = serviceProvider.GetService<IMyService>();
}

Resolving Dependencies in Startup.Configure

public void Configure(
    IApplicationBuilder application,
    IServiceProvider serviceProvider)
{
    // By type.
    var service1 = (MyService)serviceProvider.GetService(typeof(MyService));

    // Using extension method.
    var service2 = serviceProvider.GetService<MyService>();

    // ...
}

Resolving Dependencies in Startup.Configure in ASP.NET Core 3

public void Configure(
    IApplicationBuilder application,
    IWebHostEnvironment webHostEnvironment)
{
    application.ApplicationServices.GetService<MyService>();
}

Using Runtime Injected Services

Some types can be injected as method parameters:

public class Startup
{
    public Startup(
        IHostingEnvironment hostingEnvironment,
        ILoggerFactory loggerFactory)
    {
    }

    public void ConfigureServices(
        IServiceCollection services)
    {
    }

    public void Configure(
        IApplicationBuilder application,
        IHostingEnvironment hostingEnvironment,
        IServiceProvider serviceProvider,
        ILoggerFactory loggerfactory,
        IApplicationLifetime applicationLifetime)
    {
    }
}

Resolving Dependencies in Controller Actions

[HttpGet("/some-action")]
public string SomeAction([FromServices] IMyService myService) => "Hello";

How to get an object's property's value by property name?

Here is an alternative way to get an object's property value:

write-host $(get-something).SomeProp

Display milliseconds in Excel

First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):

=DATE(1970,1,1)+(A1/86400000)

If your cell is properly formatted, you should see a human-readable date/time.

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

How to use hex color values

UIColor:

extension UIColor {

    convenience init(hex: Int) {
        let components = (
            R: CGFloat((hex >> 16) & 0xff) / 255,
            G: CGFloat((hex >> 08) & 0xff) / 255,
            B: CGFloat((hex >> 00) & 0xff) / 255
        )
        self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
    }

}

CGColor:

extension CGColor {

    class func colorWithHex(hex: Int) -> CGColorRef {

        return UIColor(hex: hex).CGColor

    }

}

Usage

let purple = UIColor(hex: 0xAB47BC)

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

Bootstrap select dropdown list placeholder

dropdown or select doesn't have a placeholder because HTML doesn't support it but it's possible to create same effect so it looks the same as other inputs placeholder

_x000D_
_x000D_
    $('select').change(function() {_x000D_
     if ($(this).children('option:first-child').is(':selected')) {_x000D_
       $(this).addClass('placeholder');_x000D_
     } else {_x000D_
      $(this).removeClass('placeholder');_x000D_
     }_x000D_
    });
_x000D_
.placeholder{color: grey;}_x000D_
select option:first-child{color: grey; display: none;}_x000D_
select option{color: #555;} // bootstrap default color
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select class="form-control placeholder">_x000D_
   <option value="">Your Placeholder Text</option>_x000D_
   <option value="1">Text 1</option>_x000D_
   <option value="2">Text 2</option>_x000D_
   <option value="3">Text 3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

if you want to see first option in list remove display property from css

How to count number of files in each directory?

A super fast miracle command, which recursively traverses files to count the number of images in a directory and organize the output by image extension:

find . -type f | sed -e 's/.*\.//' | sort | uniq -c | sort -n | grep -Ei '(tiff|bmp|jpeg|jpg|png|gif)$'

Credits: https://unix.stackexchange.com/a/386135/354980

How can I convert a hex string to a byte array?

The following code changes the hexadecimal string to a byte array by parsing the string byte-by-byte.

public static byte[] ConvertHexStringToByteArray(string hexString)
{
    if (hexString.Length % 2 != 0)
    {
        throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
    }

    byte[] data = new byte[hexString.Length / 2];
    for (int index = 0; index < data.Length; index++)
    {
        string byteValue = hexString.Substring(index * 2, 2);
        data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
    }

    return data; 
}

how to set default method argument values?

You can't declare default values for the parameters like C# (I believe) lets you, but you could simply just create an overload.

public int doSomething(int arg1, int arg2) {
    //some logic here
    return 0;
}

//overload supplies default values of 1 and 2
public int doSomething() {
    return doSomething(1, 2);
}

If you are going to do something like this please do everyone else who works with your code a favor and make sure you mention in Javadoc comments what the default values you are using are!

Find all packages installed with easy_install/pip?

As of version 1.3 of pip you can now use pip list

It has some useful options including the ability to show outdated packages. Here's the documentation: https://pip.pypa.io/en/latest/reference/pip_list/

Beautiful way to remove GET-variables with PHP?

Couldn't you use the server variables to do this?

Or would this work?:

unset($_GET['page']);
$url = $_SERVER['SCRIPT_NAME'] ."?".http_build_query($_GET);

Just a thought.

multiple conditions for filter in spark data frames

This question has been answered but for future reference, I would like to mention that, in the context of this question, the where and filter methods in Dataset/Dataframe supports two syntaxes: The SQL string parameters:

df2 = df1.filter(("Status = 2 or Status = 3"))

and Col based parameters (mentioned by @David ):

df2 = df1.filter($"Status" === 2 || $"Status" === 3)

It seems the OP'd combined these two syntaxes. Personally, I prefer the first syntax because it's cleaner and more generic.

Sort an array of objects in React and render them

this.state.data.sort((a, b) => a.item.timeM > b.item.timeM).map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

s = "I     am having  a   very  nice  23!@$      day. "
sum([i.strip(string.punctuation).isalpha() for i in s.split()])

The statement above will go through each chunk of text and remove punctuations before verifying if the chunk is really string of alphabets.

Remove columns from dataframe where ALL values are NA

Late to the game but you can also use the janitor package. This function will remove columns which are all NA, and can be changed to remove rows that are all NA as well.

df <- janitor::remove_empty(df, which = "cols")

Completely removing phpMyAdmin

Try purge

sudo aptitude purge phpmyadmin

Not sure this works with plain old apt-get though

jquery how to use multiple ajax calls one after the end of the other

Wrap each ajax call in a named function and just add them to the success callbacks of the previous call:

function callA() {
    $.ajax({
    ...
    success: function() {
      //do stuff
      callB();
    }
    });
}

function callB() {
    $.ajax({
    ...
    success: function() {
        //do stuff
        callC();
    }
    });
}

function callC() {
    $.ajax({
    ...
    });
}


callA();

How to do a JUnit assert on a message in a logger

The API for Log4J2 is slightly different. Also you might be using its async appender. I created a latched appender for this:

    public static class LatchedAppender extends AbstractAppender implements AutoCloseable {

    private final List<LogEvent> messages = new ArrayList<>();
    private final CountDownLatch latch;
    private final LoggerConfig loggerConfig;

    public LatchedAppender(Class<?> classThatLogs, int expectedMessages) {
        this(classThatLogs, null, null, expectedMessages);
    }
    public LatchedAppender(Class<?> classThatLogs, Filter filter, Layout<? extends Serializable> layout, int expectedMessages) {
        super(classThatLogs.getName()+"."+"LatchedAppender", filter, layout);
        latch = new CountDownLatch(expectedMessages);
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();
        loggerConfig = config.getLoggerConfig(LogManager.getLogger(classThatLogs).getName());
        loggerConfig.addAppender(this, Level.ALL, ThresholdFilter.createFilter(Level.ALL, null, null));
        start();
    }

    @Override
    public void append(LogEvent event) {
        messages.add(event);
        latch.countDown();
    }

    public List<LogEvent> awaitMessages() throws InterruptedException {
        assertTrue(latch.await(10, TimeUnit.SECONDS));
        return messages;
    }

    @Override
    public void close() {
        stop();
        loggerConfig.removeAppender(this.getName());
    }
}

Use it like this:

        try (LatchedAppender appender = new LatchedAppender(ClassUnderTest.class, 1)) {

        ClassUnderTest.methodThatLogs();
        List<LogEvent> events = appender.awaitMessages();
        assertEquals(1, events.size());
        //more assertions here

    }//appender removed

Set transparent background of an imageview on Android

Use the following for complete transparency:

#00000000

When I tried with #80000000 I got a black transparent overlay which I don't want. Try to change the first two digits; it controls the level of transparency, like

#00000000
#10000000
#20000000
#30000000

How do I lowercase a string in C?

If you need Unicode support in the lower case function see this question: Light C Unicode Library

git checkout all the files

  • If you are in base directory location of your tracked files then git checkout . will works otherwise it won't work

Android TabLayout Android Design

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
    xmlns:app="http://schemas.android.com/apk/res-auto"_x000D_
    xmlns:tools="http://schemas.android.com/tools"_x000D_
    android:id="@+id/main_content"_x000D_
    android:layout_width="match_parent"_x000D_
    android:layout_height="match_parent"_x000D_
    android:fitsSystemWindows="true"_x000D_
    tools:context=".ui.MainActivity"_x000D_
    >_x000D_
    <android.support.design.widget.AppBarLayout_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">_x000D_
_x000D_
        <android.support.v7.widget.Toolbar_x000D_
            android:id="@+id/toolbar"_x000D_
            android:layout_width="match_parent"_x000D_
            android:layout_height="wrap_content"_x000D_
            android:layout_alignParentTop="true"_x000D_
            android:background="?attr/colorPrimary"_x000D_
            android:elevation="6dp"_x000D_
            android:minHeight="?attr/actionBarSize"_x000D_
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"_x000D_
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />_x000D_
_x000D_
        <android.support.design.widget.TabLayout_x000D_
            android:id="@+id/tabs"_x000D_
            android:layout_width="match_parent"_x000D_
            android:layout_height="wrap_content"_x000D_
            app:tabMode="fixed"_x000D_
            app:tabGravity="fill"_x000D_
            >_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_1" />_x000D_
_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem2"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_2" />_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem3"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_3" />_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tItemab4"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_4" />_x000D_
        </android.support.design.widget.TabLayout>_x000D_
    </android.support.design.widget.AppBarLayout>_x000D_
    <android.support.v4.view.ViewPager_x000D_
        android:id="@+id/container"_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="match_parent"_x000D_
        android:layout_below="@id/tabs"_x000D_
        app:layout_behavior="@string/appbar_scrolling_view_behavior"_x000D_
        tools:ignore="NotSibling"/>_x000D_
</android.support.constraint.ConstraintLayout>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
    xmlns:tools="http://schemas.android.com/tools"_x000D_
    android:id="@+id/activity_main"_x000D_
    android:layout_width="match_parent"_x000D_
    android:layout_height="match_parent"_x000D_
    tools:context=".ui.MainActivity">_x000D_
    <include layout="@layout/tabs"></include>_x000D_
    <LinearLayout_x000D_
        android:orientation="vertical"_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="match_parent"_x000D_
        android:layout_marginBottom="@dimen/activity_vertical_margin"_x000D_
        android:layout_marginLeft="@dimen/activity_horizontal_margin"_x000D_
        android:layout_marginRight="@dimen/activity_horizontal_margin"_x000D_
        android:layout_marginTop="80dp">_x000D_
        <FrameLayout android:id="@+id/tabContent"_x000D_
            android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp">_x000D_
        </FrameLayout>_x000D_
    </LinearLayout>_x000D_
</RelativeLayout>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
public class MainActivity extends  AppCompatActivity{_x000D_
_x000D_
  private Toolbar toolbar;_x000D_
    private TabLayout tabLayout;_x000D_
    private ViewPagerAdapter adapter;_x000D_
_x000D_
    private final static int[] tabIcons = {_x000D_
            R.drawable.ic_action_car,_x000D_
            android.R.drawable.ic_menu_mapmode,_x000D_
            android.R.drawable.ic_dialog_email,_x000D_
            R.drawable.ic_action_settings_x000D_
    };_x000D_
_x000D_
protected void onCreate(Bundle savedInstanceState) {_x000D_
        super.onCreate(savedInstanceState);_x000D_
        setContentView(R.layout.activity_main);_x000D_
        _x000D_
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);_x000D_
       setSupportActionBar(toolbar);_x000D_
_x000D_
        ViewPager viewPager = (ViewPager)         findViewById(R.id.container);_x000D_
        setupViewPager(viewPager);_x000D_
_x000D_
_x000D_
        tabLayout = (TabLayout) findViewById(R.id.tabs);_x000D_
        tabLayout.setupWithViewPager(viewPager);_x000D_
        setupTabIcons();_x000D_
_x000D_
        _x000D_
        }_x000D_
            private void setupTabIcons() {_x000D_
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);_x000D_
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);_x000D_
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);_x000D_
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);_x000D_
    }_x000D_
_x000D_
    private void setupViewPager(ViewPager viewPager) {_x000D_
        adapter = new ViewPagerAdapter(getSupportFragmentManager());_x000D_
        adapter.addFrag(new CarFragment());_x000D_
        adapter.addFrag(new LocationFragment());_x000D_
        adapter.addFrag(new MessageFragment());_x000D_
        adapter.addFrag(new SettingsFragment());_x000D_
        viewPager.setAdapter(adapter);_x000D_
    }_x000D_
    _x000D_
    class ViewPagerAdapter extends FragmentPagerAdapter {_x000D_
        private final List<Fragment> mFragmentList = new ArrayList<>();_x000D_
        ViewPagerAdapter(FragmentManager manager) {_x000D_
            super(manager);_x000D_
        }_x000D_
_x000D_
        @Override_x000D_
        public Fragment getItem(int position) {_x000D_
            return mFragmentList.get(position);_x000D_
        }_x000D_
_x000D_
        @Override_x000D_
        public int getCount() {_x000D_
            return mFragmentList.size();_x000D_
        }_x000D_
_x000D_
        void addFrag(Fragment fragment) {_x000D_
            mFragmentList.add(fragment);_x000D_
_x000D_
        }_x000D_
_x000D_
    }_x000D_
        }
_x000D_
_x000D_
_x000D_

MySQL WHERE: how to write "!=" or "not equals"?

You may be using old version of Mysql but surely you can use

 DELETE FROM konta WHERE taken <> ''

But there are many other options available. You can try the following ones

DELETE * from konta WHERE strcmp(taken, '') <> 0;

DELETE * from konta where NOT (taken = '');

Where is Java's Array indexOf?

Arrays themselves do not have that method. A List, however, does: indexOf

Is there an easy way to add a border to the top and bottom of an Android View?

I've used a trick so that the border is displayed outside the container. With this trick only a line is drawn so the background will be shown of the underlying view.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:bottom="1dp"
        android:left="-2dp"
        android:right="-2dp"
        android:top="-2dp">
        <shape android:shape="rectangle" >
            <stroke
                android:width="1dp"
                android:color="#FF000000" />

            <solid android:color="#00FFFFFF" />

            <padding android:left="10dp"
                android:right="10dp"
                android:top="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

</layer-list>

EPPlus - Read Excel Table

Working solution with validate email,mobile number

 public class ExcelProcessing
        {
            public List<ExcelUserData> ReadExcel()
            {
                string path = Config.folderPath + @"\MemberUploadFormat.xlsx";
    
                using (var excelPack = new ExcelPackage())
                {
                    //Load excel stream
                    using (var stream = File.OpenRead(path))
                    {
                        excelPack.Load(stream);
                    }
    
                    //Lets Deal with first worksheet.(You may iterate here if dealing with multiple sheets)
                    var ws = excelPack.Workbook.Worksheets[0];
    
                    List<ExcelUserData> userList = new List<ExcelUserData>();
    
                    int colCount = ws.Dimension.End.Column;  //get Column Count
                    int rowCount = ws.Dimension.End.Row;
                       
                    for (int row = 2; row <= rowCount; row++) // start from to 2 omit header
                    {
                       
                        bool IsValid = true;
                        ExcelUserData _user = new ExcelUserData();
    
                        for (int col = 1; col <= colCount; col++)
                        {
                            if (col == 1)
                            {
                                _user.FirstName = ws.Cells[row, col].Value?.ToString().Trim();
                                if (string.IsNullOrEmpty(_user.FirstName))
                                {
                                    _user.ErrorMessage += "Enter FirstName <br/>";
                                    IsValid = false;
                                }
                            }
                            else if (col == 2)
                            {
                                _user.Email = ws.Cells[row, col].Value?.ToString().Trim();
    
                                if (string.IsNullOrEmpty(_user.Email))
                                {
                                    _user.ErrorMessage += "Enter Email <br/>";
                                    IsValid = false;
                                }
                                else if (!IsValidEmail(_user.Email))
                                {
                                    _user.ErrorMessage += "Invalid Email Address <br/>";
                                    IsValid = false;
                                }
                            }
                            else if (col ==3)
                            {
                                _user.MobileNo = ws.Cells[row, col].Value?.ToString().Trim();
    
                                if (string.IsNullOrEmpty(_user.MobileNo))
                                {
                                    _user.ErrorMessage += "Enter Mobile No <br/>";
                                    IsValid = false;
                                }
                                else if (_user.MobileNo.Length != 10)
                                {
                                    _user.ErrorMessage += "Invalid Mobile No <br/>";
                                    IsValid = false;
                                }
    
                            }
                            else if (col == 4)
                            {
                                _user.IsAdmin = ws.Cells[row, col].Value?.ToString().Trim();
    
                                if (string.IsNullOrEmpty(_user.IsAdmin))
                                {
                                    _user.IsAdmin = "0";
                                }
                            }
    
                            _user.IsValid = IsValid;
                        }
                        userList.Add(_user);
                    }
                    return userList;
                }
            }
            public static bool IsValidEmail(string email)
            {
                Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                 RegexOptions.CultureInvariant | RegexOptions.Singleline);
    
                return regex.IsMatch(email);
            }
        }

Delete/Reset all entries in Core Data?

Here is combined solution for purging Core Data.

- (void)deleteAllObjectsInCoreData
{
    NSArray *allEntities = self.managedObjectModel.entities;
    for (NSEntityDescription *entityDescription in allEntities)
    {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entityDescription];

        fetchRequest.includesPropertyValues = NO;
        fetchRequest.includesSubentities = NO;

        NSError *error;
        NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

        if (error) {
                NSLog(@"Error requesting items from Core Data: %@", [error localizedDescription]);
            }

        for (NSManagedObject *managedObject in items) {
            [self.managedObjectContext deleteObject:managedObject];
        }

        if (![self.managedObjectContext save:&error]) {
            NSLog(@"Error deleting %@ - error:%@", entityDescription, [error localizedDescription]);
        }
    }  
}

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The == operator tests value equivalence. The is operator tests object identity, and Python tests whether the two are really the same object (i.e., live at the same address in memory).

>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True

In this example, Python only created one string object, and both a and b refers to it. The reason is that Python internally caches and reuses some strings as an optimization. There really is just a string 'banana' in memory, shared by a and b. To trigger the normal behavior, you need to use longer strings:

>>> a = 'a longer banana'
>>> b = 'a longer banana'
>>> a == b, a is b
(True, False)

When you create two lists, you get two objects:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.

If a refers to an object and you assign b = a, then both variables refer to the same object:

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

Add to integers in a list

If you try appending the number like, say listName.append(4) , this will append 4 at last. But if you are trying to take <int> and then append it as, num = 4 followed by listName.append(num), this will give you an error as 'num' is of <int> type and listName is of type <list>. So do type cast int(num) before appending it.

Difference between wait and sleep

You are correct - Sleep() causes that thread to "sleep" and the CPU will go off and process other threads (otherwise known as context switching) wheras I believe Wait keeps the CPU processing the current thread.

We have both because although it may seem sensible to let other people use the CPU while you're not using it, actualy there is an overhead to context switching - depending on how long the sleep is for, it can be more expensive in CPU cycles to switch threads than it is to simply have your thread doing nothing for a few ms.

Also note that sleep forces a context switch.

Also - in general it's not possible to control context switching - during the Wait the OS may (and will for longer waits) choose to process other threads.

Gem Command not found

On Debian, Ubuntu or Linux Mint:

$ sudo apt-get install rubygems ruby-dev

On CentOS, Fedora or RHEL:

$ sudo yum install rubygems ruby-devel

How to filter multiple values (OR operation) in angularJS

The quickest solution that I've found is to use the filterBy filter from angular-filter, for example:

<input type="text" placeholder="Search by name or genre" ng-model="ctrl.search"/>   
<ul>
  <li ng-repeat="movie in ctrl.movies | filterBy: ['name', 'genre']: ctrl.search">
    {{movie.name}} ({{movie.genre}}) - {{movie.rating}}
  </li>
</ul>

The upside is that angular-filter is a fairly popular library (~2.6k stars on GitHub) which is still actively developed and maintained, so it should be fine to add it to your project as a dependency.

Getting a 'source: not found' error when using source in a bash script

If you're writing a bash script, call it by name:

#!/bin/bash

/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).

The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.

How to use GNU Make on Windows?

Although this question is old, it is still asked by many who use MSYS2.

I started to use it this year to replace CygWin, and I'm getting pretty satisfied.

To install make, open the MSYS2 shell and type the following commands:

# Update the package database and core system packages
pacman -Syu
# Close shell and open again if needed

# Update again
pacman -Su

# Install make
pacman -S make

# Test it (show version)
make -v

websocket closing connection automatically

You need to send ping messages from time to time. I think the default timeout is 300 seconds. Sending websocket ping/pong frame from browser

Add missing dates to pandas dataframe

You could use Series.reindex:

import pandas as pd

idx = pd.date_range('09-01-2013', '09-30-2013')

s = pd.Series({'09-02-2013': 2,
               '09-03-2013': 10,
               '09-06-2013': 5,
               '09-07-2013': 1})
s.index = pd.DatetimeIndex(s.index)

s = s.reindex(idx, fill_value=0)
print(s)

yields

2013-09-01     0
2013-09-02     2
2013-09-03    10
2013-09-04     0
2013-09-05     0
2013-09-06     5
2013-09-07     1
2013-09-08     0
...

What does "Use of unassigned local variable" mean?

The compiler isn't smart enough to know that at least one of your if blocks will be executed. Therefore, it doesn't see that variables like annualRate will be assigned no matter what. Here's how you can make the compiler understand:

if (creditPlan == "0")
{
    // ...
}
else if (creditPlan == "1")
{
    // ...
}
else if (creditPlan == "2")
{
    // ...
}
else
{
    // ...
}

The compiler knows that with an if/else block, one of the blocks is guaranteed to be executed, and therefore if you're assigning the variable in all of the blocks, it won't give the compiler error.

By the way, you can also use a switch statement instead of ifs to maybe make your code cleaner.

Copy Notepad++ text with formatting?

As the chosen answer is pretty old, and things changed, here is the new procedure, if you use 64 bits Notepad++. 64 bits version does not come with Plugin Manager nor NppExport. All details provided here.

To resume quickly, Plugin Manager is no longer develloped and NppExport can be found just here.

How to change the button color when it is active using bootstrap?

CSS has different pseudo selector by which you can achieve such effect. In your case you can use

:active : if you want background color only when the button is clicked and don't want to persist.

:focus: if you want background color untill the focus is on the button.

button:active{
    background:olive;
}

and

button:focus{
    background:olive;
}

JsFiddle Example

P.S.: Please don't give the number in Id attribute of html elements.

Java: is there a map function?

This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/

sequence(1, 2).map(toString); // lazily returns "1", "2"

Simple Pivot Table to Count Unique Values

UPDATE: You can do this now automatically with Excel 2013. I've created this as a new answer because my previous answer actually solves a slightly different problem.

If you have that version, then select your data to create a pivot table, and when you create your table, make sure the option 'Add this data to the Data Model' tickbox is check (see below).

Tick the box next to 'Add this data to the Data Model'

Then, when your pivot table opens, create your rows, columns and values normally. Then click the field you want to calculate the distinct count of and edit the Field Value Settings: Edit field value settings

Finally, scroll down to the very last option and choose 'Distinct Count.' Choose the option 'Distinct Count'

This should update your pivot table values to show the data you're looking for.

How to declare a constant map in Golang?

Your syntax is incorrect. To make a literal map (as a pseudo-constant), you can do:

var romanNumeralDict = map[int]string{
  1000: "M",
  900 : "CM",
  500 : "D",
  400 : "CD",
  100 : "C",
  90  : "XC",
  50  : "L",
  40  : "XL",
  10  : "X",
  9   : "IX",
  5   : "V",
  4   : "IV",
  1   : "I",
}

Inside a func you can declare it like:

romanNumeralDict := map[int]string{
...

And in Go there is no such thing as a constant map. More information can be found here.

Try it out on the Go playground.

How to add/update an attribute to an HTML element using JavaScript?

What do you want to do with the attribute? Is it an html attribute or something of your own?

Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

Run R script from command line

This does not answer the question directly. But someone may end up here because they want to run a oneliner of R from the terminal. For example, if you just want to install some missing packages and quit, this oneliner can be very convenient. I use it a lot when I suddenly find out that I miss some packages, and I want to install them to where I want.

  • To install to the default location:

    R -e 'install.packages(c("package1", "package2"))'
    
  • To install to a location that requires root privileges:

    R -e 'install.packages(c("package1", "package2"), lib="/usr/local/lib/R/site-library")' 
    

How can I disable mod_security in .htaccess file?

In .htaccess file at site root directory edit following line:

_x000D_
_x000D_
<ifmodule mod_security.c>_x000D_
_x000D_
SecFilterEngine Off_x000D_
SecFilterScanPOST Off_x000D_
_x000D_
</ifmodule>_x000D_
_x000D_
<IfModule mod_rewrite.c>_x000D_
RewriteEngine On_x000D_
RewriteBase /_x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
RewriteCond %{REQUEST_FILENAME} !-d_x000D_
RewriteRule . /index.php [L]_x000D_
</IfModule>
_x000D_
_x000D_
_x000D_

Just keep the mod_security rules like SecFilterEngine and parts apart from each other. Its works for apache server

How to convert unix timestamp to calendar date moment.js

new moment(timeStamp,'yyyyMMddHHmmssfff').toDate()

Is an HTTPS query string secure?

I don't agree with the statement about [...] HTTP referrer leakage (an external image in the target page might leak the password) in Slough's response.

The HTTP 1.1 RFC explicitly states:

Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP request if the referring page was transferred with a secure protocol.

Anyway, server logs and browser history are more than sufficient reasons not to put sensitive data in the query string.

AutoComplete TextBox in WPF

I have published a WPF Auto Complete Text Box in WPF at CodePlex.com. You can download and try it from https://wpfautocomplete.codeplex.com/.

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<%
String session_val = (String)session.getAttribute("sessionval"); 
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Javascript - Regex to validate date format

Please find in the below code which enables to perform the date validation for any of the supplied format or based on user locale to validate start/from and end/to dates. There could be some better approaches but have come up with this. Have tested it for the formats like: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd and dd-MM-yyyy.

Note supplied date format and date string go hand in hand.

    <script type="text/javascript">
function validate(format) {

    if(isAfterCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is after the current date.');
    } else {
        alert('Date is not after the current date.');
    }
    if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is before current date.');
    } else {
        alert('Date is not before current date.');
    }
    if(isCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is current date.');
    } else {
        alert('Date is not a current date.');
    }
    if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('Start/Effective Date cannot be greater than End/Expiration Date');
    } else {
        alert('Valid dates...');
    }
    if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('End/Expiration Date cannot be less than Start/Effective Date');
    } else {
        alert('Valid dates...');
    }
    if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('Dates are equals...');
    } else {
        alert('Dates are not equals...');
    }
    if (isDate(document.getElementById('start').value, format)) {
        alert('Is valid date...');
    } else {
        alert('Is invalid date...');
    }
}

/**
 * This method gets the year index from the supplied format
 */
function getYearIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'YYYY'
            || tokens[0] === 'yyyy') {
        return 0;
    } else if (tokens[1]=== 'YYYY'
            || tokens[1] === 'yyyy') {
        return 1;
    } else if (tokens[2] === 'YYYY'
            || tokens[2] === 'yyyy') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the year string located at the supplied index
 */
function getYear(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method gets the month index from the supplied format
 */
function getMonthIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'MM'
            || tokens[0] === 'mm') {
        return 0;
    } else if (tokens[1] === 'MM'
            || tokens[1] === 'mm') {
        return 1;
    } else if (tokens[2] === 'MM'
            || tokens[2] === 'mm') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the month string located at the supplied index
 */
function getMonth(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method gets the date index from the supplied format
 */
function getDateIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'DD'
            || tokens[0] === 'dd') {
        return 0;
    } else if (tokens[1] === 'DD'
            || tokens[1] === 'dd') {
        return 1;
    } else if (tokens[2] === 'DD'
            || tokens[2] === 'dd') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the date string located at the supplied index
 */
function getDate(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method returns true if date1 is before date2 else return false
 */
function isBefore(date1, date2, format) {
    // Validating if date1 date is greater than the date2 date
    if (new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        > new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method returns true if date1 is after date2 else return false
 */
function isAfter(date1, date2, format) {
    // Validating if date2 date is less than the date1 date
    if (new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()
        < new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        ) {
        return true;
    } 
    return false;                
}

/**
 * This method returns true if date1 is equals to date2 else return false
 */
function isEquals(date1, date2, format) {
    // Validating if date1 date is equals to the date2 date
    if (new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        === new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()) {
        return true;
    } 
    return false;
}

/**
 * This method validates and returns true if the supplied date is 
 * equals to the current date.
 */
function isCurrentDate(date, format) {
    // Validating if the supplied date is the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        === new Date(new Date().getFullYear(), 
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method validates and returns true if the supplied date value 
 * is before the current date.
 */
function isBeforeCurrentDate(date, format) {
    // Validating if the supplied date is before the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        < new Date(new Date().getFullYear(), 
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method validates and returns true if the supplied date value 
 * is after the current date.
 */
function isAfterCurrentDate(date, format) {
    // Validating if the supplied date is before the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        > new Date(new Date().getFullYear(),
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method splits the supplied date OR format based 
 * on non alpha numeric characters in the supplied string.
 */
function splitDateFormat(dateFormat) {
    // Spliting the supplied string based on non characters
    return dateFormat.split(/\W/);
}

/*
 * This method validates if the supplied value is a valid date.
 */
function isDate(date, format) {                
    // Validating if the supplied date string is valid and not a NaN (Not a Number)
    if (!isNaN(new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))))) {                    
        return true;
    } 
    return false;                                      
}

Below is the HTML snippet

    <input type="text" name="start" id="start" size="10" value="05/31/2016" />
    <br/> 
    <input type="text" name="end" id="end" size="10" value="04/28/2016" />
    <br/>
    <input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />

How to get the selected radio button’s value?

I like to use brackets to get value from input, its way more clear than using dots.

document.forms['form_name']['input_name'].value;

Set Background color programmatically

I didn't understand your question ... what do you mean by "when i set every one of my colour"? try this (edit: "#fffff" in original answer changed to "#ffffff"

  yourView.setBackgroundColor(Color.parseColor("#ffffff"));

Getting Class type from String

Not sure what you are asking, but... Class.forname, maybe?

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Read a HTML file into a string variable in memory

Use File.ReadAllText(path_to_file) to read

How to use MySQL DECIMAL?

Although the answers above seems correct, just a simple explanation to give you an idea of how it works.

Suppose that your column is set to be DECIMAL(13,4). This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.

So, in summary, for that column you would have a max value of: 999999999.9999

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

Word wrapping in phpstorm

You have to enable Soft Wraps. Find that option through this path.

View > Active Editor > Use Soft Wraps

wrap words in PhpStorm

How to vertically center an image inside of a div element in HTML using CSS?

Let's say you want to put the image (40px X 40px) on the center (horizontal and vertical) of the div class="box". So you have the following html:

<div class="box"><img /></div>

What you have to do is apply the CSS:

.box img {
    position: absolute;
    top: 50%;
    margin-top: -20px;
    left: 50%;
    margin-left: -20px;
}

Your div can even change it's size, the image will always be on the center of it.

Adding space/padding to a UILabel

I have tried with it on Swift 4.2, hopefully it work for you!

@IBDesignable class PaddingLabel: UILabel {

    @IBInspectable var topInset: CGFloat = 5.0
    @IBInspectable var bottomInset: CGFloat = 5.0
    @IBInspectable var leftInset: CGFloat = 7.0
    @IBInspectable var rightInset: CGFloat = 7.0

    override func drawText(in rect: CGRect) {
        let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
        super.drawText(in: rect.inset(by: insets))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        return CGSize(width: size.width + leftInset + rightInset,
                      height: size.height + topInset + bottomInset)
    }   

    override var bounds: CGRect {
        didSet {
            // ensures this works within stack views if multi-line
            preferredMaxLayoutWidth = bounds.width - (leftInset + rightInset)
        }
    } 
}

Or you can use CocoaPods here https://github.com/levantAJ/PaddingLabel

pod 'PaddingLabel', '1.2'

enter image description here

Single Page Application: advantages and disadvantages

Disadvantages: Technically, design and initial development of SPA is complex and can be avoided. Other reasons for not using this SPA can be:

  • a) Security: Single Page Application is less secure as compared to traditional pages due to cross site scripting(XSS).
  • b) Memory Leak: Memory leak in JavaScript can even cause powerful Computer to slow down. As traditional websites encourage to navigate among pages, thus any memory leak caused by previous page is almost cleansed leaving less residue behind.
  • c) Client must enable JavaScript to run SPA, but in multi-page application JavaScript can be completely avoided.
  • d) SPA grows to optimal size, cause long waiting time. Eg: Working on Gmail with slower connection.

Apart from above, other architectural limitations are Navigational Data loss, No log of Navigational History in browser and difficulty in Automated Functional Testing with selenium.

This link explain Single Page Application's Advantages and Disadvantages.

Angular 2: import external js file into component

You can also try this:

import * as drawGauge from '../../../../js/d3gauge.js';

and just new drawGauge(this.opt); in your ts-code. This solution works in project with angular-cli embedded into laravel on which I currently working on. In my case I try to import poliglot library (btw: very good for translations) from node_modules:

import * as Polyglot from '../../../node_modules/node-polyglot/build/polyglot.min.js';
...
export class Lang 
{
    constructor() {

        this.polyglot = new Polyglot({ locale: 'en' });
        ...
    }
    ...
}

This solution is good because i don't need to COPY any files from node_modules :) .

UPDATE

You can also look on this LIST of ways how to include libs in angular.

Interface vs Base class

When should I use an interface and when should I use a base class?

You should use interface if

  1. You have pure abstract methods and don't have non-abstract methods
  2. You don't have default implementation of non abstract methods (except for Java 8 language, where interface methods provides default implementation)
  3. If you are using Java 8, now interface will provide default implementation for some non-abstract methods. This will make interface more usable compared to abstract classes.

Have a look at this SE question for more details.

Should it always be an interface if I don't want to actually define a base implementation of the methods?

Yes. It's better and cleaner. Even if you have a base class with some abstract methods, let's base class extends abstract methods through interface. You can change interface in future without changing the base class.

Example in java:

abstract class PetBase implements IPet {
// Add all abstract methods in IPet interface and keep base class clean. 
   Base class will contain only non abstract methods and static methods.
}

If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.

I prefer to have base class implement the interface.

 abstract class PetBase implements IPet {
 // Add all abstract methods in IPet
 }

 /*If ISheds,IBarks is common for Pets, your PetBase can implement ISheds,IBarks. 
  Respective implementations of PetBase can change the behaviour in their concrete classes*/

 abstract class PetBase implements IPet,ISheds,IBarks {
 // Add all abstract methods in respective interfaces
 }

Advantages:

  1. If I want to add one more abstract method in existing interfaces, I simple change interface without touching the abstract base class. If I want to change the contract, I will change interface & implementation classes without touching base class.

  2. You can provide immutability to base class through interface. Have a look at this article

Refer to this related SE question for more details:

How should I have explained the difference between an Interface and an Abstract class?

How to check SQL Server version

Here is what i have done to find the version Here is what i have done to find the version: just write SELECT @@version and it will give you the version.

In Python how should I test if a variable is None, True or False

if result is None:
    print "error parsing stream"
elif result:
    print "result pass"
else:
    print "result fail"

keep it simple and explicit. You can of course pre-define a dictionary.

messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]

If you plan on modifying your simulate function to include more return codes, maintaining this code might become a bit of an issue.

The simulate might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.

How to launch Windows Scheduler by command-line?

If you’re asking what I think you’re asking, you can open it by executing this:

explorer.exe "C:\WINDOWS\Tasks\"

Trim leading and trailing spaces from a string in awk

remove leading and trailing white space in 2nd column

awk 'BEGIN{FS=OFS=","}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2)}1' input.txt

another way by one gsub:

awk 'BEGIN{FS=OFS=","} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' infile

Center Triangle at Bottom of Div

You could also use a CSS "calc" to get the same effect instead of using the negative margin or transform properties (in case you want to use those properties for anything else).

.hero:after,
.hero:after {
    z-index: -1;
    position: absolute;
    top: 98.1%;
    left: calc(50% - 25px);
    content: '';
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

Warning - Build path specifies execution environment J2SE-1.4

the correct procedure to resolve this warning, as other people write, is to go inside your project Properties and click on Java Build Path located on the left. Now you will find inside the Libraries Window the J2SE 1.5, double click on this one and a new window will give you the possibility to choose the correct Excecution Environment. Now select your version and the warning will disappear.

What exactly is the difference between Web API and REST API in MVC?

I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.

REST

It is neither an API nor a framework. It is just an architectural concept. You can find more details here.

RESTful

I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.

EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.

Web API

It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

How to normalize a vector in MATLAB efficiently? Any related built-in function?

By the rational of making everything multiplication I add the entry at the end of the list

    clc; clear all;
    V = rand(1024*1024*32,1);
    N = 10;
    tic; for i=1:N, V1 = V/norm(V);         end; toc % 4.5 s
    tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 7.5 s
    tic; for i=1:N, V3 = V/sqrt(V'*V);      end; toc % 4.9 s
    tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 6.8 s
    tic; for i=1:N, V1 = V/norm(V);         end; toc % 4.7 s
    tic; for i=1:N, d = 1/norm(V); V1 = V*d;end; toc % 4.9 s
    tic; for i=1:N, d = norm(V)^-1; V1 = V*d;end;toc % 4.4 s

Passing multiple values to a single PowerShell script parameter

Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:

param(
    [Parameter(Position = 0)]
    [string[]]$Hosts,
    [string]$VLAN
    )

foreach ($i in $Hosts)  
{ 
    Do-Stuff $i
}

Then call it like:

.\script.ps1 host1, host2, host3 -VLAN 2

Notice the comma between the values. This collects them in an array

How to parse an RSS feed using JavaScript?

If you want to use a plain javascript API, there is a good example at https://github.com/hongkiat/js-rss-reader/

The complete description at https://www.hongkiat.com/blog/rss-reader-in-javascript/

It uses fetch method as a global method that asynchronously fetches a resource. Below is a snap of code:

fetch(websiteUrl).then((res) => {
  res.text().then((htmlTxt) => {
    var domParser = new DOMParser()
    let doc = domParser.parseFromString(htmlTxt, 'text/html')
    var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
  })
}).catch(() => console.error('Error in fetching the website'))

How to remove a file from the index in git?

You want:

git rm --cached [file]

If you omit the --cached option, it will also delete it from the working tree. git rm is slightly safer than git reset, because you'll be warned if the staged content doesn't match either the tip of the branch or the file on disk. (If it doesn't, you have to add --force.)

Force to open "Save As..." popup open at text link click for PDF in HTML

If you have a plugin within the browser which knows how to open a PDF file it will open directly. Like in case of images and HTML content.

So the alternative approach is not to send your MIME type in the response. In this way the browser will never know which plugin should open it. Hence it will give you a Save/Open dialog box.

Strange "java.lang.NoClassDefFoundError" in Eclipse

Stab in the dark, but I was having the same exact issue. I solved it by deleting the project from my workspace (be careful not to delete from disk), and then re-imported the project and it worked fine. I think mine was caused by a bad windows shutdown (restarting windows correctly did not correct the issue). HTH.

JQuery wait for page to finish loading before starting the slideshow?

did you try this ?

$("#yourdiv").load(url, function(){ 

         your functions goes here !!!

}); 

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join

Build .NET Core console application to output an EXE

Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args].

Of course this assumes that .NET is installed on the target machine.

Here's the code. Feel free to copy!

using System;
using System.Diagnostics;
using System.Text;

namespace dotNetLauncher
{
    class Program
    {
        /*
            If you make .NET Core applications, they have to be launched like .NET blah.dll args here
            This is a convenience EXE file that launches .NET Core applications via name.exe
            Just rename the output exe to the name of the .NET Core DLL file you wish to launch
        */
        static void Main(string[] args)
        {
            var exePath = AppDomain.CurrentDomain.BaseDirectory;
            var exeName = AppDomain.CurrentDomain.FriendlyName;
            var assemblyName = exeName.Substring(0, exeName.Length - 4);
            StringBuilder passInArgs = new StringBuilder();
            foreach(var arg in args)
            {
                bool needsSurroundingQuotes = false;
                if (arg.Contains(" ") || arg.Contains("\""))
                {
                    passInArgs.Append("\"");
                    needsSurroundingQuotes = true;
                }
                passInArgs.Append(arg.Replace("\"","\"\""));
                if (needsSurroundingQuotes)
                {
                    passInArgs.Append("\"");
                }

                passInArgs.Append(" ");
            }
            string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";

            var p = new Process
            {
                StartInfo = new ProcessStartInfo("dotnet", callingArgs)
                {
                    UseShellExecute = false
                }
            };

            p.Start();
            p.WaitForExit();
        }
    }
}

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

I've found this easy solution

To convert from bitmap to Base64 use this method.

private String convertBitmapToBase64(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream .toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

To convert from Base64 to bitmap OR revert.

private Bitmap convertBase64ToBitmap(String b64) {
    byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}

Is there an easy way to convert jquery code to javascript?

This will get you 90% of the way there ; )

window.$ = document.querySelectorAll.bind(document)

For Ajax, the Fetch API is now supported on the current version of every major browser. For $.ready(), DOMContentLoaded has near universal support. You Might Not Need jQuery gives equivalent native methods for other common jQuery functions.

Zepto offers similar functionality but weighs in at 10K zipped. There are custom Ajax builds for jQuery and Zepto as well as some micro frameworks, but jQuery/Zepto have solid support and 10KB is only ~1 second on a 56K modem.

How can I change CSS display none or block property using jQuery?

Other way to do it using jQuery CSS method:

$("#id").css({display: "none"});
$("#id").css({display: "block"});

Django: OperationalError No Such Table

If anyone finds that any of the suggested:

python manage.py makemigrations

python manage.py migrate

python manage.py migrate --run-syncdb

fail, you may need to add a folder named "migrations" inside the app directory, and create an empty __init__.py file.

What is the Python equivalent for a case/switch statement?

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

MYSQL query between two timestamps

SELECT * FROM `orders` WHERE `order_date_time`  BETWEEN 1534809600 AND 1536718364

ArrayList or List declaration in Java

It is easy to change the implementation to List to Set:

Collection<String> stringList = new ArrayList<String>();
//Client side
stringList = new LinkedList<String>();

stringList = new HashSet<String>();
//stringList = new HashSet<>(); java 1.7 and 1.8

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

Round a divided number in Bash

I think this should be enough.

$ echo "3/2" | bc 

How to assert two list contain the same elements in Python?

Given

l1 = [a,b]
l2 = [b,a]

In Python >= 3.0

assertCountEqual(l1, l2) # True

In Python >= 2.7, the above function was named:

assertItemsEqual(l1, l2) # True

In Python < 2.7

import unittest2
assertItemsEqual(l1, l2) # True

Via six module (Any Python version)

import unittest
import six
class MyTest(unittest.TestCase):
    def test(self):
        six.assertCountEqual(self, self.l1, self.l2) # True

How do I convert a string to enum in TypeScript?

If you provide string values to your enum, a straight cast works just fine.

enum Color {
  Green = "Green",
  Red = "Red"
}

const color = "Green";
const colorEnum = color as Color;

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

How to highlight a current menu item?

The route:

$routeProvider.when('/Account/', { templateUrl: '/Home/Account', controller: 'HomeController' });

The menu html:

<li id="liInicio" ng-class="{'active':url=='account'}">

The controller:

angular.module('Home').controller('HomeController', function ($scope, $http, $location) {
    $scope.url = $location.url().replace(/\//g, "").toLowerCase();
...

The problem I found here is that the menu item is active only when the full page is loaded. When the partial view is loaded the menu doesn't change. Somebody knows why it happens?

How to return a string value from a Bash function

You can echo a string, but catch it by piping (|) the function to something else.

You can do it with expr, though ShellCheck reports this usage as deprecated.

Cannot open new Jupyter Notebook [Permission Denied]

In my opinion, it is a good practice to run Jupyter in a dedicated workbook folder.

$ mkdir jupyter_folder
$ jupyter-notebook --notebook-dir jupyter_folder

where 'jupyter_folder' is a folder in my home.

This method work without permission issue.

Why can't Python parse this JSON data?

Your data is not valid JSON format. You have [] when you should have {}:

  • [] are for JSON arrays, which are called list in Python
  • {} are for JSON objects, which are called dict in Python

Here's how your JSON file should look:

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": {
        "id": "valore"
    },
    "om_points": "value",
    "parameters": {
        "id": "valore"
    }
}

Then you can use your code:

import json
from pprint import pprint

with open('data.json') as f:
    data = json.load(f)

pprint(data)

With data, you can now also find values like so:

data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]

Try those out and see if it starts to make sense.

What is the equivalent of ngShow and ngHide in Angular 2+?

According to Angular 1 documentation of ngShow and ngHide, both of these directive adds the css style display: none !important;, to the element according to the condition of that directive (for ngShow adds the css on false value, and for ngHide adds the css for true value).

We can achieve this behavior using Angular 2 directive ngClass:

/* style.css */
.hide 
{
    display: none !important;
}

<!-- old angular1 ngShow -->
<div ng-show="ngShowVal"> I'm Angular1 ngShow... </div>

<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': !ngShowVal }"> I'm Angular2 ngShow... </div>

<!-- old angular2 ngHide -->
<div ng-hide="ngHideVal"> I'm Angular1 ngHide... </div>

<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': ngHideVal }"> I'm Angular2 ngHide... </div>

Notice that for show behavior in Angular2 we need to add ! (not) before the ngShowVal, and for hide behavior in Angular2 we don't need to add ! (not) before the ngHideVal.

Count number of days between two dates

def business_days_between(date1, date2)
  business_days = 0
  date = date2
  while date > date1
   business_days = business_days + 1 unless date.saturday? or date.sunday?
   date = date - 1.day
  end
  business_days
end

how to release localhost from Error: listen EADDRINUSE

The aforementioned killall -9 node, suggested by Patrick works as expected and solves the problem but you may want to read the edit part of this very answer about why kill -9 may not be the best way to do it.

On top of that you might want to target a single process rather than blindly killing all active processes.

In that case, first get the process ID (PID) of the process running on that port (say 8888):

lsof -i tcp:8888

This will return something like:

COMMAND   PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node     57385   You   11u  IPv6 0xac745b2749fd2be3      0t0  TCP *:ddi-tcp-1

(LISTEN) Then just do (ps - actually do not. Please keep reading below):

kill -9 57385

Directory.GetFiles: how to get only filename, not full path?

Have a look at using FileInfo.Name Property

something like

string[] files = Directory.GetFiles(dir); 

for (int iFile = 0; iFile < files.Length; iFile++)
    string fn = new FileInfo(files[iFile]).Name;

Also have a look at using DirectoryInfo Class and FileInfo Class

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

I was facing same error. I have configured slf4j-api, slf4j-log4j12 and log4j, in my local development. All configuration was fine, but slf4j-log4j12 dependency which I copied from mvnrepository had test scope <scope>test</scope>. When I removed this every thing is fine.

Some times silly mistakes breaks our head ;)

How can I output UTF-8 from Perl?

TMTOWTDI, chose the method that best fits how you work. I use the environment method so I don't have to think about it.

In the environment:

export PERL_UNICODE=SDL

on the command line:

perl -CSDL -le 'print "\x{1815}"';

or with binmode:

binmode(STDOUT, ":utf8");          #treat as if it is UTF-8
binmode(STDIN, ":encoding(utf8)"); #actually check if it is UTF-8

or with PerlIO:

open my $fh, ">:utf8", $filename
    or die "could not open $filename: $!\n";

open my $fh, "<:encoding(utf-8)", $filename
    or die "could not open $filename: $!\n";

or with the open pragma:

use open ":encoding(utf8)";
use open IN => ":encoding(utf8)", OUT => ":utf8";

What is the best way to know if all the variables in a Class are null?

This can be done fairly easily using a Lombok generated equals and a static EMPTY object:

import lombok.Data;

public class EmptyCheck {
    public static void main(String[] args) {
        User user1 = new User();

        User user2 = new User();
        user2.setName("name");

        System.out.println(user1.isEmpty()); // prints true
        System.out.println(user2.isEmpty()); // prints false
    }

    @Data
    public static class User {
        private static final User EMPTY = new User();

        private String id;
        private String name;
        private int age;

        public boolean isEmpty() {
            return this.equals(EMPTY);
        }
    }
}

Prerequisites:

  • Default constructor should not be implemented with custom behavior as that is used to create the EMPTY object
  • All fields of the class should have an implemented equals (built-in Java types are usually not a problem, in case of custom types you can use Lombok)

Advantages:

  • No reflection involved
  • As new fields added to the class, this does not require any maintenance as due to Lombok they will be automatically checked in the equals implementation
  • Unlike some other answers this works not just for null checks but also for primitive types which have a non-null default value (e.g. if field is int it checks for 0, in case of boolean for false, etc.)

Stretch Image to Fit 100% of Div Height and Width

You're mixing notations. It should be:

<img src="folder/file.jpg" width="200" height="200">

(note, no px). Or:

<img src="folder/file.jpg" style="width: 200px; height: 200px;">

(using the style attribute) The style attribute could be replaced with the following CSS:

#mydiv img {
    width: 200px;
    height: 200px;
}

or

#mydiv img {
    width: 100%;
    height: 100%;
}

Sort a List of objects by multiple fields

You have to write your own compareTo() method that has the Java code needed to perform the comparison.

If we wanted for example to compare two public fields, campus, then faculty, we might do something like:

int compareTo(GraduationCeremony gc)
{
    int c = this.campus.compareTo(gc.campus);

    if( c != 0 )
    {
        //sort by campus if we can
        return c;
    }
    else
    {
        //campus equal, so sort by faculty
        return this.faculty.compareTo(gc.faculty);
    }
}

This is simplified but hopefully gives you an idea. Consult the Comparable and Comparator docs for more info.

How to compare a local git branch with its remote branch?

tl;dr: git diff <local branch> <remote branch>

When using git on the shell, I like to first orient myself by looking around. Here's a command to show all branches

$ git branch -a  # (or git branch --all) 
* my-branch
  master
  remotes/origin/some-branch
  remotes/origin/HEAD -> origin/master
  remotes/origin/my-branch
  remotes/origin/some-other-branch
  remotes/origin/master

Here I have two local branches (my-branch and master) and 4 remote (some-branch, some-other-branch, master, and my-branch).

Also, the asterisk next to my-branch signals the fact that I'm currently in that branch (you would also know that by using the command git status that would output: On branch my-branch.).

Note: the remote branches in the git bash shell are shown in red while the local ones are shown in green.

If you just want to show remote branches:

$ git branch -r # (or git branch --remotes)
  origin/some-branch
  origin/HEAD -> origin/master
  origin/my-branch
  origin/some-other-branch
  origin/master

To show just local branches you might be tempted to use git branch -l but that's a completely different command. To show local branches use git branch with no options

$ git branch
* my-branch 
  master

To complete a review of the basic branch options there's the --list that contrary to what you might expect is there to allow filtering. Use it with a pattern like this:

$ git branch --list 'my*'
* my-branch

You can also combine --list with the options -a and -r but make sure to adapt your pattern accordingly (remember: remote branches start with "remotes"). Example:

# this will show all branches (local & remote) that start with my
$ git branch --list 'my*' -a
* my-branch

# better: the pattern includes the remote
$ git branch --list '*my*' -a
* my-branch
  remotes/origin/my-branch

Docs: https://git-scm.com/docs/git-branch

Now you can compare any two branches from all the available ones (you can also compare two locals or two remotes).

Here I'm comparing the local with the remote my-branch, they're synchronized so I don't get any output:

$ git diff my-branch remotes/origin/my-branch

Note: you have to give the full names of the branches with no quotation marks.

I can also compare the local my-branch to the remote master. Here I get some output because the remote my-branch hasn't been merged into the master branch.

$ git diff my-branch remotes/origin/master
diff --git a/src/controllers/call.controller.js b/src/controllers/call.controller.js
index fd79b98..df3d798 100644
--- a/src/controllers/call.controller.js
+++ b/src/controllers/call.controller.js
@@ -261,7 +261,7 @@ function callController() {
   /*
    *  Function: doCall
[ . . . ]

How to check if a character in a string is a digit or letter

char charInt=character.charAt(0);   
if(charInt>=48 && charInt<=57){
    System.out.println("not character");
}
else
    System.out.println("Character");

Look for ASCII table to see how the int value are hardcoded .

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

Update Item to Revision vs Revert to Revision

The text from the Tortoise reference:

Update item to revision Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent.

If you want to undo an earlier change permanently, use Revert to this revision instead.

Revert to this revision Revert to an earlier revision. If you have made several changes, and then decide that you really want to go back to how things were in revision N, this is the command you need. The changes are undone in your working copy so this operation does not affect the repository until you commit the changes. Note that this will undo all changes made after the selected revision, replacing the file/folder with the earlier version.

If your working copy is in an unmodified state, after you perform this action your working copy will show as modified. If you already have local changes, this command will merge the undo changes into your working copy.

What is happening internally is that Subversion performs a reverse merge of all the changes made after the selected revision, undoing the effect of those previous commits.

If after performing this action you decide that you want to undo the undo and get your working copy back to its previous unmodified state, you should use TortoiseSVN ? Revert from within Windows Explorer, which will discard the local modifications made by this reverse merge action.

If you simply want to see what a file or folder looked like at an earlier revision, use Update to revision or Save revision as... instead.

On - window.location.hash - Change?

There are a lot of tricks to deal with History and window.location.hash in IE browsers:

  • As original question said, if you go from page a.html#b to a.html#c, and then hit the back button, the browser doesn't know that page has changed. Let me say it with an example: window.location.href will be 'a.html#c', no matter if you are in a.html#b or a.html#c.

  • Actually, a.html#b and a.html#c are stored in history only if elements '<a name="#b">' and '<a name="#c">' exists previously in the page.

  • However, if you put an iframe inside a page, navigate from a.html#b to a.html#c in that iframe and then hit the back button, iframe.contentWindow.document.location.href changes as expected.

  • If you use 'document.domain=something' in your code, then you can't access to iframe.contentWindow.document.open()' (and many History Managers does that)

I know this isn't a real response, but maybe IE-History notes are useful to somebody.

.bashrc: Permission denied

If you want to edit that file (or any file in generally), you can't edit it simply writing its name in terminal. You must to use a command to a text editor to do this. For example:

nano ~/.bashrc

or

gedit ~/.bashrc

And in general, for any type of file:

xdg-open ~/.bashrc

Writing only ~/.bashrc in terminal, this will try to execute that file, but .bashrc file is not meant to be an executable file. If you want to execute the code inside of it, you can source it like follow:

source ~/.bashrc

or simple:

. ~/.bashrc 

Git add all subdirectories

You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a.

To remove go to the subdirectory and rm .git -rf.

How to remove anaconda from windows completely?

On my machine (Win10), the uninstaller was located at C:\ProgramData\Anaconda3\Uninstall-Anaconda3.exe.

Cannot read property 'map' of undefined

I considered giving a comment under the answer by taggon to this very question, but well, i felt it owed more explanation for those interested in details.

Uncaught TypeError: Cannot read property 'value' of undefined is strictly a JavaScript error.
(Note that value can be anything, but for this question value is 'map')

It's critical to understand that point, just so you avoid endless debugging cycles.
This error is common especially if just starting out in JavaScript (and it's libraries/frameworks).
For React, this has a lot to do with understanding the component lifecycle methods.

// Follow this example to get the context
// Ignore any complexity, focus on how 'props' are passed down to children

import React, { useEffect } from 'react'

// Main component
const ShowList = () => {
  // Similar to componentDidMount and componentDidUpdate
  useEffect(() => {// dispatch call to fetch items, populate the redux-store})

  return <div><MyItems items={movies} /></div>
}

// other component
const MyItems = props =>
  <ul>
    {props.items.map((item, i) => <li key={i}>item</li>)}
  </ul>


/**
  The above code should work fine, except for one problem.
  When compiling <ShowList/>,
  React-DOM renders <MyItems> before useEffect (or componentDid...) is called.
  And since `items={movies}`, 'props.items' is 'undefined' at that point.
  Thus the error message 'Cannot read property map of undefined'
 */

As a way to tackle this problem, @taggon gave a solution (see first anwser or link).

Solution: Set an initial/default value.
In our example, we can avoid items being 'undefined' by declaring a default value of an empty array.

Why? This allows React-DOM to render an empty list initially.
And when the useEffect or componentDid... method is executed, the component is re-rendered with a populated list of items.

// Let's update our 'other' component
// destructure the `items` and initialize it as an array

const MyItems = ({items = []}) =>
  <ul>
    {items.map((item, i) => <li key={i}>item</li>)}
  </ul>

Python Remove last char from string and return it

Yes, python strings are immutable and any modification will result in creating a new string. This is how it's mostly done.

So, go ahead with it.

Insert a line at specific line number with sed or awk

Perl solutions:

quick and dirty:

perl -lpe 'print "Project_Name=sowstest" if $. == 8' file

  • -l strips newlines and adds them back in, eliminating the need for "\n"
  • -p loops over the input file, printing every line
  • -e executes the code in single quotes

$. is the line number

equivalent to @glenn's awk solution, using named arguments:

perl -slpe 'print $s if $. == $n' -- -n=8 -s="Project_Name=sowstest" file

  • -s enables a rudimentary argument parser
  • -- prevents -n and -s from being parsed by the standard perl argument parser

positional command arguments:

perl -lpe 'BEGIN{$n=shift; $s=shift}; print $s if $. == $n' 8 "Project_Name=sowstest" file

environment variables:

setenv n 8 ; setenv s "Project_Name=sowstest"
echo $n ; echo $s
perl -slpe 'print $ENV{s} if $. == $ENV{n}' file

ENV is the hash which contains all environment variables

Getopt to parse arguments into hash %o:

perl -MGetopt::Std -lpe 'BEGIN{getopt("ns",\%o)}; print $o{s} if $. == $o{n}' -- -n 8 -s "Project_Name=sowstest" file

Getopt::Long and longer option names

perl -MGetopt::Long -lpe 'BEGIN{GetOptions(\%o,"line=i","string=s")}; print $o{string} if $. == $o{line}' -- --line 8 --string "Project_Name=sowstest" file

Getopt is the recommended standard-library solution.
This may be overkill for one-line perl scripts, but it can be done

How do I schedule jobs in Jenkins?

*/5 * * * * means every 5 minutes

5 * * * * means the 5th minute of every hour

How to Convert UTC Date To Local time Zone in MySql Select Query

SELECT CONVERT_TZ() will work for that.but its not working for me.

Why, what error do you get?

SELECT CONVERT_TZ(displaytime,'GMT','MET');

should work if your column type is timestamp, or date

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_convert-tz

Test how this works:

SELECT CONVERT_TZ(a_ad_display.displaytime,'+00:00','+04:00');

Check your timezone-table

SELECT * FROM mysql.time_zone;
SELECT * FROM mysql.time_zone_name;

http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

If those tables are empty, you have not initialized your timezone tables. According to link above you can use mysql_tzinfo_to_sql program to load the Time Zone Tables. Please try this

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo

or if not working read more: http://dev.mysql.com/doc/refman/5.5/en/mysql-tzinfo-to-sql.html

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

Get environment value in controller

As @Rajib pointed out, You can't access your env variables using config('myVariable')

  1. You have to add the variable to .env file first.
  2. Add the variable to some config file in config directory. I usually add to config/app.php
  3. Once done, will access them like Config::get('fileWhichContainsVariable.Variable'); using the Config Facade

Probably You will have to clear config cache using php artisan config:clear AND you will also have to restart server.

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

How to read data when some numbers contain commas as thousand separator?

If number is separated by "." and decimals by "," (1.200.000,00) in calling gsub you must set fixed=TRUE as.numeric(gsub(".","",y,fixed=TRUE))

How to get a random number in Ruby

If you're not only seeking for a number but also hex or uuid it's worth mentioning that the SecureRandom module found its way from ActiveSupport to the ruby core in 1.9.2+. So without the need for a full blown framework:

require 'securerandom'

p SecureRandom.random_number(100) #=> 15
p SecureRandom.random_number(100) #=> 88

p SecureRandom.random_number #=> 0.596506046187744
p SecureRandom.random_number #=> 0.350621695741409

p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"

It's documented here: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)

Rolling or sliding window iterator?

I tested a few solutions and one I came up with and found the one I came up with to be the fastest so I thought I would share it.

import itertools
import sys

def windowed(l, stride):
    return zip(*[itertools.islice(l, i, sys.maxsize) for i in range(stride)])

$watch an object

Call $watch with true as the third argument:

$scope.$watch('form', function(newVal, oldVal){
    console.log('changed');
}, true);

By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal.

Per the Angular documentation, the third parameter is for objectEquality:

When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

Is it possible to sort a ES6 map object?

Unfortunately, not really implemented in ES6. You have this feature with OrderedMap.sort() from ImmutableJS or _.sortBy() from Lodash.

Accessing localhost of PC from USB connected Android mobile device

Problem I faced maybe it will help some one, I was working long time where my pc and android device connected to the same WiFi network and the android device connected via the IPV4 address of the pc with opened port 8080 trought the fire wall.

ONE DAY : I installed Genymotion emulator in order to debug UI on different screens. THANKS to Genymotion/Virtualbox network configurations it ruined my WiFi adapter.

The fix was to reconfigure IPV4/TCP settings on the WiFi netwrok adapter :

enter image description here

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

Invalidating JSON Web Tokens

If you want to be able to revoke user tokens, you can keep track of all issued tokens on your DB and check if they're valid (exist) on a session-like table. The downside is that you'll hit the DB on every request.

I haven't tried it, but i suggest the following method to allow token revocation while keeping DB hits to a minimum -

To lower the database checks rate, divide all issued JWT tokens into X groups according to some deterministic association (e.g., 10 groups by first digit of the user id).

Each JWT token will hold the group id and a timestamp created upon token creation. e.g., { "group_id": 1, "timestamp": 1551861473716 }

The server will hold all group ids in memory and each group will have a timestamp that indicates when was the last log-out event of a user belonging to that group. e.g., { "group1": 1551861473714, "group2": 1551861487293, ... }

Requests with a JWT token that have an older group timestamp, will be checked for validity (DB hit) and if valid, a new JWT token with a fresh timestamp will be issued for client's future use. If the token's group timestamp is newer, we trust the JWT (No DB hit).

So -

  1. We only validate a JWT token using the DB if the token has an old group timestamp, while future requests won't get validated until someone in the user's group will log-out.
  2. We use groups to limit the number of timestamp changes (say there's a user logging in and out like there's no tomorrow - will only affect limited number of users instead of everyone)
  3. We limit the number of groups to limit the amount of timestamps held in memory
  4. Invalidating a token is a breeze - just remove it from the session table and generate a new timestamp for the user's group.

How do I use Apache tomcat 7 built in Host Manager gui?

Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in

/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf (its called Catalina Base and is often hidden)

instead of the apacahe installation directory.

open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.

    <user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>

restart the server . That's all

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

includes() not working in all browsers

One more solution is to use contains which will return true or false

_.contains($(".right-tree").css("background-image"), "stage1")

Hope this helps

react button onClick redirect page

I was trying to find a way with Redirect but failed. Redirecting onClick is simpler than we think. Just place the following basic JavaScript within your onClick function, no monkey business:

window.location.href="pagelink"

Numpy - add row to array

If you can do the construction in a single operation, then something like the vstack-with-fancy-indexing answer is a fine approach. But if your condition is more complicated or your rows come in on the fly, you may want to grow the array. In fact the numpythonic way to do something like this - dynamically grow an array - is to dynamically grow a list:

A = np.array([[1,2,3],[4,5,6]])
Alist = [r for r in A]
for i in range(100):
    newrow = np.arange(3)+i
    if i%5:
        Alist.append(newrow)
A = np.array(Alist)
del Alist

Lists are highly optimized for this kind of access pattern; you don't have convenient numpy multidimensional indexing while in list form, but for as long as you're appending it's hard to do better than a list of row arrays.

How to make a machine trust a self-signed Java application

Just Go To *Startmenu >>Java >>Configure Java >> Security >> Edit site list >> copy and paste your Link with problem >> OK Problem fixed :)*

Cast IList to List

In my case I had to do this, because none of the suggested solutions were available:

List<SubProduct> subProducts = Model.subproduct.Cast<SubProduct>().ToList();

Get key and value of object in JavaScript?

If this is all the object is going to store, then best literal would be

var top_brands = {
    'Adidas' : 100,
    'Nike'   : 50
    };

Then all you need is a for...in loop.

for (var key in top_brands){
    console.log(key, top_brands[key]);
    }

Spark - load CSV file as DataFrame?

spark-csv is part of core Spark functionality and doesn't require a separate library. So you could just do for example

df = spark.read.format("csv").option("header", "true").load("csvfile.csv")

In scala,(this works for any format-in delimiter mention "," for csv, "\t" for tsv etc)

val df = sqlContext.read.format("com.databricks.spark.csv") .option("delimiter", ",") .load("csvfile.csv")

Efficiently replace all accented characters in a string?

I can't speak to what you are trying to do specifically with the function itself, but if you don't like the regex being built every time, here are two solutions and some caveats about each.

Here is one way to do this:

function makeSortString(s) {
  if(!makeSortString.translate_re) makeSortString.translate_re = /[öäüÖÄÜ]/g;
  var translate = {
    "ä": "a", "ö": "o", "ü": "u",
    "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
  };
  return ( s.replace(makeSortString.translate_re, function(match) { 
    return translate[match]; 
  }) );
}

This will obviously make the regex a property of the function itself. The only thing you may not like about this (or you may, I guess it depends) is that the regex can now be modified outside of the function's body. So, someone could do this to modify the interally-used regex:

makeSortString.translate_re = /[a-z]/g;

So, there is that option.

One way to get a closure, and thus prevent someone from modifying the regex, would be to define this as an anonymous function assignment like this:

var makeSortString = (function() {
  var translate_re = /[öäüÖÄÜ]/g;
  return function(s) {
    var translate = {
      "ä": "a", "ö": "o", "ü": "u",
      "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
    };
    return ( s.replace(translate_re, function(match) { 
      return translate[match]; 
    }) );
  }
})();

Hopefully this is useful to you.


UPDATE: It's early and I don't know why I didn't see the obvious before, but it might also be useful to put you translate object in a closure as well:

var makeSortString = (function() {
  var translate_re = /[öäüÖÄÜ]/g;
  var translate = {
    "ä": "a", "ö": "o", "ü": "u",
    "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
  };
  return function(s) {
    return ( s.replace(translate_re, function(match) { 
      return translate[match]; 
    }) );
  }
})();

How to set min-font-size in CSS

In CSS3 there is a simple but brilliant hack for that:

font-size:calc(12px + 1.5vw);

This is because the static part of calc() defines the minimum. Even though the dynamic part might shrink to something near 0.

Get height of div with no height set in css

Can do this in jQuery. Try all options .height(), .innerHeight() or .outerHeight().

$('document').ready(function() {
    $('#right_div').css({'height': $('#left_div').innerHeight()});
});

Example Screenshot

enter image description here

Hope this helps. Thanks!!

Convert array to JSON string in swift

SWIFT 2.0

var tempJson : NSString = ""
do {
    let arrJson = try NSJSONSerialization.dataWithJSONObject(arrInvitationList, options: NSJSONWritingOptions.PrettyPrinted)
    let string = NSString(data: arrJson, encoding: NSUTF8StringEncoding)
    tempJson = string! as NSString
}catch let error as NSError{
    print(error.description)
}

NOTE:- use tempJson variable when you want to use.

What is the use of static constructors?

Why and when would we create a static constructor ...?

One specific reason to use a static constructor is to create a 'super enum' class. Here's a (simple, contrived) example:

public class Animals
{
    private readonly string _description;
    private readonly string _speciesBinomialName;

    public string Description { get { return _description; } }
    public string SpeciesBinomialName { get { return _speciesBinomialName; } }

    private Animals(string description, string speciesBinomialName)
    {
        _description = description;
        _speciesBinomialName = speciesBinomialName;
    }

    private static readonly Animals _dog;
    private static readonly Animals _cat;
    private static readonly Animals _boaConstrictor;

    public static Animals Dog { get { return _dog; } }
    public static Animals Cat { get { return _cat; } }
    public static Animals BoaConstrictor { get { return _boaConstrictor; } }

    static Animals()
    {
        _dog = new Animals("Man's best friend", "Canis familiaris");
        _cat = new Animals("Small, typically furry, killer", "Felis catus");
        _boaConstrictor = new Animals("Large, heavy-bodied snake", "Boa constrictor");
    }
}

You'd use it very similarly (in syntactical appearance) to any other enum:

Animals.Dog

The advantage of this over a regular enum is that you can encapsulate related info easily. One disadvantage is that you can't use these values in a switch statement (because it requires constant values).

How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

That's impossible with just HTML and CSS, or at least wildly exotic and complicated. If you're willing to throw some javascript in, here's a solution using jQuery:

$(function() {
    $(window).resize(function() {
        var $i = $('img#image_to_resize');
        var $c = $img.parent();
        var i_ar = $i.width() / $i.height(), c_ar = $c.width() / $c.height();            
        $i.width(i_ar > c_ar ? $c.width() : $c.height() * (i_ar));
    });
    $(window).resize();
});

That will resize the image so that it will always fit inside the parent element, regardless of it's size. And as it's binded to the $(window).resize() event, when user resizes the window, the image will adjust.

This does not try to center the image in the container, that would be possible but I guess that's not what you're after.

@Scope("prototype") bean scope not creating new bean

By default, Spring beans are singletons. The problem arises when we try to wire beans of different scopes. For example, a prototype bean into a singleton. This is known as the scoped bean injection problem.

Another way to solve the problem is method injection with the @Lookup annotation.

Here is a nice article on this issue of injecting prototype beans into a singleton instance with multiple solutions.

https://www.baeldung.com/spring-inject-prototype-bean-into-singleton

How to empty the message in a text area with jquery?

A comment to jarijira

Well I have had many issues with .html and .empty() methods for inputs o. If the id represents an input and not another type of html selector like

or use the .val() function to manipulate.

For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').val('') //clear input value
     $('#someInput').val(newVal) //override w/ the new value
     $('#someInput').val('test2) 
     newVal= $('#someInput').val(newVal) //get input value

}

For improper, but sometimes works For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').html('') //clear input value
     $('#someInput').empty() //clear html inside of the id
     $('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
     really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input. 
     newVal= $('#someInput').val(newVal) //get input value

}

An issue that I had was I was using the $getJson method and I was indeed able to use .html calls to manipulate my inputs. However, whenever I had an error or fail on the getJSON I could no longer change my inputs using the .clear and .html calls. I could still return the .val(). After some experimentation and research I discovered that you should only use the .val() function to make changes to input fields.

If my interface must return Task what is the best way to have a no-operation implementation?

return Task.CompletedTask; // this will make the compiler happy

How to replace NA values in a table for selected columns

For a specific column, there is an alternative with sapply

DF <- data.frame(A = letters[1:5],
             B = letters[6:10],
             C = c(2, 5, NA, 8, NA))

DF_NEW <- sapply(seq(1, nrow(DF)),
                    function(i) ifelse(is.na(DF[i,3]) ==
                                       TRUE,
                                       0,
                                       DF[i,3]))

DF[,3] <- DF_NEW
DF

Configuring IntelliJ IDEA for unit testing with JUnit

If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.

However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.

You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.

A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.

Create Test Intention

Create Test Dialog

You can find more details in the Testing help section of the on-line documentation.

How can I get the application's path in a .NET console application?

I have used this code and get the solution.

AppDomain.CurrentDomain.BaseDirectory

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

One line if-condition-assignment

Here is what i can suggest. Use another variable to derive the if clause and assign it to num1.

Code:

num2 =20 if someBoolValue else num1
num1=num2

Java get String CompareTo as a comparator object

The Arrays class has versions of sort() and binarySearch() which don't require a Comparator. For example, you can use the version of Arrays.sort() which just takes an array of objects. These methods call the compareTo() method of the objects in the array.

Excel compare two columns and highlight duplicates

There may be a simpler option, but you can use VLOOKUP to check if a value appears in a list (and VLOOKUP is a powerful formula to get to grips with anyway).

So for A1, you can set a conditional format using the following formula:

=NOT(ISNA(VLOOKUP(A1,$B:$B,1,FALSE)))

Copy and Paste Special > Formats to copy that conditional format to the other cells in column A.

What the above formula is doing:

  • VLOOKUP is looking up the value of Cell A1 (first parameter) against the whole of column B ($B:$B), in the first column (that's the 3rd parameter, redundant here, but typically VLOOKUP looks up a table rather than a column). The last parameter, FALSE, specifies that the match must be exact rather than just the closest match.
  • VLOOKUP will return #ISNA if no match is found, so the NOT(ISNA(...)) returns true for all cells which have a match in column B.

Convert objective-c typedef to its string equivalent

My solution:

edit: I've added even a better solution at the end, using Modern Obj-C

1.
Put names as keys in an array.
Make sure the indexes are the appropriate enums, and in the right order (otherwise exception).
note: names is a property synthesized as *_names*;

code was not checked for compilation, but I used the same technique in my app.

typedef enum {
  JSON,
  XML,
  Atom,
  RSS
} FormatType;

+ (NSArray *)names
{
    static NSMutableArray * _names = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _names = [NSMutableArray arrayWithCapacity:4];
        [_names insertObject:@"JSON" atIndex:JSON];
        [_names insertObject:@"XML" atIndex:XML];
        [_names insertObject:@"Atom" atIndex:Atom];
        [_names insertObject:@"RSS" atIndex:RSS];
    });

    return _names;
}

+ (NSString *)nameForType:(FormatType)type
{
    return [[self names] objectAtIndex:type];
}


//

2.
Using Modern Obj-C you we can use a dictionary to tie descriptions to keys in the enum.
Order DOES NOT matter.

typedef NS_ENUM(NSUInteger, UserType) {
    UserTypeParent = 0,
    UserTypeStudent = 1,
    UserTypeTutor = 2,
    UserTypeUnknown = NSUIntegerMax
};  

@property (nonatomic) UserType type;

+ (NSDictionary *)typeDisplayNames
{
    return @{@(UserTypeParent) : @"Parent",
             @(UserTypeStudent) : @"Student",
             @(UserTypeTutor) : @"Tutor",
             @(UserTypeUnknown) : @"Unknown"};
}

- (NSString *)typeDisplayName
{
    return [[self class] typeDisplayNames][@(self.type)];
}


Usage (in a class instance method):

NSLog(@"%@", [self typeDisplayName]);


require_once :failed to open stream: no such file or directory

You will need to link to the file relative to the file that includes eventManager.php (Page A)

Change your code from
require_once('../includes/dbconn.inc');

To
require_once('../mysite/php/includes/dbconn.inc');

using if else with eval in aspx page

You can try c#

public string ProcessMyDataItem(object myValue)
 {
  if (myValue == null)
   {
   return "0 %"";
  }
   else
  {
     if(Convert.ToInt32(myValue) < 50)
       return "0";
     else
      return myValue.ToString() + "%";
  }

 }

asp

 <div class="tooltip" style="display: none">                                                                  
      <div style="text-align: center; font-weight: normal">
   Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
 </div>

find path of current folder - cmd

for /f "delims=" %%i in ("%0") do set "curpath=%%~dpi"
echo "%curpath%"

or

echo "%cd%"

The double quotes are needed if the path contains any & characters.

How do I pass data between Activities in Android application?

Another way is to use a public static field in which you store data, i.e.:

public class MyActivity extends Activity {

  public static String SharedString;
  public static SomeObject SharedObject;

//...

How to run different python versions in cmd

I also met the case to use both python2 and python3 on my Windows machine. Here's how i resolved it:

  1. download python2x and python3x, installed them.
  2. add C:\Python35;C:\Python35\Scripts;C:\Python27;C:\Python27\Scripts to environment variable PATH.
  3. Go to C:\Python35 to rename python.exe to python3.exe, also to C:\Python27, rename python.exe to python2.exe.
  4. restart your command window.
  5. type python2 scriptname.py, or python3 scriptname.py in command line to switch the version you like.

ADB error: cannot connect to daemon

Check your firewall and antivirus for permissions for Android Debugger Bridge (adb.exe).

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Swiss Army Knife: GroupBy.describe

Returns count, mean, std, and other useful statistics per-group.

df.groupby(['A', 'B'])['C'].describe()

           count  mean   std   min   25%   50%   75%   max
A   B                                                     
bar one      1.0  0.40   NaN  0.40  0.40  0.40  0.40  0.40
    three    1.0  2.24   NaN  2.24  2.24  2.24  2.24  2.24
    two      1.0 -0.98   NaN -0.98 -0.98 -0.98 -0.98 -0.98
foo one      2.0  1.36  0.58  0.95  1.15  1.36  1.56  1.76
    three    1.0 -0.15   NaN -0.15 -0.15 -0.15 -0.15 -0.15
    two      2.0  1.42  0.63  0.98  1.20  1.42  1.65  1.87

To get specific statistics, just select them,

df.groupby(['A', 'B'])['C'].describe()[['count', 'mean']]

           count      mean
A   B                     
bar one      1.0  0.400157
    three    1.0  2.240893
    two      1.0 -0.977278
foo one      2.0  1.357070
    three    1.0 -0.151357
    two      2.0  1.423148

describe works for multiple columns (change ['C'] to ['C', 'D']—or remove it altogether—and see what happens, the result is a MultiIndexed columned dataframe).

You also get different statistics for string data. Here's an example,

df2 = df.assign(D=list('aaabbccc')).sample(n=100, replace=True)

with pd.option_context('precision', 2):
    display(df2.groupby(['A', 'B'])
               .describe(include='all')
               .dropna(how='all', axis=1))

              C                                                   D                
          count  mean       std   min   25%   50%   75%   max count unique top freq
A   B                                                                              
bar one    14.0  0.40  5.76e-17  0.40  0.40  0.40  0.40  0.40    14      1   a   14
    three  14.0  2.24  4.61e-16  2.24  2.24  2.24  2.24  2.24    14      1   b   14
    two     9.0 -0.98  0.00e+00 -0.98 -0.98 -0.98 -0.98 -0.98     9      1   c    9
foo one    22.0  1.43  4.10e-01  0.95  0.95  1.76  1.76  1.76    22      2   a   13
    three  15.0 -0.15  0.00e+00 -0.15 -0.15 -0.15 -0.15 -0.15    15      1   c   15
    two    26.0  1.49  4.48e-01  0.98  0.98  1.87  1.87  1.87    26      2   b   15

For more information, see the documentation.


pandas >= 1.1: DataFrame.value_counts

This is available from pandas 1.1 if you just want to capture the size of every group, this cuts out the GroupBy and is faster.

df.value_counts(subset=['col1', 'col2'])

Minimal Example

# Setup
np.random.seed(0)
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                          'foo', 'bar', 'foo', 'foo'],
                   'B' : ['one', 'one', 'two', 'three',
                          'two', 'two', 'one', 'three'],
                   'C' : np.random.randn(8),
                   'D' : np.random.randn(8)})

df.value_counts(['A', 'B']) 

A    B    
foo  two      2
     one      2
     three    1
bar  two      1
     three    1
     one      1
dtype: int64

Other Statistical Analysis Tools

If you didn't find what you were looking for above, the User Guide has a comprehensive listing of supported statical analysis, correlation, and regression tools.

Ubuntu - Run command on start-up with "sudo"

Edit the tty configuration in /etc/init/tty*.conf with a shellscript as a parameter :

(...)
exec /sbin/getty -n -l  theInputScript.sh -8 38400 tty1
(...)

This is assuming that we're editing tty1 and the script that reads input is theInputScript.sh.

A word of warning this script is run as root, so when you are inputing stuff to it you have root priviliges. Also append a path to the location of the script.

Important: the script when it finishes, has to invoke the /sbin/login otherwise you wont be able to login in the terminal.

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

MySQL query to get column names?

I have tried this query in SQL Server and this worked for me :

SELECT name FROM sys.columns WHERE OBJECT_ID = OBJECT_ID('table_name')

sqldeveloper error message: Network adapter could not establish the connection error

If you have such error when using remote oracle database, you can delete your tnsname and listener then create new config with "hostname" or ip address instead of "localhost". such as listener.ora

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521))
    )

tnsnames.ora

DB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = DB)
    )
  )

It works fine for me.

Difference between "git add -A" and "git add ."

git add . equals git add -A . adds files to index only from current and children folders.

git add -A adds files to index from all folders in working tree.

P.S.: information relates to Git 2.0 (2014-05-28).

Convert JSON String to JSON Object c#

if you don't want or need a typed object try:

using Newtonsoft.Json;
// ...   
dynamic json  = JsonConvert.DeserializeObject(str);

or try for a typed object try:

Foo json  = JsonConvert.DeserializeObject<Foo>(str)

Cannot use string offset as an array in php

The error occurs when:

$a = array(); 
$a['text1'] = array();
$a['text1']['text2'] = 'sometext';

Then

echo $a['text1']['text2'];     //Error!!

Solution

$b = $a['text1'];
echo $b['text2'];    // prints: sometext

..