Programs & Examples On #Netbeans plugins

Dark theme in Netbeans 7 or 8

And then there is the original plugin ez-on-da-ice. Better yet, you can complain to me directly if there are issues. I promise you, I am mostly very responsive :).

http://plugins.netbeans.org/plugin/40985/ez-on-da-ice

enter image description here

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.

Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How to convert an xml string to a dictionary?

The code from http://code.activestate.com/recipes/410469-xml-as-dictionary/ works well, but if there are multiple elements that are the same at a given place in the hierarchy it just overrides them.

I added a shim between that looks to see if the element already exists before self.update(). If so, pops the existing entry and creates a lists out of the existing and the new. Any subsequent duplicates are added to the list.

Not sure if this can be handled more gracefully, but it works:

import xml.etree.ElementTree as ElementTree

class XmlDictConfig(dict):
    def __init__(self, parent_element):
        if parent_element.items():
            self.updateShim(dict(parent_element.items()))
        for element in parent_element:
            if len(element):
                aDict = XmlDictConfig(element)
                if element.items():
                    aDict.updateShim(dict(element.items()))
                self.updateShim({element.tag: aDict})
            elif element.items():
                self.updateShim({element.tag: dict(element.items())})
            else:
                self.updateShim({element.tag: element.text.strip()})

    def updateShim (self, aDict ):
        for key in aDict.keys():
            if key in self:
                value = self.pop(key)
                if type(value) is not list:
                    listOfDicts = []
                    listOfDicts.append(value)
                    listOfDicts.append(aDict[key])
                    self.update({key: listOfDicts})

                else:
                    value.append(aDict[key])
                    self.update({key: value})
            else:
                self.update(aDict)

In which conda environment is Jupyter executing?

  1. For checking on Which Python your Jupyter Notebook is running try executig this code.

from platform import python_version print(python_version())

  1. In order to run jupyter notebook from your environment activate MYenv and install jupyter notebook using command pip install jupyter notebook

then just jupyter notebook

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

How to check if ping responded or not in a batch file

You can ping without "-t" and check the exit code of the ping. It reports failure when there is no answer.

how can I enable PHP Extension intl?

Simply copy all icu****.dll files from

C:\xampp\php

to

C:\xampp\apache\bin

[or]

C:\wamp\bin\php\php5.5.12

to

C:\wamp\bin\apache\apache2.4.9

intl extension will start working!!!

T-SQL CASE Clause: How to specify WHEN NULL

Found a solution to this. Just ISNULL the CASE statement:

ISNULL(CASE x WHEN x THEN x ELSE x END, '') AS 'BLAH'

How to disable spring security for particular url

As @M.Deinum already wrote the answer.

I tried with api /api/v1/signup. it will bypass the filter/custom filter but an additional request invoked by the browser for /favicon.ico, so, I add this also in web.ignoring() and it works for me.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/v1/signup", "/favicon.ico");
}

Maybe this is not required for the above question.

How to add an event after close the modal window?

If you're using version 3.x of Bootstrap, the correct way to do this now is:

$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

Scroll down to the events section to learn more.

http://getbootstrap.com/javascript/#modals-usage

This appears to remain unchanged for whenever version 4 releases (http://v4-alpha.getbootstrap.com/components/modal/#events), but if it does I'll be sure to update this post with the relevant information.

How to print Boolean flag in NSLog?

//assuming b is BOOL. ternary operator helps us in any language.
NSLog(@"result is :%@",((b==YES)?@"YES":@"NO"));

How to hide element using Twitter Bootstrap and show it using jQuery?

The right answer

Bootstrap 4.x

Bootstrap 4.x uses the new .d-none class. Instead of using either .hidden, or .hide if you're using Bootstrap 4.x use .d-none.

<div id="myId" class="d-none">Foobar</div>
  • To show it: $("#myId").removeClass('d-none');
  • To hide it: $("#myId").addClass('d-none');
  • To toggle it: $("#myId").toggleClass('d-none');

(thanks to the comment by Fangming)

Bootstrap 3.x

First, don't use .hide! Use .hidden. As others have said, .hide is deprecated,

.hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1

Second, use jQuery's .toggleClass(), .addClass() and .removeClass()

<div id="myId" class="hidden">Foobar</div>
  • To show it: $("#myId").removeClass('hidden');
  • To hide it: $("#myId").addClass('hidden');
  • To toggle it: $("#myId").toggleClass('hidden');

Don't use the css class .show, it has a very small use case. The definitions of show, hidden and invisible are in the docs.

// Classes
.show {
  display: block !important;
}
.hidden {
  display: none !important;
  visibility: hidden !important;
}
.invisible {
  visibility: hidden;
}

Web API Put Request generates an Http 405 Method Not Allowed error

In my case the error 405 was invoked by static handler due to route ("api/images") conflicting with the folder of the same name ("~/images").

Get div to take up 100% body height, minus fixed-height header and footer

This question has been pretty well answered, but I'm taking the liberty of adding a javascript solution. Just give the element that you want to 'expand' the id footerspacerdiv, and this javascript snippet will expand that div until the page takes up the full height of the browser window.

It works based on the observation that, when a page is less than the full height of the browser window, document.body.scrollHeight is equal to document.body.clientHeight. The while loop increases the height of footerspacerdiv until document.body.scrollHeight is greater than document.body.clientHeight. At this point, footerspacerdiv will actually be 1 pixel too tall, and the browser will show a vertical scroll bar. So, the last line of the script reduces the height of footerspacerdiv by one pixel to make the page height exactly the height of the browser window.

By placing footerspacerdiv just above the 'footer' of the page, this script can be used to 'push the footer down' to the bottom of the page, so that on short pages, the footer is flush with the bottom of the browser window.

<script>    
//expand footerspacer div so that footer goes to bottom of page on short pages        
  var objSpacerDiv=document.getElementById('footerspacer');          
  var bresize=0;   

  while(document.body.scrollHeight<=document.body.clientHeight) {
    objSpacerDiv.style.height=(objSpacerDiv.clientHeight+1)+"px";
    bresize=1;
  }             
  if(bresize) { objSpacerDiv.style.height=(objSpacerDiv.clientHeight-1)+"px"; }               
 </script>

Where does this come from: -*- coding: utf-8 -*-

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

Ignoring upper case and lower case in Java

I have also tried all the posted code until I found out this one

if(math.toLowerCase(Locale.ENGLISH));

Here whatever character the user input will be converted to lower cases.

What is lazy loading in Hibernate?

Say you have a parent and that parent has a collection of children. Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.

Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded.

Also beware of the n+1-problem. Hibernate will not actually load all children when you access the collection. Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Don't detect mobile devices, go for stationary ones instead.

Nowadays (2016) there is a way to detect dots per inch/cm/px that seems to work in most modern browsers (see http://caniuse.com/#feat=css-media-resolution). I needed a method to distinguish between a relatively small screen, orientation didn't matter, and a stationary computer monitor.

Because many mobile browsers don't support this, one can write the general css code for all cases and use this exception for large screens:

@media (max-resolution: 1dppx) {
    /* ... */
}

Both Windows XP and 7 have the default setting of 1 dot per pixel (or 96dpi). I don't know about other operating systems, but this works really well for my needs.

Edit: dppx doesn't seem to work in Internet Explorer.. use (96)dpi instead.

error: passing xxx as 'this' argument of xxx discards qualifiers

Let's me give a more detail example. As to the below struct:

struct Count{
    uint32_t c;

    Count(uint32_t i=0):c(i){}

    uint32_t getCount(){
        return c;
    }

    uint32_t add(const Count& count){
        uint32_t total = c + count.getCount();
        return total;
    }
};

enter image description here

As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object. In the method add count is declared as const object, but the method getCount is not const method, so count.getCount() may change the members in count.

Compile error as below(core message in my compiler):

error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]

To solve the above problem, you can:

  1. change the method uint32_t getCount(){...} to uint32_t getCount() const {...}. So count.getCount() won't change the members in count.

or

  1. change uint32_t add(const Count& count){...} to uint32_t add(Count& count){...}. So count don't care about changing members in it.

As to you problem, objects in the std::set are stored as const StudentT, but the method getId and getName are not const, so you give the above error.

You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.

Difference between IISRESET and IIS Stop-Start command

The following was tested for IIS 8.5 and Windows 8.1.

As of IIS 7, Windows recommends restarting IIS via net stop/start. Via the command prompt (as Administrator):

> net stop WAS
> net start W3SVC

net stop WAS will stop W3SVC as well. Then when starting, net start W3SVC will start WAS as a dependency.

Notification Icon with the new Firebase Cloud Messaging system

My solution is similar to ATom's one, but easier to implement. You don't need to create a class that shadows FirebaseMessagingService completely, you can just override the method that receives the Intent (which is public, at least in version 9.6.1) and take the information to be displayed from the extras. The "hacky" part is that the method name is indeed obfuscated and is gonna change every time you update the Firebase sdk to a new version, but you can look it up quickly by inspecting FirebaseMessagingService with Android Studio and looking for a public method that takes an Intent as the only parameter. In version 9.6.1 it's called zzm. Here's how my service looks like:

public class MyNotificationService extends FirebaseMessagingService {

    public void onMessageReceived(RemoteMessage remoteMessage) {
        // do nothing
    }

    @Override
    public void zzm(Intent intent) {
        Intent launchIntent = new Intent(this, SplashScreenActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R    equest code */, launchIntent,
                PendingIntent.FLAG_ONE_SHOT);
        Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setLargeIcon(rawBitmap)
                .setContentTitle(intent.getStringExtra("gcm.notification.title"))
                .setContentText(intent.getStringExtra("gcm.notification.body"))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager)     getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Is it possible to refresh a single UITableViewCell in a UITableView?

I tried just calling -[UITableView cellForRowAtIndexPath:], but that didn't work. But, the following works for me for example. I alloc and release the NSArray for tight memory management.

- (void)reloadRow0Section0 {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    [indexPaths release];
}

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

How to add new item to hash

If you want to add new items from another hash - use merge method:

hash = {:item1 => 1}
another_hash = {:item2 => 2, :item3 => 3}
hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3}

In your specific case it could be:

hash = {:item1 => 1}
hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2}

but it's not wise to use it when you should to add just one element more.

Pay attention that merge will replace the values with the existing keys:

hash = {:item1 => 1}
hash.merge({:item1 => 2}) # {:item1=>2}

exactly like hash[:item1] = 2

Also you should pay attention that merge method (of course) doesn't effect the original value of hash variable - it returns a new merged hash. If you want to replace the value of the hash variable then use merge! instead:

hash = {:item1 => 1}
hash.merge!({:item2 => 2})
# now hash == {:item1=>1, :item2=>2}

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

JS. How to replace html element with another element/text, represented in string?

idTABLE.parentElement.innerHTML =  '<span>123 element</span> 456';

while this works, it's still recommended to use getElementById: Do DOM tree elements with ids become global variables?

replaceChild would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement and appendChild, but I don't see the point.

iPad Multitasking support requires these orientations

as Michael said,

Check the "Requires full screen" of the target of xcodeproj, if you don't need to support multitasking.

or Check the following device orientations

  • Portrait
  • Upside Down
  • Landscape Left
  • Landscape Right

In this case, we need to support launch storyboard.

port forwarding in windows

I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm

The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.

Disable Rails SQL logging in console

In Rails 3.2 I'm doing something like this in config/environment/development.rb:

module MyApp
  class Application < Rails::Application
    console do
      ActiveRecord::Base.logger = Logger.new( Rails.root.join("log", "development.log") )
    end
  end
end

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

Read values into a shell variable from a pipe

In my eyes the best way to read from stdin in bash is the following one, which also lets you work on the lines before the input ends:

while read LINE; do
    echo $LINE
done < /dev/stdin

How to use paginator from material angular?

The issue in the original question is that you are not capturing "page" event, to resolve this you need to add (page)='yourEventHandler($event)' as an attribute in the md-paginator tag.

check a working example here

You can also check the API docs here

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

I was having the same problem using my class SharedModule.

export class SharedModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: SharedModule,
            providers: [MyService]
         }
     }
}

Then I changed it putting directly in the app.modules this way

@NgModule({declarations: [
AppComponent,
NaviComponent],imports: [BrowserModule,RouterModule.forRoot(ROUTES),providers: [MoviesService],bootstrap: [MyService] })

Obs: I'm using "@angular/core": "^6.0.2".

I hope its help you.

Docker - Cannot remove dead container

You can also remove dead containers with this command

docker rm $(docker ps --all -q -f status=dead)

But, I'm really not sure why & how the dead containers are created. This error seems related https://github.com/typesafehub/mesos-spark-integration-tests/issues/34 whenever i get dead containers

[Update] With Docker 1.13 update, we can easily remove both unwanted containers, dangling images

$ docker system df #will show used space, similar to the unix tool df
$ docker system prune # will remove all unused data.

On select change, get data attribute value

this works for me

<select class="form-control" id="foo">
    <option value="first" data-id="1">first</option>
    <option value="second" data-id="2">second</option>
</select>

and the script

$('#foo').on("change",function(){
    var dataid = $("#foo option:selected").attr('data-id');
    alert(dataid)
});

Best way to get identity of inserted row?

I can't speak to other versions of SQL Server, but in 2012, outputting directly works just fine. You don't need to bother with a temporary table.

INSERT INTO MyTable
OUTPUT INSERTED.ID
VALUES (...)

By the way, this technique also works when inserting multiple rows.

INSERT INTO MyTable
OUTPUT INSERTED.ID
VALUES
    (...),
    (...),
    (...)

Output

ID
2
3
4

How to read files and stdout from a running Docker container

To view the stdout, you can start the docker container with -i. This of course does not enable you to leave the started process and explore the container.

docker start -i containerid

Alternatively you can view the filesystem of the container at

/var/lib/docker/containers/containerid/root/

However neither of these are ideal. If you want to view logs or any persistent storage, the correct way to do so would be attaching a volume with the -v switch when you use docker run. This would mean you can inspect log files either on the host or attach them to another container and inspect them there.

How to turn a vector into a matrix in R?

A matrix is really just a vector with a dim attribute (for the dimensions). So you can add dimensions to vec using the dim() function and vec will then be a matrix:

vec <- 1:49
dim(vec) <- c(7, 7)  ## (rows, cols)
vec

> vec <- 1:49
> dim(vec) <- c(7, 7)  ## (rows, cols)
> vec
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    8   15   22   29   36   43
[2,]    2    9   16   23   30   37   44
[3,]    3   10   17   24   31   38   45
[4,]    4   11   18   25   32   39   46
[5,]    5   12   19   26   33   40   47
[6,]    6   13   20   27   34   41   48
[7,]    7   14   21   28   35   42   49

What is Dependency Injection?

Dependency Injection (DI) is part of Dependency Inversion Principle (DIP) practice, which is also called Inversion of Control (IoC). Basically you need to do DIP because you want to make your code more modular and unit testable, instead of just one monolithic system. So you start identifying parts of the code that can be separated from the class and abstracted away. Now the implementation of the abstraction need to be injected from outside of the class. Normally this can be done via constructor. So you create a constructor that accepts the abstraction as a parameter, and this is called dependency injection (via constructor). For more explanation about DIP, DI, and IoC container you can read Here

How to subtract date/time in JavaScript?

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

Java check if boolean is null

In Java, null only applies to object references; since boolean is a primitive type, it cannot be assigned null.

It's hard to get context from your example, but I'm guessing that if hideInNav is not in the object returned by getProperties(), the (default value?) you've indicated will be false. I suspect this is the bug that you're seeing, as false is not equal to null, so hideNavigation is getting the empty string?

You might get some better answers with a bit more context to your code sample.

What version of Java is running in Eclipse?

The one the eclipse run in is the default java installed in the system (unless set specifically in the eclipse.ini file, use the -vm option). You can of course add more Java runtimes and use them for your projects

The string you've written is the right one, but it is specific to your environment. If you want to know the exact update then run the following code:

public class JavaVersion {
  public static void main(String[] args) {
    System.out.println(System.getProperty("java.runtime.version"));
  }
}

How do I correctly setup and teardown for my pytest class with tests?

When you write "tests defined as class methods", do you really mean class methods (methods which receive its class as first parameter) or just regular methods (methods which receive an instance as first parameter)?

Since your example uses self for the test methods I'm assuming the latter, so you just need to use setup_method instead:

class Test:

    def setup_method(self, test_method):
        # configure self.attribute

    def teardown_method(self, test_method):
        # tear down self.attribute

    def test_buttons(self):
        # use self.attribute for test

The test method instance is passed to setup_method and teardown_method, but can be ignored if your setup/teardown code doesn't need to know the testing context. More information can be found here.

I also recommend that you familiarize yourself with py.test's fixtures, as they are a more powerful concept.

What does "if (rs.next())" mean?

The next() method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:

Moves the cursor down one row from its current position.

This method return true if there's another row or false otherwise.

Get full path of a file with FileUpload Control

Check this:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="FileUp.aspx.vb" Inherits="FileUp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server"></asp:Label><br />
       <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <asp:Button ID="Button1" runat="server" Text="Upload" />
    </div>
    </form>
</body>
</html>

Code:

Partial Class FileUp
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim path As String
        Dim path1 As String
        path = Server.MapPath("~/")
        FileUpload1.SaveAs(path + FileUpload1.FileName)
        path1 = path + FileUpload1.FileName
        Label1.Text = path1
        Response.Write("File Uploaded successfully")
    End Sub
End Class

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

private IEnumerable<TextBox> GetTextBoxes(Control control)
{
    if (control is TextBox textBox)
    {
        yield return textBox;
    }

    if (control.HasChildren)
    {
        foreach (Control ctr in control.Controls)
        {
            foreach (var textbox in GetTextBoxes(ctr))
            {
                yield return textbox;
            }
        }
    }
}

Python: Random numbers into a list

import random

a=[]
n=int(input("Enter number of elements:"))

for j in range(n):
       a.append(random.randint(1,20))

print('Randomised list is: ',a)

How to detect internet speed in JavaScript?

As I outline in this other answer here on StackOverflow, you can do this by timing the download of files of various sizes (start small, ramp up if the connection seems to allow it), ensuring through cache headers and such that the file is really being read from the remote server and not being retrieved from cache. This doesn't necessarily require that you have a server of your own (the files could be coming from S3 or similar), but you will need somewhere to get the files from in order to test connection speed.

That said, point-in-time bandwidth tests are notoriously unreliable, being as they are impacted by other items being downloaded in other windows, the speed of your server, links en route, etc., etc. But you can get a rough idea using this sort of technique.

"installation of package 'FILE_PATH' had non-zero exit status" in R

Simple install following libs on your linux.
curl: sudo apt-get install curl
libssl-dev: sudo apt-get install libssl-dev
libcurl: sudo apt-get install libcurl4-openssl-dev
xml2: sudo apt-get install libxml2-dev

Bootstrap 3 - jumbotron background image effect

I think what you are looking for is to keep the background image fixed and just move the content on scroll. For that you have to simply use the following css property :

background-attachment: fixed;

What do I use on linux to make a python program executable

You can use PyInstaller. It generates a build dist so you can execute it as a single "binary" file.

http://pythonhosted.org/PyInstaller/#using-pyinstaller

Python 3 has the native option of create a build dist also:

https://docs.python.org/3/distutils/builtdist.html

TypeError: can't use a string pattern on a bytes-like object in re.findall()

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

See Convert bytes to a Python String

How to create a JPA query with LEFT OUTER JOIN

Write this;

 SELECT f from Student f LEFT JOIN f.classTbls s WHERE s.ClassName = 'abc'

Because your Student entity has One To Many relationship with ClassTbl entity.

Retrieve a single file from a repository

A nuanced variant of some of the answers here that answers the OP's question:

git archive [email protected]:foo/bar.git \
  HEAD path/to/file.txt | tar -xO path/to/file.txt > file.txt

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

Better way to sort array in descending order

Use LINQ OrderByDescending method. It returns IOrderedIEnumerable<int>, which you can convert back to Array if you need so. Generally, List<>s are more functional then Arrays.

array = array.OrderByDescending(c => c).ToArray();

How can I access global variable inside class in Python

It is very simple to make a variable global in a class:

a = 0

class b():
    global a
    a = 10

>>> a
10

CSS content property: is it possible to insert HTML instead of Text?

As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()) in combination with svg's <foreignObject> element.

You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup))

But note that it is mostly a hack and that there are a lot of limitations :

  • You can not load any external resources from this markup (no CSS, no images, no media etc.).
  • You can not execute script.
  • Since this won't be part of the DOM, the only way to alter it, is to pass the markup as a dataURI, and edit this dataURI in document.styleSheets. for this part, DOMParser and XMLSerializer may help.
  • While the same operation allows us to load url-encoded media in <img> tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).

Now, a small demo of some html markup in a pseudo element :

_x000D_
_x000D_
/* _x000D_
**  original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
*     xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
*  I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
  content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
_x000D_
_x000D_

The term "Add-Migration" is not recognized

I ran into the same issue. Most of my projects had the same thing in tools.

"tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
}

This worked fine on all but one project. I changed the entry in tools to

"tools": {
    "Microsoft.EntityFrameworkCore.Tools": {
    "version": "1.0.0-preview2-final",
    "type": "build"
  }
}

And then ran dotnet restore. After the restore completed, Add-Migration worked normally.

jQuery: Check if button is clicked

You can use this:

$("#id").click(function()
{
   $(this).data('clicked', true);
});

Now check it via an if statement:

if($("#id").data('clicked'))
{
   // code here 
}

For more information you can visit the jQuery website on the .data() function.

Flutter- wrapping text

You Can Wrap your widget with Flexible Widget and than you can set property of Text using overflow property of Text Widget. you have to set TextOverflow.clip for example:-

Flexible
(child: new Text("This is Dummy Long Text",
 style: TextStyle(
 fontFamily: "Roboto",
 color: Colors.black,
 fontSize: 10.0,
 fontWeight: FontWeight.bold),
 overflow: TextOverflow.clip,),)

hope this help someone :)

Performing Breadth First Search recursively

Let v be the starting vertex

Let G be the graph in question

The following is the pseudo code without using queue

Initially label v as visited as you start from v
BFS(G,v)
    for all adjacent vertices w of v in G:
        if vertex w is not visited:
            label w as visited
    for all adjacent vertices w of v in G:
        recursively call BFS(G,w)

Laravel 5 - How to access image uploaded in storage within View?

If disk 'local' is not working for you then try this :

  1. Change local to public in 'default' => env('FILESYSTEM_DRIVER', 'public'), from project_folder/config/filesystem.php
  2. Clear config cache php artisan config:clear
  3. Then create sym link php artisan storage:link

To get url of uploaded image you can use this Storage::url('iamge_name.jpg');

Can I get the name of the currently running function in JavaScript?

The answer is short: alert(arguments.callee.name);

Embed Google Map code in HTML with marker

no javascript or third party 'tools' necessary, use this:

<iframe src="https://www.google.com/maps/embed/v1/place?key=<YOUR API KEY>&q=71.0378379,-110.05995059999998"></iframe>

the place parameter provides the marker

there are a few options for the format of the 'q' parameter

make sure you have Google Maps Embed API and Static Maps API enabled in your APIs, or google will block the request

for more information check here

Round to 2 decimal places

Don't use doubles. You can lose some precision. Here's a general purpose function.

public static double round(double unrounded, int precision, int roundingMode)
{
    BigDecimal bd = new BigDecimal(unrounded);
    BigDecimal rounded = bd.setScale(precision, roundingMode);
    return rounded.doubleValue();
}

You can call it with

round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);

"precision" being the number of decimal points you desire.

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

Date Conversion from String to sql Date in Java giving different output?

While using the date formats, you may want to keep in mind to always use MM for months and mm for minutes. That should resolve your problem.

Visual Studio Code: format is not using indent settings

Most likely you have some formatting extension installed, e.g. JS-CSS-HTML Formatter.

If it is the case, then just open Command Palette, type "Formatter" and select Formatter Config. Then edit the value of "indent_size" as you like.

P.S. Don't forget to restart Visual Studio Code after editing :)

Radio button validation in javascript

In addition to the Javascript solutions above, you can also use an HTML 5 solution by marking the radio buttons as required in the markup. This will eliminate the need for any Javascript and let the browser do the work for you.

See HTML5: How to use the "required" attribute with a "radio" input field for more information on how to do this well.

Can I catch multiple Java exceptions in the same catch clause?

A cleaner (but less verbose, and perhaps not as preferred) alternative to user454322's answer on Java 6 (i.e., Android) would be to catch all Exceptions and re-throw RuntimeExceptions. This wouldn't work if you're planning on catching other types of exceptions further up the stack (unless you also re-throw them), but will effectively catch all checked exceptions.

For instance:

try {
    // CODE THAT THROWS EXCEPTION
} catch (Exception e) {
    if (e instanceof RuntimeException) {
        // this exception was not expected, so re-throw it
        throw e;
    } else {
        // YOUR CODE FOR ALL CHECKED EXCEPTIONS
    } 
}

That being said, for verbosity, it might be best to set a boolean or some other variable and based on that execute some code after the try-catch block.

Is there a CSS selector for the first direct child only?

The CSS selector for the direct first-child in your case is:

.section > :first-child

The direct selector is > and the first child selector is :first-child

No need for an asterisk before the : as others suggest. You could speed up the DOM searching by modifying this solution by prepending the tag:

div.section > :first-child

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

Just install the necessary types for react and it should solve the error.

if you are using yarn:

yarn add @types/react @types/react-dom @types/react-router-dom -D

if you are using npm:

npm install @types/react @types/react-dom @types/react-router-dom --save-dev

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

Download all stock symbol list of a market

There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).

You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:

Company:  Vodafone
------------------
LSE symbol:    VOD
 in Google:    LON:VOD
 in Yahoo:     VOD.L
NASDAQ symbol: VOD
 in Google:    NASDAQ:VOD
 in Yahoo:     VOD

Why do I get a "permission denied" error while installing a gem?

Your Ruby is installed in /usr/local/Cellar/ruby/....

That is a restricted path and can only be written to when you use elevated privileges, either by running as root or by using sudo. I won't recommend you run things as root since you don't understand how paths and permissions work. You can use sudo gem install jekyll, which will temporarily elevate your permissions, giving your command the rights needed to write to that directory.

However, I'd recommend you give serious thought into NOT doing that, and instead use your RVM to install Ruby into your own home directory, where you'll automatically be able to install Rubies and gems without permission issues. See the directions for installing into a local RVM sandbox in "Single-User installations".

Because you have RVM in your ~/.bash_profile, but it doesn't show up in your Gem environment listing, I suspect you either haven't followed the directions for installing RVM correctly, or you haven't used the all-important command:

rvm use 2.0.0 --default

to configure a default Ruby.

For most users, the "Single-User installation" is the way to go. If you have to use sudo with that configuration you've done something wrong.

Counting number of words in a file

This is just a thought. There is one very easy way to do it. If you just need number of words and not actual words then just use Apache WordUtils

import org.apache.commons.lang.WordUtils;

public class CountWord {

public static void main(String[] args) {    
String str = "Just keep a boolean flag around that lets you know if the previous character was whitespace or not pseudocode follows";

    String initials = WordUtils.initials(str);

    System.out.println(initials);
    //so number of words in your file will be
    System.out.println(initials.length());    
  }
}

Difference between EXISTS and IN in SQL?

IN:

  • Works on List result set
  • Doesn’t work on subqueries resulting in Virtual tables with multiple columns
  • Compares every value in the result list
  • Performance is comparatively SLOW for larger result set of subquery

EXISTS:

  • Works on Virtual tables
  • Is used with co-related queries
  • Exits comparison when match is found
  • Performance is comparatively FAST for larger result set of subquery

How can I change the font size using seaborn FacetGrid?

The FacetGrid plot does produce pretty small labels. While @paul-h has described the use of sns.set as a way to the change the font scaling, it may not be the optimal solution since it will change the font_scale setting for all plots.

You could use the seaborn.plotting_context to change the settings for just the current plot:

with sns.plotting_context(font_scale=1.5):
    sns.factorplot(x, y ...)

Best way to check if a character array is empty

Given this code:

char text[50];
if(strlen(text) == 0) {}

Followed by a question about this code:

 memset(text, 0, sizeof(text));
 if(strlen(text) == 0) {}

I smell confusion. Specifically, in this case:

char text[50];
if(strlen(text) == 0) {}

... the contents of text[] will be uninitialized and undefined. Thus, strlen(text) will return an undefined result.

The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0.

char text[50];
text[0] = 0;

From then, both strlen(text) and the very-fast-but-not-as-straightforward (text[0] == 0) tests will both detect the empty string.

how to convert image to byte array in java?

Here is a complete version of code for doing this. I have tested it. The BufferedImage and Base64 class do the trick mainly. Also some parameter needs to be set correctly.

public class SimpleConvertImage {
    public static void main(String[] args) throws IOException{
        String dirName="C:\\";
        ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
        BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
        ImageIO.write(img, "jpg", baos);
        baos.flush();

        String base64String=Base64.encode(baos.toByteArray());
        baos.close();

        byte[] bytearray = Base64.decode(base64String);

        BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
        ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    }
}

Reference link

Selenium Webdriver: Entering text into text field

Use this code.

driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");

How do I convert a decimal to an int in C#?

Rounding a decimal to the nearest integer

decimal a ;
int b = (int)(a + 0.5m);

when a = 49.9, then b = 50

when a = 49.5, then b = 50

when a = 49.4, then b = 49 etc.

Distribution certificate / private key not installed

Up to date (January 2021) (Xcode 10 - 12)

  1. Go to Xcode - Preferences - Accounts - Manage Certificates
  2. Click on the + at the bottom left, then Apple development
  3. Wait a little, then click Done

That's all. You may want to revoke the old certificate on developer.apple.com too.

Old answer

Step 1: Xcode -> Product -> Archives -> Click manage certificate

Click manage certificate

Step 2: Add iOS distribution

Add iOS distribution

How to count the occurrence of certain item in an ndarray?

if you are dealing with very large arrays using generators could be an option. The nice thing here it that this approach works fine for both arrays and lists and you dont need any additional package. Additionally, you are not using that much memory.

my_array = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
sum(1 for val in my_array if val==0)
Out: 8

Oracle ORA-12154: TNS: Could not resolve service name Error?

I just spend an hour on this, I'm new to Oracle so i was thoroughly confused..

the situation:

just installed visual studio 2012 Oracle developer tools. When i did this I lost the items in my drop down which contained my TNS entries in TOAD. I was getting this error from Visual studio AND TOAD!! WTH! so i added the environmental Variable TNS_ADMIN under "ALL USERS" with the path to my .ora file (which i now worked fine because it worked until I broke it). Toad picked up that change. Still Visual Studio wouldn't give me any love... still getting same error. THEN, i added the environmental Variable TO MY USER VARIABLES.. VIOLA!!

ENSURE THE ENVIRONMENTAL VARIABLES ARE SET FOR THE SYSTEM AND THE USER

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

https connection using CURL from command line

I actually had this kind of problem and I solve it by these steps:

  1. Get the bundle of root CA certificates from here: https://curl.haxx.se/ca/cacert.pem and save it on local

  2. Find the php.ini file

  3. Set the curl.cainfo to be the path of the certificates. So it will something like:

curl.cainfo = /path/of/the/keys/cacert.pem

android: changing option menu items programmatically

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.calendar, menu);
        if(show_list == true) {         

        if(!locale.equalsIgnoreCase("sk")) menu.findItem(R.id.action_cyclesn).setVisible(false);

        return true;
    }

PYTHONPATH on Linux

PYTHONPATH is an environment variable those content is added to the sys.path where Python looks for modules. You can set it to whatever you like.

However, do not mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…

I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.

To show only file name without the entire directory path

you could add an sed script to your commandline:

ls /home/user/new/*.txt | sed -r 's/^.+\///'

Stretch background image css?

Just paste this into your line of codes:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

How to validate phone number using PHP?

I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....

Take a look at this similar question to get some ideas.

Then there is E.164 which is a numbering standard recommendation from ITU-T

Retrieving the first digit of a number

Almost certainly more efficient than using Strings:

int firstDigit(int x) {
    while (x > 9) {
        x /= 10;
    }
    return x;
}

(Works only for nonnegative integers.)

NULL values inside NOT IN clause

The title of this question at the time of writing is

SQL NOT IN constraint and NULL values

From the text of the question it appears that the problem was occurring in a SQL DML SELECT query, rather than a SQL DDL CONSTRAINT.

However, especially given the wording of the title, I want to point out that some statements made here are potentially misleading statements, those along the lines of (paraphrasing)

When the predicate evaluates to UNKNOWN you don't get any rows.

Although this is the case for SQL DML, when considering constraints the effect is different.

Consider this very simple table with two constraints taken directly from the predicates in the question (and addressed in an excellent answer by @Brannon):

DECLARE @T TABLE 
(
 true CHAR(4) DEFAULT 'true' NOT NULL, 
 CHECK ( 3 IN (1, 2, 3, NULL )), 
 CHECK ( 3 NOT IN (1, 2, NULL ))
);

INSERT INTO @T VALUES ('true');

SELECT COUNT(*) AS tally FROM @T;

As per @Brannon's answer, the first constraint (using IN) evaluates to TRUE and the second constraint (using NOT IN) evaluates to UNKNOWN. However, the insert succeeds! Therefore, in this case it is not strictly correct to say, "you don't get any rows" because we have indeed got a row inserted as a result.

The above effect is indeed the correct one as regards the SQL-92 Standard. Compare and contrast the following section from the SQL-92 spec

7.6 where clause

The result of the is a table of those rows of T for which the result of the search condition is true.

4.10 Integrity constraints

A table check constraint is satisfied if and only if the specified search condition is not false for any row of a table.

In other words:

In SQL DML, rows are removed from the result when the WHERE evaluates to UNKNOWN because it does not satisfy the condition "is true".

In SQL DDL (i.e. constraints), rows are not removed from the result when they evaluate to UNKNOWN because it does satisfy the condition "is not false".

Although the effects in SQL DML and SQL DDL respectively may seem contradictory, there is practical reason for giving UNKNOWN results the 'benefit of the doubt' by allowing them to satisfy a constraint (more correctly, allowing them to not fail to satisfy a constraint): without this behaviour, every constraints would have to explicitly handle nulls and that would be very unsatisfactory from a language design perspective (not to mention, a right pain for coders!)

p.s. if you are finding it as challenging to follow such logic as "unknown does not fail to satisfy a constraint" as I am to write it, then consider you can dispense with all this simply by avoiding nullable columns in SQL DDL and anything in SQL DML that produces nulls (e.g. outer joins)!

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

How to use Python to execute a cURL command?

Some background: I went looking for exactly this question because I had to do something to retrieve content, but all I had available was an old version of python with inadequate SSL support. If you're on an older MacBook, you know what I'm talking about. In any case, curl runs fine from a shell (I suspect it has modern SSL support linked in) so sometimes you want to do this without using requests or urllib2.

You can use the subprocess module to execute curl and get at the retrieved content:

import subprocess

// 'response' contains a []byte with the retrieved content.
// use '-s' to keep curl quiet while it does its job, but
// it's useful to omit that while you're still writing code
// so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])

Python 3's subprocess module also contains .run() with a number of useful options. I'll leave it to someone who is actually running python 3 to provide that answer.

How to reload a page after the OK click on the Alert Page

Interesting that Firefox will stop further processing of JavaScript after the relocate function. Chrome and IE will continue to display any other alerts and then reload the page. Try it:

<script type="text/javascript">
    alert('foo');
    window.location.reload(true);
    alert('bar');
    window.location.reload(true);
    alert('foobar');
    window.location.reload(true);
</script>

Jenkins - How to access BUILD_NUMBER environment variable

Assuming I am understanding your question and setup correctly,

If you're trying to use the build number in your script, you have two options:

1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}

2) Change your script so that:

<property environment="env" />
<property name="build_parameter"  value="${env.BUILD_NUMBER}"/>

How to get json key and value in javascript?

For getting key

var a = {"a":"1","b":"2"};
var keys = []
for(var k in a){
  keys.push(k)
}

For getting value.

var a = {"a":"1","b":"2"};
var values = []
for(var k in a){
  values.push(a[k]);
}

LISTAGG in Oracle to return distinct values

If you do not need a particular order of concatenated values, and the separator can be a comma, you can do:

select col1, stragg(distinct col2)
  from table
 group by col1

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

if you get this error

Gradle: 
FAILURE: Could not determine which tasks to execute.
* What went wrong:
Task 'assemble' not found in root project 'MyProject'.
* Try:
Run gradle tasks to get a list of available tasks.

You need to edit your Projects .iml file. not the one under src. the one that is like myappProject.iml' delete the whole component name = facetmanager

<module external.system.id="GRADLE" type="JAVA_MODULE" version="4">
<component name="FacetManager">
...remove this element and everything inside such as <facet> elements...
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
...keep this part...
</component

How do I disable TextBox using JavaScript?

With the help of jquery it can be done as follows.

$("#color").prop('disabled', true);

How to use bluetooth to connect two iPhone?

We cant connect to iPhones normally by bluetooth.it is so difficult.so,please try any other file transfers like zapya,xender.it seems good

How do I use raw_input in Python 3

Here's a piece of code I put in my scripts that I wan't to run in py2/3-agnostic environment:

# Thank you, python2-3 team, for making such a fantastic mess with
# input/raw_input :-)
real_raw_input = vars(__builtins__).get('raw_input',input)

Now you can use real_raw_input. It's quite expensive but short and readable. Using raw input is usually time expensive (waiting for input), so it's not important.

In theory, you can even assign raw_input instead of real_raw_input but there might be modules that check existence of raw_input and behave accordingly. It's better stay on the safe side.

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

How to set seekbar min and max value

The easiest way to set a min and max value to a seekbar for me: if you want values min=60 to max=180, this is equal to min=0 max=120. So in your seekbar xml set property:

android:max="120"

min will be always 0.

Now you only need to do what your are doing, add the amount to get your translated value in any change, in this case +60.

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            int translatedProgress = progress + 60;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

Be careful with the seekbar property android:progress, if you change the range you must recalculate your initial progress. If you want 50%, max/2, in my example 120/2 = 60;

Accessing the last entry in a Map

In such scenario last used key is usually known so it can be used for accessing last value (inserted with the one):

class PostIndexData {
    String _office_name;
    Boolean _isGov;
    public PostIndexData(String name, Boolean gov) {
        _office_name = name;
        _isGov = gov;
    }
}
//-----------------------
class KgpData {
    String _postIndex;
    PostIndexData _postIndexData;
    public KgpData(String postIndex, PostIndexData postIndexData) {
        _postIndex = postIndex;
        _postIndexData = postIndexData;;
    }
}

public class Office2ASMPro {
    private HashMap<String,PostIndexData> _postIndexMap = new HashMap<>();
    private HashMap<String,KgpData> _kgpMap = new HashMap<>();
...
private void addOffice(String kgp, String postIndex, String officeName, Boolean gov) {
            if (_postIndexMap.get(postIndex) == null) {
                _postIndexMap.put(postIndex, new PostIndexData(officeName, gov));
            }
            _kgpMap.put( kgp, new KgpData(postIndex, _postIndexMap.get(postIndex)) );
        }

How to get .app file of a xcode application

You can find the .app file here:

~/Library/Developer/Xcode/DerivedData/{app name}/Build/Products/Deployment/ 

credit for path goes to this answer

SIDENOTE: I had a lot of fun trying to get this into my iPad after that. It worked however. Using Snow Leopard + Xcode 4.2 + iPad with IOS 5.1.1 :) - I used the iPhone configuration utility to get the app into the ipad (you have to add the app, then click on the device, then click "install" behind the app you just added in the "application library" of iphone configuration utility) and had to create a Distribution Provisioning Profile and get the WWDR certificate and finally change the build settings in Xcode after all the certificates were in place. See here

But after much fun I am now looking at my first app on my iPad :) - btw, for getting apps into the app store you need to create a app store Distribution Provisioning Profile, while for ad hoc installs like these you create an ad hoc one. There is a bit more to it, but I think these are the most important and tricky steps. Enjoy.

PS. Just remembered that you also have to set the build type (top left of Xcode) to "iOS device", otherwise it will never sign your application. So the path name above only has limited value: yes, it will have the .app file in it, but no you can't upload it (at least not using the iPhone configuration utility) since it is not code signed - you will get an "Could not copy validate signature" error. So change it to "iOS device" and build (remember to select the right certificates in the build section of Xcode as per the url info above). In that same build section, you can also set the "Installation Build Products Location" to a different path, so that you can determine where the .app (the one that is properly code signed) ends up.

XPath to select Element by attribute value

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

Installing packages in Sublime Text 2

You may try to install Package Control first by following simple instructions available at Installation Guide (which is like 1. Open the Console, 2. Paste the code).

Then please check Package Docs Control Usage for Basic Functionality:

Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+P (Win, Linux) or CMD+Shift+P (OS X). All Package Control commands begin with Package Control:, so start by typing Package.

The command pallete will now show a number of commands. Most users will be interested in the following:

Install Package

Show a list of all available packages that are available for install. This will include all of the packages from the default channel, plus any from repositories you have added.

Easiest way to copy a single file from host to Vagrant guest?

Since you ask for the easiest way, I suggest using vagrant-scp. It adds a scp command to vagrant, so you can copy files to your VM like you would normally do with scp.

Install via:

vagrant plugin install vagrant-scp

Use it like so:

vagrant scp <some_local_file_or_dir> [vm_name]:<somewhere_on_the_vm>

Convert List<Object> to String[] in Java

Using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());

What does 'const static' mean in C and C++?

A lot of people gave the basic answer but nobody pointed out that in C++ const defaults to static at namespace level (and some gave wrong information). See the C++98 standard section 3.5.3.

First some background:

Translation unit: A source file after the pre-processor (recursively) included all its include files.

Static linkage: A symbol is only available within its translation unit.

External linkage: A symbol is available from other translation units.

At namespace level

This includes the global namespace aka global variables.

static const int sci = 0; // sci is explicitly static
const int ci = 1;         // ci is implicitly static
extern const int eci = 2; // eci is explicitly extern
extern int ei = 3;        // ei is explicitly extern
int i = 4;                // i is implicitly extern
static int si = 5;        // si is explicitly static

At function level

static means the value is maintained between function calls.
The semantics of function static variables is similar to global variables in that they reside in the program's data-segment (and not the stack or the heap), see this question for more details about static variables' lifetime.

At class level

static means the value is shared between all instances of the class and const means it doesn't change.

Printing out a number in assembly language?

Call WinAPI function (if u are developing win-application)

List of special characters for SQL LIKE clause

Sybase :

%              : Matches any string of zero or more characters.
_              : Matches a single character.
[specifier]    : Brackets enclose ranges or sets, such as [a-f] 
                 or [abcdef].Specifier  can take two forms:

                 rangespec1-rangespec2: 
                   rangespec1 indicates the start of a range of characters.
                   - is a special character, indicating a range.
                   rangespec2 indicates the end of a range of characters.

                 set: 
                  can be composed of any discrete set of values, in any 
                  order, such as [a2bR].The range [a-f], and the 
                  sets [abcdef] and [fcbdae] return the same 
                  set of values.

                 Specifiers are case-sensitive.

[^specifier]    : A caret (^) preceding a specifier indicates 
                  non-inclusion. [^a-f] means "not in the range 
                  a-f"; [^a2bR] means "not a, 2, b, or R."

Can a constructor in Java be private?

Basic idea behind having a private constructor is to restrict the instantiation of a class from outside by JVM, but if a class having a argument constructor, then it infers that one is intentionally instantiating.

dlib installation on Windows 10

Simple and 100% working trick

(Make sure you install cmake)

My Anaconda python ver : 3.6.8 (64 bit) | OS :Windows 10

python -m pip install https://files.pythonhosted.org/packages/0e/ce/f8a3cff33ac03a8219768f0694c5d703c8e037e6aba2e865f9bae22ed63c/dlib-19.8.1-cp36-cp36m-win_amd64.whl#sha256=794994fa2c54e7776659fddb148363a5556468a6d5d46be8dad311722d54bfcf

enter image description here

Android Studio - mergeDebugResources exception

It could be a faulty name of a drawable file. I had an image I was using that was named Untitled. Changing the name solved my problem.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

For those who are experiencing same problem after controlling there is no suspicious java process which allocate the port, there is no red square on eclipse to terminate any process and also there is no change even you try different port for your spring boot application.

might sound stupid but; restarting eclipse works. :)

How do I set up cron to run a file just once at a specific time?

Your comment suggests you're trying to call this from a programming language. If that's the case, can your program fork a child process that calls sleep then does the work?

What about having your program calculate the number of seconds until the desired runtime, and have it call shell_exec("sleep ${secondsToWait) ; myCommandToRun");

Where does mysql store data?

Reading between the lines - Is this an innodb database? In which case the actual data is normally stored in that directory under the name ibdata1. This file contains all your tables unless you specifically set up mysql to use one-file-per-table (innodb-file-per-table)

How to merge two files line by line in Bash

here's non-paste methods

awk

awk 'BEGIN {OFS=" "}{
  getline line < "file2"
  print $0,line
} ' file1

Bash

exec 6<"file2"
while read -r line
do
    read -r f2line <&6
    echo "${line}${f2line}"
done <"file1"
exec 6<&-

jQuery Validate Plugin - Trigger validation of single field

When you set up your validation, you should be saving the validator object. you can use this to validate individual fields.

<script type="text/javascript">
var _validator;
$(function () {    
     _validator = $("#form").validate();   
});

function doSomething() {    
     _validator.element($('#someElement'));
}
</script> 

-- cross posted with this similar question

What is the difference between pull and clone in git?

git clone means you are making a copy of the repository in your system.

git fork means you are copying the repository to your Github account.

git pull means you are fetching the last modified repository.

git push means you are returning the repository after modifying it.

In layman's term:

git clone is downloading and git pull is refreshing.

Importing CSV with line breaks in Excel 2007

Line breaks inside double quotes are perfectly fine according to CSV standard. The parsing of line breaks in Excel depends on the OS setting of list separator:

  1. Windows: you need to set the list seperator to comma (Region and language » Formats » Advanced) Source: https://superuser.com/questions/238944/how-to-force-excel-to-open-csv-files-with-data-arranged-in-columns#answer-633302

  2. Mac: Need to change the region to US (then to manually change back other settings to your preference) Source: https://answers.microsoft.com/en-us/mac/forum/macoffice2016-macexcel/line-separator-comma-semicolon-in-excel-2016-for/7db1b1a0-0300-44ba-ab9b-35d1c40159c6 (see NewmanLee's answer)

Don't forget to close Excel completely before trying again.

I've succesfully replicated the issue and was able to fix it using the above in both Max and Windows.

How do I get a YouTube video thumbnail from the YouTube API?

YouTube API version 3 up and running in 2 minutes

If all you want to do is search YouTube and get associated properties:

  1. Get a public API -- This link gives a good direction

  2. Use below query string. The search query (denoted by q=) in the URL string is stackoverflow for example purposes. YouTube will then send you back a JSON reply where you can then parse for Thumbnail, Snippet, Author, etc.

    https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&maxResults=50&q=stackoverflow&key=YOUR_API_KEY_HERE

Determine if variable is defined in Python

'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)

Log4j: How to configure simplest possible file logging?

Here's a simple one that I often use:

# Set up logging to include a file record of the output
# Note: the file is always created, even if there is 
# no actual output.
log4j.rootLogger=error, stdout, R

# Log format to standard out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=   %5p\t[%d] [%t] (%F:%L)\n     \t%m%n\n

# File based log output
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=owls_conditions.log
log4j.appender.R.MaxFileSize=10000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=   %5p\t[%d] [%t] (%F:%L)\n     \t%m%n\n

The format of the log is as follows:

ERROR   [2009-09-13 09:56:01,760] [main] (RDFDefaultErrorHandler.java:44)
        http://www.xfront.com/owl/ontologies/camera/#(line 1 column 1): Content is not allowed in prolog.

Such a format is defined by the string %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n. You can read the meaning of conversion characters in log4j javadoc for PatternLayout.

Included comments should help in understanding what it does. Further notes:

  • it logs both to console and to file; in this case the file is named owls_conditions.log: change it according to your needs;
  • files are rotated when they reach 10000KB, and one back-up file is kept

Dump a NumPy array into a csv file

tofile is a convenient function to do this:

import numpy as np
a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
a.tofile('foo.csv',sep=',',format='%10.5f')

The man page has some useful notes:

This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.

Note. This function does not produce multi-line csv files, it saves everything to one line.

Angular2 - Focusing a textbox on component load

Also, it can be done dynamically like so...

<input [id]="input.id" [type]="input.type" [autofocus]="input.autofocus" />

Where input is

const input = {
  id: "my-input",
  type: "text",
  autofocus: true
};

How do you format a Date/Time in TypeScript?

Update (2020)

As pointed by @jonhF in the comments, MomentJs recommends to not use MomentJs anymore. Check https://momentjs.com/docs/

Instead, I'm keeping this list with my personal TOP 3 js date libraries for future reference.

Old comment

I suggest you to use MomentJS

With moment you can have lot of outputs, and this one 09/11/2015 16:16 is one of then.

How to get database structure in MySQL via query

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_SCHEMA = 'test' AND TABLE_NAME ='products'; 

where Table_schema is database name

How to convert an address into a Google Maps Link (NOT MAP)

The C# Replace method usually works for me:

foo = "http://maps.google.com/?q=" + address.Text.Replace(" ","+");

How to access a mobile's camera from a web app?

Nowadays at least with android it's relatively easy. Just use normal file input tag and when user clicks it the phone will ask if user wants to use camera (or file managers etc..) to upload a file. Just take a photo with the camera and it will automatically be added and uploaded.

No idea about iphone. Maybe someone can enlighten on that. EDIT: Iphone works similarly.

Sample of the input tag:

<input type="file" accept="image/*" capture="camera">

Convert INT to VARCHAR SQL

CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.

SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

iOS: UIButton resize according to text length

In UIKit, there are additions to the NSString class to get from a given NSString object the size it'll take up when rendered in a certain font.

Docs was here. Now it's here under Deprecated.

In short, if you go:

CGSize stringsize = [myString sizeWithFont:[UIFont systemFontOfSize:14]]; 
//or whatever font you're using
[button setFrame:CGRectMake(10,0,stringsize.width, stringsize.height)];

...you'll have set the button's frame to the height and width of the string you're rendering.

You'll probably want to experiment with some buffer space around that CGSize, but you'll be starting in the right place.

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

Error Code: 1406. Data too long for column - MySQL

Go to your Models and check, because you might have truncated a number of words for that particular column eg. max_length="150".

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

Function Redim2d(ByRef Mtx As Variant, ByVal QtyColumnToAdd As Integer)
    ReDim Preserve Mtx(LBound(Mtx, 1) To UBound(Mtx, 1), LBound(Mtx, 2) To UBound(Mtx, 2) + QtyColumnToAdd)
End Function

'Main Code
sub Main ()
    Call Redim2d(MtxR8Strat, 1)  'Add one column
end sub

'OR
sub main2()
    QtyColumnToAdd = 1 'Add one column
    ReDim Preserve Mtx(LBound(Mtx, 1) To UBound(Mtx, 1), LBound(Mtx, 2) To UBound(Mtx, 2) + QtyColumnToAdd)
end sub

How to pass a parameter like title, summary and image in a Facebook sharer URL

On the Developers bugs Facebook site, the last answer about that (parameters with sharer.php), makes me believe it was a bug that was going to be resolved. Am I right?

https://developers.facebook.com/x/bugs/357750474364812/

Ibrahim Faour · · Facebook Platform Team

Apologies for the inconvenience. We aim to update our external reports as soon as we get a resolution on issues. I do understand that sometimes the answer provided may not be satisfying, but we are eager to keep our platform as stable and efficient as possible. Thanks!

How to add external fonts to android application

You need to create fonts folder under assets folder in your project and put your TTF into it. Then in your Activity onCreate()

TextView myTextView=(TextView)findViewById(R.id.textBox);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
myTextView.setTypeface(typeFace);

Please note that not all TTF will work. While I was experimenting, it worked just for a subset (on Windows the ones whose name is written in small caps).

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...


function shipOff(event) {
    var result = event.target.result;
    var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
    $.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and jQuery.post().

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

How do I create a link to add an entry to a calendar?

Here's an Add to Calendar service to serve the purpose for adding an event on

  1. Apple Calendar
  2. Google Calendar
  3. Outlook
  4. Outlook Online
  5. Yahoo! Calendar

The "Add to Calendar" button for events on websites and calendars is easy to install, language independent, time zone and DST compatible. It works perfectly in all modern browsers, tablets and mobile devices, and with Apple Calendar, Google Calendar, Outlook, Outlook.com and Yahoo Calendar.

<div title="Add to Calendar" class="addeventatc">
    Add to Calendar
    <span class="start">03/01/2018 08:00 AM</span>
    <span class="end">03/01/2018 10:00 AM</span>
    <span class="timezone">America/Los_Angeles</span>
    <span class="title">Summary of the event</span>
    <span class="description">Description of the event</span>
    <span class="location">Location of the event</span>
</div>

enter image description here

What does %~dp0 mean, and how does it work?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

How to set transparent background for Image Button in code?

Do it in your xml

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButtonSettings"
        android:layout_gravity="right|bottom"
        android:src="@drawable/tabbar_settings_icon"
        android:background="@android:color/transparent"/>

Mean of a column in a data frame, given the column's name

I think you're asking how to compute the mean of a variable in a data frame, given the name of the column. There are two typical approaches to doing this, one indexing with [[ and the other indexing with [:

data(iris)
mean(iris[["Petal.Length"]])
# [1] 3.758
mean(iris[,"Petal.Length"])
# [1] 3.758
mean(iris[["Sepal.Width"]])
# [1] 3.057333
mean(iris[,"Sepal.Width"])
# [1] 3.057333

How can I repeat a character in Bash?

In bash 3.0 or higher

for i in {1..100};do echo -n =;done

VueJS conditionally add an attribute for an element

Try:

<input :required="test ? true : false">

How to grant permission to users for a directory using command line in Windows?

You can also use ICACLS.

To grant the Users group Full Control to a folder:

>icacls "C:\MyFolder" /grant Users:F

To grant Modify permission to IIS users for C:\MyFolder (if you need your IIS has ability to R/W files into specific folder):

>icacls "C:\MyFolder" /grant IIS_IUSRS:M

If you do ICACLS /? you will be able to see all available options.

How to use the TextWatcher class in Android?

A little bigger perspective of the solution:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.yourlayout, container, false);
        View tv = v.findViewById(R.id.et1);
        ((TextView) tv).addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                 SpannableString contentText = new SpannableString(((TextView) tv).getText());
                 String contents = Html.toHtml(contentText).toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
            }
        });
        return v;
    }

This works for me, doing it my first time.

Difference between a theta join, equijoin and natural join

A theta join allows for arbitrary comparison relationships (such as ≥).

An equijoin is a theta join using the equality operator.

A natural join is an equijoin on attributes that have the same name in each relationship.

Additionally, a natural join removes the duplicate columns involved in the equality comparison so only 1 of each compared column remains; in rough relational algebraic terms: ? = pR,S-as ? ?aR=aS

How to convert .pfx file to keystore with private key?

Your PFX file should contain the private key within it. Export the private key and certificate directly from your PFX file (e.g. using OpenSSL) and import them into your Java keystore.

Edit

Further information:

  • Download OpenSSL for Windows here.
  • Export private key: openssl pkcs12 -in filename.pfx -nocerts -out key.pem
  • Export certificate: openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
  • Import private key and certificate into Java keystore using keytool.

iPhone Debugging: How to resolve 'failed to get the task for process'?

This took me a while to figure out.

If you are using a distribution / ad hoc/ profile you cannot test it through xcode. You will get the error: The program being debugged is not being run.

You can build the app, go to the products folder in your app in xcode, click on the file with your project name and choose reveal in finder. You can drag this app into into iTunes and sync and that point you can test your app on your device.

is there any IE8 only css hack?

Doing something like this should work for you.

<!--[if IE 8]> 
<div id="IE8">
<![endif]--> 

*Your content* 

<!--[if IE 8]> 
</div>
<![endif]--> 

Then your CSS can look like this:

#IE8 div.something
{ 
    color: purple; 
}

What is the total amount of public IPv4 addresses?

According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.

And too many addresses in this post.

how to append a css class to an element by javascript?

When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.

Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.

document.addClass= function(el, css){
    var tem, C= el.className.split(/\s+/), A=[];    
    while(C.length){
        tem= C.shift();
        if(tem && tem!= css) A[A.length]= tem;
    }
    A[A.length]= css;
    return el.className= A.join(' ');   
}

Converting java.sql.Date to java.util.Date

In the recent implementation, java.sql.Data is an subclass of java.util.Date, so no converting needed. see here: https://docs.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

A more elegant way I found to achieve this behaviour is simply:

<div id="{{ 'object-' + myScopeObject.index }}"></div>

For my implementation I wanted each input element in a ng-repeat to each have a unique id to associate the label with. So for an array of objects contained inside myScopeObjects one could do this:

<div ng-repeat="object in myScopeObject">
    <input id="{{object.name + 'Checkbox'}}" type="checkbox">
    <label for="{{object.name + 'Checkbox'}}">{{object.name}}</label>
</div>

Being able to generate unique ids on the fly can be pretty useful when dynamically adding content like this.

Html.ActionLink as a button or an image, not a link

if you don't want to use a link, use button. you can add image to button as well:

<button type="button" onclick="location.href='@Url.Action("Create", "Company")'" >
   Create New
   <img alt="New" title="New" src="~/Images/Button/plus.png">
</button>

type="button" performs your action instead of submitting form.

Convert XML to JSON (and back) using Javascript

Disclaimer: I've written fast-xml-parser

Fast XML Parser can help to convert XML to JSON and vice versa. Here is the example;

var options = {
    attributeNamePrefix : "@_",
    attrNodeName: "attr", //default is 'false'
    textNodeName : "#text",
    ignoreAttributes : true,
    ignoreNameSpace : false,
    allowBooleanAttributes : false,
    parseNodeValue : true,
    parseAttributeValue : false,
    trimValues: true,
    decodeHTMLchar: false,
    cdataTagName: "__cdata", //default is 'false'
    cdataPositionChar: "\\c",
};
if(parser.validate(xmlData)=== true){//optional
    var jsonObj = parser.parse(xmlData,options);
}

If you want to parse JSON or JS object into XML then

//default options need not to set
var defaultOptions = {
    attributeNamePrefix : "@_",
    attrNodeName: "@", //default is false
    textNodeName : "#text",
    ignoreAttributes : true,
    encodeHTMLchar: false,
    cdataTagName: "__cdata", //default is false
    cdataPositionChar: "\\c",
    format: false, 
    indentBy: "  ",
    supressEmptyNode: false
};
var parser = new parser.j2xParser(defaultOptions);
var xml = parser.parse(json_or_js_obj);

How to style child components from parent component's CSS file?

I have solved it outside Angular. I have defined a shared scss that I'm importing to my children.

shared.scss

%cell {
  color: #333333;
  background: #eee;
  font-size: 13px;
  font-weight: 600;
}

child.scss

@import 'styles.scss';
.cell {
  @extend %cell;
}

My proposed approach is a way how to solve the problem the OP has asked about. As mentioned at multiple occasions, ::ng-deep, :ng-host will get depreciated and disabling encapsulation is just too much of a code leakage, in my view.

Modal width (increase)

Bootstrap 4 includes sizing utilities. You can change the size to 25/50/75/100% of the page width (I wish there were even more increments).

To use these we will replace the modal-lg class. Both the default width and modal-lg use css max-width to control the modal's width, so first add the mw-100 class to effectively disable max-width. Then just add the width class you want, e.g. w-75.

Note that you should place the mw-100 and w-75 classes in the div with the modal-dialog class, not the modal div e.g.,

<div class='modal-dialog mw-100 w-75'>
    ...
</div>

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

List<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList();

This one works.

Use latest version of Internet Explorer in the webbrowser control

A cheap and easy workaround for it is that you can just put a value which is bigger than 11001 in the FEATURE_BROWSER_EMULATION key. Then it takes the latest IE that is available in the system.

How can I post data as form data instead of a request payload?

Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer

var res = $resource(serverUrl + 'Token', { }, {
                save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
            });

            res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {

            }, function (error) { 

            });

CSS: Control space between bullet and <li>

You can also use a background image replacement as an alternative, giving you total control over vertical and horizontal positioning.

See the answer to this Question

Implement a loading indicator for a jQuery AJAX call

There is a global configuration using jQuery. This code runs on every global ajax request.

<div id='ajax_loader' style="position: fixed; left: 50%; top: 50%; display: none;">
    <img src="themes/img/ajax-loader.gif"></img>
</div>

<script type="text/javascript">
    jQuery(function ($){
        $(document).ajaxStop(function(){
            $("#ajax_loader").hide();
         });
         $(document).ajaxStart(function(){
             $("#ajax_loader").show();
         });    
    });    
</script>

Here is a demo: http://jsfiddle.net/sd01fdcm/

Difference in Months between two dates in JavaScript

You could also consider this solution, this function returns the month difference in integer or number

Passing the start date as the first or last param, is fault tolerant. Meaning, the function would still return the same value.

_x000D_
_x000D_
const diffInMonths = (end, start) => {_x000D_
   var timeDiff = Math.abs(end.getTime() - start.getTime());_x000D_
   return Math.round(timeDiff / (2e3 * 3600 * 365.25));_x000D_
}_x000D_
_x000D_
const result = diffInMonths(new Date(2015, 3, 28), new Date(2010, 1, 25));_x000D_
_x000D_
// shows month difference as integer/number_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Best way to check if MySQL results returned in PHP?

$connect = new mysqli('localhost', 'user', 'password', 'db');
$result = $connect->query("select * from ...");
$count=$result->num_rows;
if(empty($count)){
echo"Query returned nothing";
}
else{
echo"query returned results";
} 

What is the difference between require() and library()?

Another benefit of require() is that it returns a logical value by default. TRUE if the packages is loaded, FALSE if it isn't.

> test <- library("abc")
Error in library("abc") : there is no package called 'abc'
> test
Error: object 'test' not found
> test <- require("abc")
Loading required package: abc
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called 'abc'
> test
[1] FALSE

So you can use require() in constructions like the one below. Which mainly handy if you want to distribute your code to our R installation were packages might not be installed.

if(require("lme4")){
    print("lme4 is loaded correctly")
} else {
    print("trying to install lme4")
    install.packages("lme4")
    if(require(lme4)){
        print("lme4 installed and loaded")
    } else {
        stop("could not install lme4")
    }
}

"date(): It is not safe to rely on the system's timezone settings..."

If you cannot modify your php.ini configuration, you could as well use the following snippet at the beginning of your code:

date_default_timezone_set('Africa/Lagos');//or change to whatever timezone you want

The list of timezones can be found at http://www.php.net/manual/en/timezones.php.

How to set cookies in laravel 5 independently inside controller

Here is a sample code with explanation.

 //Create a response instance
 $response = new Illuminate\Http\Response('Hello World');

 //Call the withCookie() method with the response method
 $response->withCookie(cookie('name', 'value', $minutes));

 //return the response
 return $response;

Cookie can be set forever by using the forever method as shown in the below code.

$response->withCookie(cookie()->forever('name', 'value'));

Retrieving a Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

Logging with Retrofit 2

Retrofit's interceptor is a great feature which allow you work with http requests. There are two types of them: application and network interceptors.

I would recommend to use Charles Web Debugging Proxy Application if you need logging your requests/responses. The output is very similar to Stetho but it is more powerful instrument which you do not need to add as a dependency to an application

How to set a variable inside a loop for /F

Try this:

setlocal EnableDelayedExpansion

...

for /F "tokens=*" %%a in ('type %FileName%') do (
    set z=%%a
    echo !z!
    echo %%a
)

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This solved my issue.

http://www.markhneedham.com/blog/2012/11/28/jersey-com-sun-jersey-api-client-clienthandlerexception-a-message-body-reader-for-java-class-and-mime-media-type-applicationjson-was-not-found/

Including following dependencies in your POM.xml and run Maven -> Update also fixed my issue.

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.19.1</version>
</dependency>
<dependency>
   <groupId>com.owlike</groupId>
   <artifactId>genson</artifactId>
   <version>0.99</version>
</dependency>

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

Waiting till the async task finish its work

wait until this call is finish its executing

You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.

To get result back in UI Thread start AsyncTask as :

String str_result= new RunInBackGround().execute().get();

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Uncomment the line extension=php_mysql.dll in your "php.ini" file and restart Apache.

Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.

See more about installing MySQL extension in manual.

P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).

JUnit Testing private variables?

Yeah you can use reflections to access private variables. Altough not a good idea.

Check this out:

http://en.wikibooks.org/wiki/Java_Programming/Reflection/Accessing_Private_Features_with_Reflection

How to directly initialize a HashMap (in a literal way)?

This is one way.

Map<String, String> h = new HashMap<String, String>() {{
    put("a","b");
}};

However, you should be careful and make sure that you understand the above code (it creates a new class that inherits from HashMap). Therefore, you should read more here: http://www.c2.com/cgi/wiki?DoubleBraceInitialization , or simply use Guava:

Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);

ImmutableMap.of works for up to 5 entries. Otherwise, use the builder: source.

Return Boolean Value on SQL Select Statement

select CAST(COUNT(*) AS BIT) FROM [User] WHERE (UserID = 20070022)

If count(*) = 0 returns false. If count(*) > 0 returns true.

Converting a string to JSON object

Simply use eval function.

var myJson = eval(theJsibStr);

The type WebMvcConfigurerAdapter is deprecated

Since Spring 5 you just need to implement the interface WebMvcConfigurer:

public class MvcConfig implements WebMvcConfigurer {

This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter class

See here:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html

How to open an elevated cmd using command line for Windows?

Similar to some of the other solutions above, I created an elevate batch file which runs an elevated PowerShell window, bypassing the execution policy to enable running everything from simple commands to batch files to complex PowerShell scripts. I recommend sticking it in your C:\Windows\System32 folder for ease of use.

The original elevate command executes its task, captures the output, closes the spawned PowerShell window and then returns, writing out the captured output to the original window.

I created two variants, elevatep and elevatex, which respectively pause and keep the PowerShell window open for more work.

https://github.com/jt-github/elevate

And in case my link ever dies, here's the code for the original elevate batch file:

@Echo Off
REM Executes a command in an elevated PowerShell window and captures/displays output
REM Note that any file paths must be fully qualified!

REM Example: elevate myAdminCommand -myArg1 -myArg2 someValue

if "%1"=="" (
    REM If no command is passed, simply open an elevated PowerShell window.
    PowerShell -Command "& {Start-Process PowerShell.exe -Wait -Verb RunAs}"
) ELSE (
    REM Copy command+arguments (passed as a parameter) into a ps1 file
    REM Start PowerShell with Elevated access (prompting UAC confirmation)
    REM     and run the ps1 file
    REM     then close elevated window when finished
    REM Output captured results

    IF EXIST %temp%\trans.txt del %temp%\trans.txt
    Echo %* ^> %temp%\trans.txt *^>^&1 > %temp%\tmp.ps1
    Echo $error[0] ^| Add-Content %temp%\trans.txt -Encoding Default >> %temp%\tmp.ps1
    PowerShell -Command "& {Start-Process PowerShell.exe -Wait -ArgumentList '-ExecutionPolicy Bypass -File ""%temp%\tmp.ps1""' -Verb RunAs}"
    Type %temp%\trans.txt
)

How to get the selected radio button value using js

check this

<input class="gender" type="radio" name="sex" value="male">Male
<br>
<input class="gender" type="radio" name="sex" value="female">Female


<script type="text/javascript">
$(document).ready(function () {
$(".gender").change(function () {

    var val = $('.gender:checked').val();
    alert(val);
});
});

</script>

Example

How to load external scripts dynamically in Angular?

I have modified @rahul kumars answer, so that it uses Observables instead:

import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";

@Injectable()
export class ScriptLoaderService {
    private scripts: ScriptModel[] = [];

    public load(script: ScriptModel): Observable<ScriptModel> {
        return new Observable<ScriptModel>((observer: Observer<ScriptModel>) => {
            var existingScript = this.scripts.find(s => s.name == script.name);

            // Complete if already loaded
            if (existingScript && existingScript.loaded) {
                observer.next(existingScript);
                observer.complete();
            }
            else {
                // Add the script
                this.scripts = [...this.scripts, script];

                // Load the script
                let scriptElement = document.createElement("script");
                scriptElement.type = "text/javascript";
                scriptElement.src = script.src;

                scriptElement.onload = () => {
                    script.loaded = true;
                    observer.next(script);
                    observer.complete();
                };

                scriptElement.onerror = (error: any) => {
                    observer.error("Couldn't load script " + script.src);
                };

                document.getElementsByTagName('body')[0].appendChild(scriptElement);
            }
        });
    }
}

export interface ScriptModel {
    name: string,
    src: string,
    loaded: boolean
}

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

Apparently, document.addEventListener() is unreliable, and hence, my error. Use window.addEventListener() with the same parameters, instead.

Java out.println() how is this possible?

out is a PrintStream type of static variable(object) of System class and println() is function of the PrintStream class.

class PrintStream
{
    public void println(){}    //member function
    ...
}

class System
{
    public static final PrintStream out;   //data member
    ...
}

That is why the static variable(object) out is accessed with the class name System which further invokes the method println() of it's type PrintStream (which is a class).

How to install sshpass on mac?

Please follow the steps below to install sshpass in mac.

curl -O -L https://fossies.org/linux/privat/sshpass-1.06.tar.gz && tar xvzf sshpass-1.06.tar.gz

cd sshpass-1.06

./configure

sudo make install

Make javascript alert Yes/No Instead of Ok/Cancel

"Confirm" in Javascript stops the whole process until it gets a mouse response on its buttons. If that is what you are looking for, you can refer jquery-ui but if you have nothing running behind your process while receiving the response and you control the flow programatically, take a look at this. You will have to hard-code everything by yourself but you have complete command over customization. https://www.w3schools.com/howto/howto_css_modals.asp

Failed to Connect to MySQL at localhost:3306 with user root

I had this exact problem after my last windows update and none of the above solutions worked. I know it's an old question, but if anyone has this problem in the future:

I managed to solve it by going to windows control panel > administrative tools > Component Services and finding "MySQL57" in the Services(local) list (I assume your server might have a slightly different name).

There I went to properties by right clicking and changed the Startup Type to Automatic under the General tab. Then I went on the Log On tab and checked "Allow Service to interact with Desktop".

If none of that works, you can try checking the "This account" box and filling both password fields with the root password you set up after installing the server (leave account blank).

I know it's a lot to do and most of these steps must be innefective, but I did it all at once and frankly have no clue which one solved the problem. Good luck I hope it helps.

Extract digits from a string in Java

You can use regex and delete non-digits.

str = str.replaceAll("\\D+","");

How to remove specific element from an array using python

If you want to delete the index of array:

Use array_name.pop(index_no.)

ex:-

>>> arr = [1,2,3,4]
>>> arr.pop(2)
>>>arr
[1,2,4]

If you want to delete a particular string/element from the array then

>>> arr1 = ['python3.6' , 'python2' ,'python3']
>>> arr1.remove('python2')
>>> arr1
['python3.6','python3']