Programs & Examples On #Jquery jscrollpane

jScrollPane is a cross-browser jQuery plugin by [Kelvin Luck](http://www.kelvinluck.com) which can be used to generate custom scrollbars on HTML block elements.

How to check if a number is between two values?

You can use Multiple clause in if condition instead of writing

if (windowsize > 500-600) {
    // do this
}

because this really makes no sense logically JavaScript will read your if condition like

windowSize > -100 

because it calculates 500-600 to -100

You should use && for strict checking both cases for example which will look like this

if( windowSize > 500 && windowSize < 600 ){

// Then doo something

}

MVC Calling a view from a different controller

To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.

public class CommentsController : Controller
{
    public ActionResult Index()
    { 
        return View("../Articles/Index", model );
    }
}

and

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}

Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.

How are POST and GET variables handled in Python?

suppose you're posting a html form with this:

<input type="text" name="username">

If using raw cgi:

import cgi
form = cgi.FieldStorage()
print form["username"]

If using Django, Pylons, Flask or Pyramid:

print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method

Using Turbogears, Cherrypy:

from cherrypy import request
print request.params['username']

Web.py:

form = web.input()
print form.username

Werkzeug:

print request.form['username']

If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:

def index(self, username):
    print username

Google App Engine:

class SomeHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.get('username') # this will get the value from the field named username
        self.response.write(name) # this will write on the document

So you really will have to choose one of those frameworks.

Using context in a fragment

You can use getActivity(), which returns the activity associated with a fragment.
The activity is a context (since Activity extends Context).

Prevent double submission of forms in jQuery

Update in 2018: I just got some points for this old answer, and just wanted to add that the best solution would be to make the operation idempotent so that duplicate submissions are harmless.

Eg, if the form creates an order, put a unique ID in the form. The first time the server sees an order creation request with that id, it should create it and respond "success". Subsequent submissions should also respond "success" (in case the client didn't get the first response) but shouldn't change anything.

Duplicates should be detected via a uniqueness check in the database to prevent race conditions.


I think that your problem is this line:

$('input').attr('disabled','disabled');

You're disabling ALL the inputs, including, I'd guess, the ones whose data the form is supposed to submit.

To disable just the submit button(s), you could do this:

$('button[type=submit], input[type=submit]').prop('disabled',true);

However, I don't think IE will submit the form if even those buttons are disabled. I'd suggest a different approach.

A jQuery plugin to solve it

We just solved this problem with the following code. The trick here is using jQuery's data() to mark the form as already submitted or not. That way, we don't have to mess with the submit buttons, which freaks IE out.

// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
  $(this).on('submit',function(e){
    var $form = $(this);

    if ($form.data('submitted') === true) {
      // Previously submitted - don't submit again
      e.preventDefault();
    } else {
      // Mark it so that the next submit can be ignored
      $form.data('submitted', true);
    }
  });

  // Keep chainability
  return this;
};

Use it like this:

$('form').preventDoubleSubmission();

If there are AJAX forms that should be allowed to submit multiple times per page load, you can give them a class indicating that, then exclude them from your selector like this:

$('form:not(.js-allow-double-submission)').preventDoubleSubmission();

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you can always do this as 'IF' condition evaluates only when the condition inside it goes true. C does not have a boolean return type and thus returns a non-zero value when the condition is true while returns 0 whenever the condition in 'IF' turns out to be false. The non zero value returned by default is 1. Thus, both ways of writing the code are correct while I will always prefer the second one.

Differences Between vbLf, vbCrLf & vbCr Constants

 Constant   Value               Description
 ----------------------------------------------------------------
 vbCr       Chr(13)             Carriage return
 vbCrLf     Chr(13) & Chr(10)   Carriage return–linefeed combination
 vbLf       Chr(10)             Line feed
  • vbCr : - return to line beginning
    Represents a carriage-return character for print and display functions.

  • vbCrLf : - similar to pressing Enter
    Represents a carriage-return character combined with a linefeed character for print and display functions.

  • vbLf : - go to next line
    Represents a linefeed character for print and display functions.


Read More from Constants Class

How to initialize var?

Why wouldn't this be possible?

var theNameOfTheVar = (TheType)null;

eg:

var name = (string)null;

Simple as that.

What is a MIME type?

It is useful to think of MIME in the context of the client-server model. Clients and servers communicate over what is known as the HTTP protocol. In a http request or response, we can have a body. The Content-type or MIME type specifies what is the type of the body, like text/javascript or something else like audio, video, etc.

However, MIME types are not limited just to HTTP.

As the name suggests, MIME stands for Multipurpose Internet Mail Extensions. Originally, SMTP only supported ascii-encodings. However, there as a need for more. We could use MIME to slap a label on the content being transmitted or received.

How to make a UILabel clickable?

Pretty easy to overlook like I did, but don't forget to use UITapGestureRecognizer rather than UIGestureRecognizer.

Convert float to double without losing precision

This is due the contract of Float.toString(float), which says in part:

How many digits must be printed for the fractional part […]? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type float. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument f. Then f must be the float value nearest to x; or, if two float values are equally close to x, then f must be one of them and the least significant bit of the significand of f must be 0.

How to tell if node.js is installed or not

Check the node version using node -v. Check the npm version using npm -v. If these commands gave you version number you are good to go with NodeJs development

Time to test node

Create a Directory using mkdir NodeJs. Inside the NodeJs folder create a file using touch index.js. Open your index.js either using vi or in your favourite text editor. Type in console.log('Welcome to NodesJs.') and save it. Navigate back to your saved file and type node index.js. If you see Welcome to NodesJs. you did a nice job and you are up with NodeJs.

Removing all unused references from a project in Visual Studio projects

The Resharper extension will do this for you.

This extension supports Visual Studio 2005 through 2017.

While the compiler won't include unused assemblies, extraneous using statements and references slows down Visual Studio and Intellisense, since there's more code the tools have to consider.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

Changing capitalization of filenames in Git

Starting Git 2.0.1 (June 25th, 2014), a git mv will just work on a case insensitive OS.

See commit baa37bf by David Turner (dturner-tw).

mv: allow renaming to fix case on case insensitive filesystems

"git mv hello.txt Hello.txt" on a case insensitive filesystem always triggers "destination already exists" error, because these two names refer to the same path from the filesystem's point of view and requires the user to give "--force" when correcting the case of the path recorded in the index and in the next commit.

Detect this case and allow it without requiring "--force".

git mv hello.txt Hello.txt just works (no --force required anymore).


The other alternative is:

git config --global core.ignorecase false

And rename the file directly; git add and commit.

Set value for particular cell in pandas DataFrame with iloc

You can use:

df.set_value('Row_index', 'Column_name', value)

set_valye is ~100 times faster than .ix method. It also better then use df['Row_index']['Column_name'] = value.

But since set_value is deprecated now so .iat/.at are good replacements.

For example if we have this data_frame

   A   B   C
0  1   8   4 
1  3   9   6
2  22 33  52

if we want to modify the value of the cell [0,"A"] we can do

df.iat[0,0] = 2

or df.at[0,'A'] = 2

Select first 4 rows of a data.frame in R

For at DataFrame one can simply type

head(data, num=10L)

to get the first 10 for example.

For a data.frame one can simply type

head(data, 10)

to get the first 10.

Consistency of hashCode() on a Java string

Another (!) issue to worry about is the possible change of implementation between early/late versions of Java. I don't believe the implementation details are set in stone, and so potentially an upgrade to a future Java version could cause problems.

Bottom line is, I wouldn't rely on the implementation of hashCode().

Perhaps you can highlight what problem you're actually trying to solve by using this mechanism, and that will highlight a more suitable approach.

Remove characters from a string

Another method that no one has talked about so far is the substr method to produce strings out of another string...this is useful if your string has defined length and the characters your removing are on either end of the string...or within some "static dimension" of the string.

Close iOS Keyboard by touching anywhere using Swift

A simple way to do this is by selecting the text field and using the method endEditing(true)

e.g

exampleTextField.endEditing(true)

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

It could be that your default format doesn't match the file extension. You should specify the file format along with the filename, making sure the format matches the extension:

With someWorkbook
.SaveAs "C:\someDirector\Awesome.xlsm", fileformat:=xlOpenXMLWorkbookMacroEnabled
End With

OTOH, I don't see an extension on your .SaveAs filename. Maybe you need to supply one when doing this programmatically. That makes sense--not having to supply an extension from the GUI interface is convenient, but we programmers are expected to write unambiguous code. I suggest adding the extension and the matching format. See this msdn page for a list of file formats. To be honest, I don't recognize a lot o the descripions.

xlExcel8 = 56 is the .xls format

xlExcel12 = 50 is the .xlsb format

xlOpenXMLWorkbook = 51 is the .xlsx format

xlOpenXMLWorkbookMacroEnabled = 52 is the .xlsm format

xlWorkbookDefault is also listed with a value of 51, which puzzles me since I thought the default format could be changed.

Authorize attribute in ASP.NET MVC

The tag in web.config is based on paths, whereas MVC works with controller actions and routes.

It is an architectural decision that might not make a lot of difference if you just want to prevent users that aren't logged in but makes a lot of difference when you try to apply authorization based in Roles and in cases that you want custom handling of types of Unauthorized.

The first case is covered from the answer of BobRock.

The user should have at least one of the following Roles to access the Controller or the Action

[Authorize(Roles = "Admin, Super User")]

The user should have both these roles in order to be able to access the Controller or Action

[Authorize(Roles = "Super User")]
[Authorize(Roles = "Admin")]

The users that can access the Controller or the Action are Betty and Johnny

[Authorize(Users = "Betty, Johnny")]

In ASP.NET Core you can use Claims and Policy principles for authorization through [Authorize].

options.AddPolicy("ElevatedRights", policy =>
                  policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));

[Authorize(Policy = "ElevatedRights")]

The second comes very handy in bigger applications where Authorization might need to be implemented with different restrictions, process and handling according to the case. For this reason we can Extend the AuthorizeAttribute and implement different authorization alternatives for our project.

public class CustomAuthorizeAttribute: AuthorizeAttribute  
{  
    public override void OnAuthorization(AuthorizationContext filterContext)  
    {  }
}

The "correct-completed" way to do authorization in ASP.NET MVC is using the [Authorize] attribute.

How to access /storage/emulated/0/

Plug in your device and run adb shell which will get you a command shell on your device. You don't have permission to read /storage/emulated/ but since you know it's in subdirectory 0 just go cd /storage/emulated/0 and you will be able to look around and interact as aspected.

Note: you can use adb wirelessly as well

How can I disable editing cells in a WPF Datagrid?

I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.

<DataGrid IsReadOnly="False">
    <DataGrid.Columns>
        <DataGridTextColumn IsReadOnly="True"/>
        <DataGridTextColumn IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

Putting HTML inside Html.ActionLink(), plus No Link Text?

A custom HtmlHelper extension is another option. Note: ParameterDictionary is my own type. You could substitute a RouteValueDictionary but you'd have to construct it differently.

public static string ActionLinkSpan( this HtmlHelper helper, string linkText, string actionName, string controllerName, object htmlAttributes )
{
    TagBuilder spanBuilder = new TagBuilder( "span" );
    spanBuilder.InnerHtml = linkText;

    return BuildNestedAnchor( spanBuilder.ToString(), string.Format( "/{0}/{1}", controllerName, actionName ), htmlAttributes );
}

private static string BuildNestedAnchor( string innerHtml, string url, object htmlAttributes )
{
    TagBuilder anchorBuilder = new TagBuilder( "a" );
    anchorBuilder.Attributes.Add( "href", url );
    anchorBuilder.MergeAttributes( new ParameterDictionary( htmlAttributes ) );
    anchorBuilder.InnerHtml = innerHtml;

    return anchorBuilder.ToString();
}

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

How to run batch file from network share without "UNC path are not supported" message?

I needed to be able to just Windows Explorer browse through the server share, then double-click launch the batch file. @dbenham led me to an easier solution for my scenario (without the popd worries):

:: Capture UNC or mapped-drive path script was launched from
set NetPath=%~dp0

:: Assumes that setup.exe is in the same UNC path
%NetPath%setup.exe

:: Note that NetPath has a trailing backslash ("\")
robocopy.exe "%NetPath%Custom" /copyall "C:\Program Files (x86)\WP\Custom Templates"
Regedit.exe /s %NetPath%..\WPX5\Custom\Migrate.reg

:: I am not sure if WPX5 was typo, so use ".." for parent directory
set NetPath=
pause

Angularjs if-then-else construction in expression

Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:

condition && (answer if true) || (answer if false)

So in example, something like this would work:

<div ng-repeater="item in items">
    <div>{{item.description}}</div>
    <div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>

UPDATE: Angular 1.1.5 added support for ternary operators:

{{myVar === "two" ? "it's true" : "it's false"}}

Centering FontAwesome icons vertically and horizontally

I just lowered the height to 28px on the .login-icon [class*='icon-'] Here's the fiddle: http://jsfiddle.net/mZHg7/

.login-icon [class*='icon-']{
    height: 28px;
    width: 50px;
    display: inline-block;
    text-align: center;
    vertical-align: baseline;
}

Iterating over a 2 dimensional python list

>>> mylist = [["%s,%s"%(i,j) for j in range(columns)] for i in range(rows)]
>>> mylist
[['0,0', '0,1', '0,2'], ['1,0', '1,1', '1,2'], ['2,0', '2,1', '2,2']]
>>> zip(*mylist)
[('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1'), ('0,2', '1,2', '2,2')]
>>> sum(zip(*mylist),())
('0,0', '1,0', '2,0', '0,1', '1,1', '2,1', '0,2', '1,2', '2,2')

How do I trim whitespace?

If using Python 3: In your print statement, finish with sep="". That will separate out all of the spaces.

EXAMPLE:

txt="potatoes"
print("I love ",txt,"",sep="")

This will print: I love potatoes.

Instead of: I love potatoes .

In your case, since you would be trying to get ride of the \t, do sep="\t"

How to add a footer in ListView?

Answers here are a bit outdated. Though the code remains the same there are some changes in the behavior.

public class MyListActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        TextView footerView = (TextView) ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
        getListView().addFooterView(footerView);
        setListAdapter(new ArrayAdapter<String>(this, getResources().getStringArray(R.array.news)));
    }
}

Info about addFooterView() method

Add a fixed view to appear at the bottom of the list. If addFooterView() is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.

Most of the answers above stress very important point -

addFooterView() must be called before calling setAdapter().This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.

From Kitkat this has changed.

Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.

Documentation

Toolbar overlapping below status bar

Just set this to v21/styles.xml file

 <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 <item name="android:statusBarColor">@color/colorPrimaryDark</item>

and be sure

 <item name="android:windowTranslucentStatus">false</item>

How can I add private key to the distribution certificate?

Since the existing answers were written, Xcode's interface has been updated and they're no longer correct (notably the Click on Window, Organiser // Expand the Teams section step). Now the instructions for importing an existing certificate are as follows:

To export selected certificates

  1. Choose Xcode > Preferences.
  2. Click Accounts at the top of the window.
  3. Select the team you want to view, and click View Details.
  4. Control-click the certificate you want to export in the Signing Identities table and choose Export from the pop-up menu.

Export certificate demo

  1. Enter a filename in the Save As field and a password in both the Password and Verify fields. The file is encrypted and password protected.
  2. Click Save. The file is saved to the location you specified with a .p12 extension.

Source (Apple's documentation)

To import it, I found that Xcode's let-me-help-you menu didn't recognise the .p12 file. Instead, I simply imported it manually into Keychain, then Xcode built and archived without complaining.

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

C# Enum - How to Compare Value

You can use Enum.Parse like, if it is string

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")

What is copy-on-write?

Copy-on-write is a technique to reduce the memory usage of resource copies using deferred copy. The resource copies are initially virtual (i.e. they share memory) and only become real (i.e. they have their own memory) on the first write operation, hence the name ‘copy-on-write’.

Here after is a Python implementation of the copy-on-write technique using the proxy design pattern. A ValueProxy object (the proxy) implements the copy-on-write technique by:

  • having an attribute bound to an immutable Value object (the subject);
  • translating copy requests to the creation of a new ValueProxy object sharing the same subject attribute as the original ValueProxy object;
  • forwarding read requests to the subject attribute;
  • translating write requests to the creation of a new immutable Value object with the new state and the rebinding of the subject attribute to this new immutable Value object.
import abc

class BaseValue(abc.ABC):
    @abc.abstractmethod
    def read(self):
        raise NotImplementedError
    @abc.abstractmethod
    def write(self, data):
        raise NotImplementedError

class Value(BaseValue):
    def __init__(self, data):
        self.data = data
    def read(self):
        return self.data
    def write(self, data):
        pass

class ValueProxy(BaseValue):
    def __init__(self, subject):
        self.subject = subject
    def read(self):
        return self.subject.read()
    def write(self, data):
        self.subject = Value(data)
    def clone(self):
        return ValueProxy(self.subject)

v1 = ValueProxy(Value('foo'))
v2 = v1.clone()  # shares the immutable Value object between the copies
assert v1.subject is v2.subject
v2.write('bar')  # creates a new immutable Value object with the new state
assert v1.subject is not v2.subject

ssh remote host identification has changed

Simple one-liner solution, tested on mac:

sed '/212.156.48.110/d' ~/.ssh/known_hosts > ~/.ssh/known_hosts

Deletes only the target ssh host IP from know hosts.

where 212.156.48.110 is replaced by the target host IP address.

Cause: Happened because the target IP was already known for a different machine due to port forwarding. Deleting the target IP before connecting will fix the issue.

Coding Conventions - Naming Enums

Enums are classes and should follow the conventions for classes. Instances of an enum are constants and should follow the conventions for constants. So

enum Fruit {APPLE, ORANGE, BANANA, PEAR};

There is no reason for writing FruitEnum any more than FruitClass. You are just wasting four (or five) characters that add no information.

Java itself recommends this approach and it is used in their examples.

Tests not running in Test Explorer

In my case, it was because one test project in my solution had the MSTest.TestFramework and MSTest.TestAdapter nuget packages installed but the others did not. These packages were apparently not required to run tests until one project in the solution had them installed.

The issue was fixed by installing those packages on test projects missing them.

Extract number from string with Oracle function

If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr function like this:

regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')

What is the difference between an Instance and an Object?

The Instance and Object are from Object Oriented Programming.

For some programming languages like Java, C++, and Smalltalk, it is important to describe and understand code. In other languages that used in Structured Programming, this concept doesn't exist.

This is a view from Structural Programming. There's no real significant difference that should consume too much of your time. There might be some fancy language that some people might take up a lot of spaces to write about, but at the end of the day, as far as a coder, developer, programmer, architect, is concerned, an instance of a class and an object mean the same thing and can often be used interchangeably. I have never met anyone in my career that would be picky and spend a half-hour trying to point out the differences because there's really none. Time can be better spent on other development efforts.

UPDATE With regards to Swift, this is what Apple who invented Swift prefers :

An instance of a class is traditionally known as an object. However, Swift classes and structures are much closer in functionality than in other languages, and much of this chapter describes functionality that can apply to instances of either a class or a structure type. Because of this, the more general term instance is used.

The remote host closed the connection. The error code is 0x800704CD

I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.

To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).

You need to decide what the best way forward is depending on your app.

How to compare two colors for similarity/difference

A color value has more than one dimension, so there is no intrinsic way to compare two colors. You have to determine for your use case the meaning of the colors and thereby how to best compare them.

Most likely you want to compare the hue, saturation and/or lightness properties of the colors as oppposed to the red/green/blue components. If you are having trouble figuring out how you want to compare them, take some pairs of sample colors and compare them mentally, then try to justify/explain to yourself why they are similar/different.

Once you know which properties/components of the colors you want to compare, then you need to figure out how to extract that information from a color.

Most likely you will just need to convert the color from the common RedGreenBlue representation to HueSaturationLightness, and then calculate something like

avghue = (color1.hue + color2.hue)/2
distance = abs(color1.hue-avghue)

This example would give you a simple scalar value indicating how far the gradient/hue of the colors are from each other.

See HSL and HSV at Wikipedia.

Iterating on a file doesn't work the second time

Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using f.seek(0) to reposition to the start of the file, or to close it and then open it again which will start from the beginning of the file.

If you prefer you can use the with syntax instead which will automatically close the file for you.

e.g.,

with open('baby1990.html', 'rU') as f:
  for line in f:
     print line

once this block is finished executing, the file is automatically closed for you, so you could execute this block repeatedly without explicitly closing the file yourself and read the file this way over again.

Java String new line

\n is used for making separate line;

Example:

System.out.print("I" +'\n'+ "am" +'\n'+ "boy"); 

Result:

I
am
boy

What is an idempotent operation?

An idempotent operation can be repeated an arbitrary number of times and the result will be the same as if it had been done only once. In arithmetic, adding zero to a number is idempotent.

Idempotence is talked about a lot in the context of "RESTful" web services. REST seeks to maximally leverage HTTP to give programs access to web content, and is usually set in contrast to SOAP-based web services, which just tunnel remote procedure call style services inside HTTP requests and responses.

REST organizes a web application into "resources" (like a Twitter user, or a Flickr image) and then uses the HTTP verbs of POST, PUT, GET, and DELETE to create, update, read, and delete those resources.

Idempotence plays an important role in REST. If you GET a representation of a REST resource (eg, GET a jpeg image from Flickr), and the operation fails, you can just repeat the GET again and again until the operation succeeds. To the web service, it doesn't matter how many times the image is gotten. Likewise, if you use a RESTful web service to update your Twitter account information, you can PUT the new information as many times as it takes in order to get confirmation from the web service. PUT-ing it a thousand times is the same as PUT-ing it once. Similarly DELETE-ing a REST resource a thousand times is the same as deleting it once. Idempotence thus makes it a lot easier to construct a web service that's resilient to communication errors.

Further reading: RESTful Web Services, by Richardson and Ruby (idempotence is discussed on page 103-104), and Roy Fielding's PhD dissertation on REST. Fielding was one of the authors of HTTP 1.1, RFC-2616, which talks about idempotence in section 9.1.2.

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

How do I use a PriorityQueue?

Here is the simple example which you can use for initial learning:

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;

public class PQExample {

    public static void main(String[] args) {
        //PriorityQueue with Comparator
        Queue<Customer> cpq = new PriorityQueue<>(7, idComp);
        addToQueue(cpq);
        pollFromQueue(cpq);
    }

    public static Comparator<Customer> idComp = new Comparator<Customer>(){

        @Override
        public int compare(Customer o1, Customer o2) {
            return (int) (o1.getId() - o2.getId());
        }

    };

    //utility method to add random data to Queue
    private static void addToQueue(Queue<Customer> cq){
        Random rand = new Random();
        for(int i=0;i<7;i++){
            int id = rand.nextInt(100);
            cq.add(new Customer(id, "KV"+id));
        }
    }


    private static void pollFromQueue(Queue<Customer> cq){
        while(true){
            Customer c = cq.poll();
            if(c == null) break;
            System.out.println("Customer Polled : "+c.getId() + " "+ c.getName());
        }
    }

}

Which are more performant, CTE or temporary tables?

Late to the party, but...

The environment I work in is highly constrained, supporting some vendor products and providing "value-added" services like reporting. Due to policy and contract limitations, I am not usually allowed the luxury of separate table/data space and/or the ability to create permanent code [it gets a little better, depending upon the application].

IOW, I can't usually develop a stored procedure or UDFs or temp tables, etc. I pretty much have to do everything through MY application interface (Crystal Reports - add/link tables, set where clauses from w/in CR, etc.). One SMALL saving grace is that Crystal allows me to use COMMANDS (as well as SQL Expressions). Some things that aren't efficient through the regular add/link tables capability can be done by defining a SQL Command. I use CTEs through that and have gotten very good results "remotely". CTEs also help w/ report maintenance, not requiring that code be developed, handed to a DBA to compile, encrypt, transfer, install, and then require multiple-level testing. I can do CTEs through the local interface.

The down side of using CTEs w/ CR is, each report is separate. Each CTE must be maintained for each report. Where I can do SPs and UDFs, I can develop something that can be used by multiple reports, requiring only linking to the SP and passing parameters as if you were working on a regular table. CR is not really good at handling parameters into SQL Commands, so that aspect of the CR/CTE aspect can be lacking. In those cases, I usually try to define the CTE to return enough data (but not ALL data), and then use the record selection capabilities in CR to slice and dice that.

So... my vote is for CTEs (until I get my data space).

Cannot run Eclipse; JVM terminated. Exit code=13

1 ) Open the SpringToolSuite4.ini File.
2 ) Search For the "openFile" text in the SpringToolSuite4.ini file.
3 ) Provide the javaw.exe file location in SpringToolSuite4.ini
4 ) Note : Provide the New Line between -vm and your javaw.exe file location path as shown below.

openFile
-vm
C:\Program Files\Java\jdk1.8.0\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Xms256m

How to run a command in the background and get no output?

Use nohup if your background job takes a long time to finish or you just use SecureCRT or something like it login the server.

Redirect the stdout and stderr to /dev/null to ignore the output.

nohup /path/to/your/script.sh > /dev/null 2>&1 &

HTTP status code for update and delete?

In addition to 200 and 204, 205 (Reset Content) could be a valid response.

The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent ... [e.g.] clearing of the form in which the input is given.

Changing selection in a select with the Chosen plugin

Sometimes you have to remove the current options in order to manipulate the selected options.

Here is an example how to set options:

<select id="mySelectId" class="chosen-select" multiple="multiple">
  <option value=""></option>
  <option value="Argentina">Argentina</option>
  <option value="Germany">Germany</option>
  <option value="Greece">Greece</option>
  <option value="Japan">Japan</option>
  <option value="Thailand">Thailand</option>
</select>

<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);

function activateChosen($container, param) {
    param = param || {};
    $container.find('.chosen-select:visible').chosen(param);
    $container.find('.chosen-select').trigger("chosen:updated");
}

function selectChosenOptions($select, values) {
    $select.val(null);                                  //delete current options
    $select.val(values);                                //add new options
    $select.trigger('chosen:updated');
}
</script>

JSFiddle (including howto append options): https://jsfiddle.net/59x3m6op/1/

How can I revert a single file to a previous version?

Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.

Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.

I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5, copy the file somewhere else, checkout master, copy the file back, then commit.

Vue equivalent of setTimeout?

You can use Vue.nextTick

addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                Vue.nextTick(() =>{
                    this.basketAddSuccess = false;
                });
            }

How do I generate a SALT in Java for Salted-Hash?

You were right regarding how you want to generate salt i.e. its nothing but a random number. For this particular case it would protect your system from possible Dictionary attacks. Now, for the second problem what you could do is instead of using UTF-8 encoding you may want to use Base64. Here, is a sample for generating a hash. I am using Apache Common Codecs for doing the base64 encoding you may select one of your own

public byte[] generateSalt() {
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);
        return bytes;
    }

public String bytetoString(byte[] input) {
        return org.apache.commons.codec.binary.Base64.encodeBase64String(input);
    }

public byte[] getHashWithSalt(String input, HashingTechqniue technique, byte[] salt) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(technique.value);
        digest.reset();
        digest.update(salt);
        byte[] hashedBytes = digest.digest(stringToByte(input));
        return hashedBytes;
    }
public byte[] stringToByte(String input) {
        if (Base64.isBase64(input)) {
            return Base64.decodeBase64(input);

        } else {
            return Base64.encodeBase64(input.getBytes());
        }
    }

Here is some additional reference of the standard practice in password hashing directly from OWASP

How do I remove  from the beginning of a file?

For me, this worked:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

If I remove this meta, the  appears again. Hope this helps someone...

How to clear basic authentication details in chrome

  1. Press the key combination Ctrl+Shift+Delete
  2. You will see popup in chrome enter image description here

  3. Check the above options and click clear data and you are done.

Can I use Twitter Bootstrap and jQuery UI at the same time?

Yes you can use both. js bootstrap from twitter is a collection of jquery plugins. There shohuldn't be any conflict with jQuery UI.

Regarding bandwidth overload, it really depends on how you handle the requests to load all of your js files. if you really dont want to make multiple requests to the server to request for each file, just append them together and minimize. Or you probably can get rid of some js bootstrap plugins you dont need. it is very modular.

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

How to make input type= file Should accept only pdf and xls

You could do so by using the attribute accept and adding allowed mime-types to it. But not all browsers do respect that attribute and it could easily be removed via some code inspector. So in either case you need to check the file type on the server side (your second question).

Example:

<input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />

To your third question "And when I click the files (PDF/XLS) on webpage it automatically should open.":

You can't achieve that. How a PDF or XLS is opened on the client machine is set by the user.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

to fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the
deserialized type so that it is a normal .NET type (e.g. not a primitive type like
integer, not a collection type like an array or List) that can be deserialized from a
JSON object.`

The whole message indicates that it is possible to serialize to a List object, but the input must be a JSON list. This means that your JSON must contain

"accounts" : [{<AccountObjectData}, {<AccountObjectData>}...],

Where AccountObject data is JSON representing your Account object or your Badge object

What it seems to be getting currently is

"accounts":{"github":"sergiotapia"}

Where accounts is a JSON object (denoted by curly braces), not an array of JSON objects (arrays are denoted by brackets), which is what you want. Try

"accounts" : [{"github":"sergiotapia"}]

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

Just run setup_xampp.bat from shell (shell from XAMPP control panel)and the paths should be set automatically for the portable version of XAMPP for windows. It has worked for me.

Error: Generic Array Creation

Besides the way suggested in the "possible duplicate", the other main way of getting around this problem is for the array itself (or at least a template of one) to be supplied by the caller, who will hopefully know the concrete type and can thus safely create the array.

This is the way methods like ArrayList.toArray(T[]) are implemented. I'd suggest you take a look at that method for inspiration. Better yet, you should probably be using that method anyway as others have noted.

Difference between subprocess.Popen and os.system

subprocess.Popen() is strict super-set of os.system().

Better way to get type of a Javascript variable?

You may find the following function useful:

function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

Or in ES7 (comment if further improvements)

const { toString } = Object.prototype;

function typeOf(obj) {
  const stringified = obj::toString();
  const type = stringified.split(' ')[1].slice(0, -1);
      
  return type.toLowerCase();
}

Results:

typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new Error) //error
typeOf(Promise.resolve()) //promise
typeOf(function *() {}) //generatorfunction
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
typeOf(async function() {}) //asyncfunction

Thanks @johnrees for notifying me of: error, promise, generatorfunction

Http Basic Authentication in Java using HttpClient?

while using Header array

String auth = Base64.getEncoder().encodeToString(("test1:test1").getBytes());
Header[] headers = {
    new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()),
    new BasicHeader("Authorization", "Basic " +auth)
};

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How to force open links in Chrome not download them?

To make certain file types OPEN on your computer, instead of Chrome Downloading...

You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE.

Now the file type will always OPEN using your default program.

To reset this feature, go to Settings / Advance Settings and under the "Download.." section, there's a button to reset 'all' Auto Downloads

Hope this helps.. :-)

Visual Instructions found here:

http://www.presentermedia.com/blog/2013/10/my-file-automatically-opens-instead-of-saving-with-chrome/

how to remove new lines and returns from php string?

you can pass an array of strings to str_replace, so you can do all in a single statement:

$content = str_replace(["\r\n", "\n", "\r"], "", $content);

How can I execute Python scripts using Anaconda's version of Python?

Set your python path to the Anaconda version instead

Windows has a built-in dialog for changing environment variables (following guide applies to XP classical view): Right-click the icon for your machine (usually located on your Desktop and called “My Computer”) and choose Properties there. Then, open the Advanced tab and click the Environment Variables button.

In short, your path is:

My Computer ? Properties ? Advanced ? Environment Variables In this dialog, you can add or modify User and System variables. To change System variables, you need non-restricted access to your machine (i.e. Administrator rights).

Find your PATH variable and add the location of your Anaconda directory.

Example of someone doing it here: How to add to the PYTHONPATH in Windows, so it finds my modules/packages? Make sure that you sub path out for the Anaconda file though.

What is a good practice to check if an environmental variable exists or not?

My comment might not be relevant to the tags given. However, I was lead to this page from my search. I was looking for similar check in R and I came up the following with the help of @hugovdbeg post. I hope it would be helpful for someone who is looking for similar solution in R

'USERNAME' %in% names(Sys.getenv())

Create a CSS rule / class with jQuery at runtime

You can use insertRule if you don't need to support IE < 9, according to dottoro. There's a bit of cross browser code over there as well.

document.styleSheets[0].insertRule('#my-window {\
    position: fixed;\
    z-index: 102;\
    display:none;\
    top:50%;\
    left:50%;\
}', 0)

How to keep environment variables when using sudo

A simple wrapper function (or in-line for loop)

I came up with a unique solution because:

  • sudo -E "$@" was leaking variables that was causing problems for my command
  • sudo VAR1="$VAR1" ... VAR42="$VAR42" "$@" was long and ugly in my case

demo.sh

#!/bin/bash

function sudo_exports(){
    eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"
}

# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh

export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."

export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"

# clean function style
sudo_exports ./sudo_test.sh

# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh

Result

$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.

How?

This is made possible by a feature of the bash builtin printf. The %q produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0

Trigger a keypress/keydown/keyup event in JS/jQuery?

To trigger an enter keypress, I had to modify @ebynum response, specifically, using the keyCode property.

e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);

python .replace() regex

You can use the re module for regexes, but regexes are probably overkill for what you want. I might try something like

z.write(article[:article.index("</html>") + 7]

This is much cleaner, and should be much faster than a regex based solution.

How to set Java SDK path in AndroidStudio?

Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear. enter image description here

SQLite add Primary Key

I had the same problem and the best solution I found is to first create the table defining primary key and then to use insert into statement.

CREATE TABLE mytable (
field1 INTEGER PRIMARY KEY,
field2 TEXT
);

INSERT INTO mytable 
SELECT field1, field2 
FROM anothertable;

Is it possible to program iPhone in C++

I use Objective-C to slap the UI together.
But the hard guts of the code is still written in C++.

That is the main purpose of Objective-C the UI interface and handling the events.
And it works great for that purpose.

I still like C++ as the backend for the code though (but that's mainly becuase I like C++) you could quite easily use Objective-C for the backend of the application as well.

How to print something when running Puppet client?

Here is the puppet script with all the available puppet log functions.

log_levels.pp

node default {
  notice("try to run this script with -v and -d to see difference between log levels")
  notice("function documentation is available here: http://docs.puppetlabs.com/references/latest/function.html")
  notice("--------------------------------------------------------------------------")

  debug("this is debug. visible only with -d or --debug")
  info("this is info. visible only with -v or --verbose or -d or --debug")
  alert("this is alert. always visible")
  crit("this is crit. always visible")
  emerg("this is emerg. always visible")
  err("this is err. always visible")
  warning("and this is warning. always visible")
  notice("this is notice. always visible")
  #fail will break execution
  fail("this is fail. always visible. fail will break execution process")

}

Script output (on puppet 2.7): different log levels colors

NB: puppet 3.x colours may alter (all the errors will be printed in red)!

What does ^M character mean in Vim?

It probably means you've got carriage returns (different operating systems use different ways of signaling the end of line).

Use dos2unix to fix the files or set the fileformats in vim:

set ffs=unix,dos

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:id="@+id/rootLayout">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE" android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
    </LinearLayout>

</RelativeLayout>

Your activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            ImageView img = (ImageView) findViewById( R.id.img1 );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img2 );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img3 );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img4 );
            moveViewToScreenCenter( img );
        }
    });
}

private void moveViewToScreenCenter( View view )
{
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setDuration(1000);
    anim.setFillAfter( true );
    view.startAnimation(anim);
}

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

how do I loop through a line from a csv file in powershell

A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name

        # doSomething $column.Name $columnvalue 
        # doSomething $i $columnvalue 
    }
} 

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

How often should Oracle database statistics be run?

Make sure to balance the risk that fresh statistics cause undesirable changes to query plans against the risk that stale statistics can themselves cause query plans to change.

Imagine you have a bug database with a table ISSUE and a column CREATE_DATE where the values in the column increase more or less monotonically. Now, assume that there is a histogram on this column that tells Oracle that the values for this column are uniformly distributed between January 1, 2008 and September 17, 2008. This makes it possible for the optimizer to reasonably estimate the number of rows that would be returned if you were looking for all issues created last week (i.e. September 7 - 13). If the application continues to be used and the statistics are never updated, though, this histogram will be less and less accurate. So the optimizer will expect queries for "issues created last week" to be less and less accurate over time and may eventually cause Oracle to change the query plan negatively.

How to create a batch file to run cmd as administrator

You can use a shortcut that links to the batch file. Just go into properties for the shortcut and select advanced, then "run as administrator".

Then just make the batch file hidden, and run the shortcut.

This way, you can even set your own icon for the shortcut.

How do I select an element in jQuery by using a variable for the ID?

I don't know much about jQuery, but try this:

row_id = "#5";
row = $("body").find(row_id);

Edit: Of course, if the variable is a number, you have to add "#" to the front:

row_id = 5
row = $("body").find("#"+row_id);

Run an Ansible task only when the variable contains a specific string

This example uses regex_search to perform a substring search.

- name: make conditional variable
  command: "file -s /dev/xvdf"
  register: fsm_out

- name: makefs
  command: touch "/tmp/condition_satisfied"
  when: fsm_out.stdout | regex_search(' data')

ansible version: 2.4.3.0

Renew Provisioning Profile

For renew team provisioning profile managed by Xcode :

In the organizer of Xcode :

  • Right click on your device (in the left list)
  • Click on "Add device to provisioning portal"
  • Wait until it's done !

VSCode: How to Split Editor Vertically

Simply in windows

ctrl + @ (the button 2 in the upper horizontal row of numbers in keyboard)

String.strip() in Python

In this case, you might get some differences. Consider a line like:

"foo\tbar "

In this case, if you strip, then you'll get {"foo":"bar"} as the dictionary entry. If you don't strip, you'll get {"foo":"bar "} (note the extra space at the end)

Note that if you use line.split() instead of line.split('\t'), you'll split on every whitespace character and the "striping" will be done during splitting automatically. In other words:

line.strip().split()

is always identical to:

line.split()

but:

line.strip().split(delimiter)

Is not necessarily equivalent to:

line.split(delimiter)

How to load a text file into a Hive table stored as sequence files

You cannot directly create a table stored as a sequence file and insert text into it. You must do this:

  1. Create a table stored as text
  2. Insert the text file into the text table
  3. Do a CTAS to create the table stored as a sequence file.
  4. Drop the text table if desired

Example:

CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';

LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;

CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;

DROP TABLE test_txt;

IIS 7, HttpHandler and HTTP Error 500.21

This situation happens because you haven't installed/start service of ASP.net.

Use below command in windows 7,8,10.

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

Ways to save enums in database

We never store enumerations as numerical ordinal values anymore; it makes debugging and support way too difficult. We store the actual enumeration value converted to string:

public enum Suit { Spade, Heart, Diamond, Club }

Suit theSuit = Suit.Heart;

szQuery = "INSERT INTO Customers (Name, Suit) " +
          "VALUES ('Ian Boyd', %s)".format(theSuit.name());

and then read back with:

Suit theSuit = Suit.valueOf(reader["Suit"]);

The problem was in the past staring at Enterprise Manager and trying to decipher:

Name                Suit
==================  ==========
Shelby Jackson      2
Ian Boyd            1

verses

Name                Suit
==================  ==========
Shelby Jackson      Diamond
Ian Boyd            Heart

the latter is much easier. The former required getting at the source code and finding the numerical values that were assigned to the enumeration members.

Yes it takes more space, but the enumeration member names are short, and hard drives are cheap, and it is much more worth it to help when you're having a problem.

Additionally, if you use numerical values, you are tied to them. You cannot nicely insert or rearrange the members without having to force the old numerical values. For example, changing the Suit enumeration to:

public enum Suit { Unknown, Heart, Club, Diamond, Spade }

would have to become :

public enum Suit { 
      Unknown = 4,
      Heart = 1,
      Club = 3,
      Diamond = 2,
      Spade = 0 }

in order to maintain the legacy numerical values stored in the database.

How to sort them in the database

The question comes up: lets say i wanted to order the values. Some people may want to sort them by the enum's ordinal value. Of course, ordering the cards by the numerical value of the enumeration is meaningless:

SELECT Suit FROM Cards
ORDER BY SuitID; --where SuitID is integer value(4,1,3,2,0)

Suit
------
Spade
Heart
Diamond
Club
Unknown

That's not the order we want - we want them in enumeration order:

SELECT Suit FROM Cards
ORDER BY CASE SuitID OF
    WHEN 4 THEN 0 --Unknown first
    WHEN 1 THEN 1 --Heart
    WHEN 3 THEN 2 --Club
    WHEN 2 THEN 3 --Diamond
    WHEN 0 THEN 4 --Spade
    ELSE 999 END

The same work that is required if you save integer values is required if you save strings:

SELECT Suit FROM Cards
ORDER BY Suit; --where Suit is an enum name

Suit
-------
Club
Diamond
Heart
Spade
Unknown

But that's not the order we want - we want them in enumeration order:

SELECT Suit FROM Cards
ORDER BY CASE Suit OF
    WHEN 'Unknown' THEN 0
    WHEN 'Heart'   THEN 1
    WHEN 'Club'    THEN 2
    WHEN 'Diamond' THEN 3
    WHEN 'Space'   THEN 4
    ELSE 999 END

My opinion is that this kind of ranking belongs in the user interface. If you are sorting items based on their enumeration value: you're doing something wrong.

But if you wanted to really do that, i would create a Suits dimension table:

| Suit       | SuitID       | Rank          | Color  |
|------------|--------------|---------------|--------|
| Unknown    | 4            | 0             | NULL   |
| Heart      | 1            | 1             | Red    |
| Club       | 3            | 2             | Black  |
| Diamond    | 2            | 3             | Red    |
| Spade      | 0            | 4             | Black  |

This way, when you want to change your cards to use Kissing Kings New Deck Order you can change it for display purposes without throwing away all your data:

| Suit       | SuitID       | Rank          | Color  | CardOrder |
|------------|--------------|---------------|--------|-----------|
| Unknown    | 4            | 0             | NULL   | NULL      |
| Spade      | 0            | 1             | Black  | 1         |
| Diamond    | 2            | 2             | Red    | 1         |
| Club       | 3            | 3             | Black  | -1        |
| Heart      | 1            | 4             | Red    | -1        |

Now we are separating an internal programming detail (enumeration name, enumeration value) with a display setting meant for users:

SELECT Cards.Suit 
FROM Cards
   INNER JOIN Suits ON Cards.Suit = Suits.Suit
ORDER BY Suits.Rank, 
   Card.Rank*Suits.CardOrder

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

python pandas: apply a function with arguments to a series

You can pass any number of arguments to the function that apply is calling through either unnamed arguments, passed as a tuple to the args parameter, or through other keyword arguments internally captured as a dictionary by the kwds parameter.

For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.

s = pd.Series(np.random.randint(0,10, 10))
s

0    5
1    3
2    1
3    1
4    6
5    0
6    3
7    4
8    9
9    6
dtype: int64

s.apply(lambda x: x >= 3 and x <= 6)

0     True
1     True
2    False
3    False
4     True
5    False
6     True
7     True
8    False
9     True
dtype: bool

This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.

def between(x, low, high):
    return x >= low and x =< high

We can replicate the output of the first function by passing unnamed arguments to args:

s.apply(between, args=(3,6))

Or we can use the named arguments

s.apply(between, low=3, high=6)

Or even a combination of both

s.apply(between, args=(3,), high=6)

java.lang.OutOfMemoryError: Java heap space

  1. Upto my knowledge, Heap space is occupied by instance variables only. If this is correct, then why this error occurred after running fine for sometime as space for instance variables are alloted at the time of object creation.

That means you are creating more objects in your application over a period of time continuously. New objects will be stored in heap memory and that's the reason for growth in heap memory.

Heap not only contains instance variables. It will store all non-primitive data types ( Objects). These objects life time may be short (method block) or long (till the object is referenced in your application)

  1. Is there any way to increase the heap space?

Yes. Have a look at this oracle article for more details.

There are two parameters for setting the heap size:

-Xms:, which sets the initial and minimum heap size

-Xmx:, which sets the maximum heap size

  1. What changes should I made to my program so that It will grab less heap space?

It depends on your application.

  1. Set the maximum heap memory as per your application requirement

  2. Don't cause memory leaks in your application

  3. If you find memory leaks in your application, find the root cause with help of profiling tools like MAT, Visual VM , jconsole etc. Once you find the root cause, fix the leaks.

Important notes from oracle article

Cause: The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak.

Possible reasons:

  1. Improper configuration ( not allocating sufficiant memory)
  2. Application is unintentionally holding references to objects and this prevents the objects from being garbage collected
  3. Applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time. If the finalizer thread cannot keep up, with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.

On a different note, use better Garbage collection algorithms ( CMS or G1GC)

Have a look at this question for understanding G1GC

Rails params explained?

As others have pointed out, params values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.

As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params. For example, if you have a route like this:

match 'products/:id', ...

Then a request to a URL like http://example.com/products/42 will set params[:id] to 42.

Python string class like StringBuilder in C#?

There is no one-to-one correlation. For a really good article please see Efficient String Concatenation in Python:

Building long strings in the Python progamming language can sometimes result in very slow running code. In this article I investigate the computational performance of various string concatenation methods.

Could not reserve enough space for object heap

32-bit Java requires contiguous free space in memory to run. If you specify a large heap size, there may not be so much contiguous free space in memory even if you have much more free space available than necessary.

Installing a 64-bit version of Java helps in these cases, the contiguous memory requirements only applies to 32-bit Java.

How can I configure my makefile for debug and release builds?

Note that you can also make your Makefile simpler, at the same time:

DEBUG ?= 1
ifeq (DEBUG, 1)
    CFLAGS =-g3 -gdwarf2 -DDEBUG
else
    CFLAGS=-DNDEBUG
endif

CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)

EXECUTABLE = output
OBJECTS = CommandParser.tab.o CommandParser.yy.o Command.o
LIBRARIES = -lfl

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CXX) -o $@ $^ $(LIBRARIES)

%.yy.o: %.l 
    flex -o $*.yy.c $<
    $(CC) -c $*.yy.c

%.tab.o: %.y
    bison -d $<
    $(CXX) -c $*.tab.c

%.o: %.cpp
    $(CXX) -c $<

clean:
    rm -f $(EXECUTABLE) $(OBJECTS) *.yy.c *.tab.c

Now you don't have to repeat filenames all over the place. Any .l files will get passed through flex and gcc, any .y files will get passed through bison and g++, and any .cpp files through just g++.

Just list the .o files you expect to end up with, and Make will do the work of figuring out which rules can satisfy the needs...

for the record:

  • $@ The name of the target file (the one before the colon)

  • $< The name of the first (or only) prerequisite file (the first one after the colon)

  • $^ The names of all the prerequisite files (space separated)

  • $* The stem (the bit which matches the % wildcard in the rule definition.

Exact difference between CharSequence and String in java

I know it a kind of obvious, but CharSequence is an interface whereas String is a concrete class :)

java.lang.String is an implementation of this interface...

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

Android: checkbox listener

try this

satView.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (isChecked){
                // perform logic
            }
        }

    });

Determining the current foreground application from a background task or service

With regards to "2. How my background application can know what the application currently running in the foreground is."

Do NOT use the getRunningAppProcesses() method as this returns all sorts of system rubbish from my experience and you'll get multiple results which have RunningAppProcessInfo.IMPORTANCE_FOREGROUND. Use getRunningTasks() instead

This is the code I use in my service to identify the current foreground application, its really easy:

ActivityManager am = (ActivityManager) AppService.this.getSystemService(ACTIVITY_SERVICE);
// The first in the list of RunningTasks is always the foreground task.
RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

Thats it, then you can easily access details of the foreground app/activity:

String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
PackageManager pm = AppService.this.getPackageManager();
PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

This requires an additional permission in activity menifest and works perfectly.

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

CardView Corner Radius

You need to do 2 things :

1) Call setPreventCornerOverlap(false) on your CardView.

2) Put rounded Imageview inside CardView

About rounding your imageview, I had the same problem so I made a library that you can set different radii on each corner. Finally I got the result what I wanted like below.

https://github.com/pungrue26/SelectableRoundedImageView

Rounded ImageView inside CardView

What is the difference between #import and #include in Objective-C?

There seems to be a lot of confusion regarding the preprocessor.

What the compiler does when it sees a #include that it replaces that line with the contents of the included files, no questions asked.

So if you have a file a.h with this contents:

typedef int my_number;

and a file b.c with this content:

#include "a.h"
#include "a.h"

the file b.c will be translated by the preprocessor before compilation to

typedef int my_number;
typedef int my_number;

which will result in a compiler error, since the type my_number is defined twice. Even though the definition is the same this is not allowed by the C language.

Since a header often is used in more than one place include guards usually are used in C. This looks like this:

 #ifndef _a_h_included_
 #define _a_h_included_

 typedef int my_number;

 #endif

The file b.c still would have the whole contents of the header in it twice after being preprocessed. But the second instance would be ignored since the macro _a_h_included_ would already have been defined.

This works really well, but has two drawbacks. First of all the include guards have to be written, and the macro name has to be different in every header. And secondly the compiler has still to look for the header file and read it as often as it is included.

Objective-C has the #import preprocessor instruction (it also can be used for C and C++ code with some compilers and options). This does almost the same as #include, but it also notes internally which file has already been included. The #import line is only replaced by the contents of the named file for the first time it is encountered. Every time after that it is just ignored.

How to create a new figure in MATLAB?

Another common option is when you do want multiple plots in a single window

f = figure;
hold on
plot(x1,y1)
plot(x2,y2)
...

plots multiple data sets on the same (new) figure.

How to get a list of installed Jenkins plugins with name and version pair

# list of plugins in sorted order
# Copy this into your Jenkins script console
    def plugins = jenkins.model.Jenkins.instance.getPluginManager().getPlugins()

    List<String> list = new ArrayList<String>()

    i = 0
    plugins.each {
      ++i
      //println " ${i}  ${it.getShortName()}: ${it.getVersion()}"
      list.add("${it.getShortName()}: ${it.getVersion()}")
    }

    list.sort{it}
    i = 0
    for (String item : list) {
      i++
      println(" ${i} ${item}")
    }

Find a file in python

If you are using Python on Ubuntu and you only want it to work on Ubuntu a substantially faster way is the use the terminal's locate program like this.

import subprocess

def find_files(file_name):
    command = ['locate', file_name]

    output = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]
    output = output.decode()

    search_results = output.split('\n')

    return search_results

search_results is a list of the absolute file paths. This is 10,000's of times faster than the methods above and for one search I've done it was ~72,000 times faster.

round() for float in C++

Based on Kalaxy's response, the following is a templated solution that rounds any floating point number to the nearest integer type based on natural rounding. It also throws an error in debug mode if the value is out of range of the integer type, thereby serving roughly as a viable library function.

    // round a floating point number to the nearest integer
    template <typename Arg>
    int Round(Arg arg)
    {
#ifndef NDEBUG
        // check that the argument can be rounded given the return type:
        if (
            (Arg)std::numeric_limits<int>::max() < arg + (Arg) 0.5) ||
            (Arg)std::numeric_limits<int>::lowest() > arg - (Arg) 0.5)
            )
        {
            throw std::overflow_error("out of bounds");
        }
#endif

        return (arg > (Arg) 0.0) ? (int)(r + (Arg) 0.5) : (int)(r - (Arg) 0.5);
    }

npm install -g less does not work: EACCES: permission denied

For my mac environment

sudo chown -R $USER /usr/local/lib/node_modules

solve the issue

Stacking DIVs on top of each other?

To add to Dave's answer:

div { position: relative; }
div div { position: absolute; top: 0; left: 0; }

Execute the setInterval function without delay the first time

I will suggest calling the functions in the following sequence

var _timer = setInterval(foo, delay, params);
foo(params)

You can also pass the _timer to the foo, if you want to clearInterval(_timer) on a certain condition

var _timer = setInterval(function() { foo(_timer, params) }, delay);
foo(_timer, params);

Smooth scroll without the use of jQuery

Native browser smooth scrolling in JavaScript is like this:

// scroll to specific values,
// same as window.scroll() method.
// for scrolling a particular distance, use window.scrollBy().
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth' 
});

// scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // negative value acceptable
  left: 0, 
  behavior: 'smooth' 
});

// scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

Integration Testing POSTing an entire object to Spring MVC controller

Here is the method I made to transform recursively the fields of an object in a map ready to be used with a MockHttpServletRequestBuilder

public static void objectToPostParams(final String key, final Object value, final Map<String, String> map) throws IllegalAccessException {
    if ((value instanceof Number) || (value instanceof Enum) || (value instanceof String)) {
        map.put(key, value.toString());
    } else if (value instanceof Date) {
        map.put(key, new SimpleDateFormat("yyyy-MM-dd HH:mm").format((Date) value));
    } else if (value instanceof GenericDTO) {
        final Map<String, Object> fieldsMap = ReflectionUtils.getFieldsMap((GenericDTO) value);
        for (final Entry<String, Object> entry : fieldsMap.entrySet()) {
            final StringBuilder sb = new StringBuilder();
            if (!GenericValidator.isEmpty(key)) {
                sb.append(key).append('.');
            }
            sb.append(entry.getKey());
            objectToPostParams(sb.toString(), entry.getValue(), map);
        }
    } else if (value instanceof List) {
        for (int i = 0; i < ((List) value).size(); i++) {
            objectToPostParams(key + '[' + i + ']', ((List) value).get(i), map);
        }
    }
}

GenericDTO is a simple class extending Serializable

public interface GenericDTO extends Serializable {}

and here is the ReflectionUtils class

public final class ReflectionUtils {
    public static List<Field> getAllFields(final List<Field> fields, final Class<?> type) {
        if (type.getSuperclass() != null) {
            getAllFields(fields, type.getSuperclass());
        }
        // if a field is overwritten in the child class, the one in the parent is removed
        fields.addAll(Arrays.asList(type.getDeclaredFields()).stream().map(field -> {
            final Iterator<Field> iterator = fields.iterator();
            while(iterator.hasNext()){
                final Field fieldTmp = iterator.next();
                if (fieldTmp.getName().equals(field.getName())) {
                    iterator.remove();
                    break;
                }
            }
            return field;
        }).collect(Collectors.toList()));
        return fields;
    }

    public static Map<String, Object> getFieldsMap(final GenericDTO genericDTO) throws IllegalAccessException {
        final Map<String, Object> map = new HashMap<>();
        final List<Field> fields = new ArrayList<>();
        getAllFields(fields, genericDTO.getClass());
        for (final Field field : fields) {
            final boolean isFieldAccessible = field.isAccessible();
            field.setAccessible(true);
            map.put(field.getName(), field.get(genericDTO));
            field.setAccessible(isFieldAccessible);
        }
        return map;
    }
}

You can use it like

final MockHttpServletRequestBuilder post = post("/");
final Map<String, String> map = new TreeMap<>();
objectToPostParams("", genericDTO, map);
for (final Entry<String, String> entry : map.entrySet()) {
    post.param(entry.getKey(), entry.getValue());
}

I didn't tested it extensively, but it seems to work.

How to simulate a click by using x,y coordinates in JavaScript?

You can dispatch a click event, though this is not the same as a real click. For instance, it can't be used to trick a cross-domain iframe document into thinking it was clicked.

All modern browsers support document.elementFromPoint and HTMLElement.prototype.click(), since at least IE 6, Firefox 5, any version of Chrome and probably any version of Safari you're likely to care about. It will even follow links and submit forms:

document.elementFromPoint(x, y).click();

https://developer.mozilla.org/En/DOM:document.elementFromPoint https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

SQL Server - NOT IN

One issue could be that if either make, model, or [serial number] were null, values would never get returned. Because string concatenations with null values always result in null, and not in () with null will always return nothing. The remedy for this is to use an operator such as IsNull(make, '') + IsNull(Model, ''), etc.

How to convert integers to characters in C?

void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);
     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

What is the 'open' keyword in Swift?

open is a new access level in Swift 3, introduced with the implementation of

It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6.

In short:

  • An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
  • A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

So open is what public used to be in previous Swift releases and the access of public has been restricted. Or, as Chris Lattner puts it in SE-0177: Allow distinguishing between public access and public overridability:

“open” is now simply “more public than public”, providing a very simple and clean model.

In your example, open var hashValue is a property which is accessible and can be overridden in NSObject subclasses.

For more examples and details, have a look at SE-0117.

jQuery: how to trigger anchor link's click event

Try the following:

$("#myanchor")[0].click()

As simple as that.

How to get WordPress post featured image URL

// Try it inside loop.  
<?php
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
echo $feat_image;
?>

Hide Text with CSS, Best Practice?

you can simply make it transparent

{
   width: 20px;
   height: 20px;
   overflow: hidden; 
   color:transparent;
}

TypeScript hashmap/dictionary interface

Just as a normal js object:

let myhash: IHash = {};   

myhash["somestring"] = "value"; //set

let value = myhash["somestring"]; //get

There are two things you're doing with [indexer: string] : string

  • tell TypeScript that the object can have any string-based key
  • that for all key entries the value MUST be a string type.

enter image description here

You can make a general dictionary with explicitly typed fields by using [key: string]: any;

enter image description here

e.g. age must be number, while name must be a string - both are required. Any implicit field can be any type of value.

As an alternative, there is a Map class:

let map = new Map<object, string>(); 

let key = new Object();

map.set(key, "value");
map.get(key); // return "value"

This allows you have any Object instance (not just number/string) as the key.

Although its relatively new so you may have to polyfill it if you target old systems.

Copy Image from Remote Server Over HTTP

PHP has a built-in function file_get_contents(), which reads the content of a file into a string.

<?php
//Get the file
$content = file_get_contents("http://example.com/image.jpg");

//Store in the filesystem. $fp = fopen("/location/to/save/image.jpg", "w"); fwrite($fp, $content); fclose($fp); ?>

If you wish to store the file in a database, simply use the $content variable and don't save the file to disk.

Byte array to image conversion

public Image byteArrayToImage(byte[] bytesArr)
{
    using (MemoryStream memstr = new MemoryStream(bytesArr))
    {
        Image img = Image.FromStream(memstr);
        return img;
    }
}

How is AngularJS different from jQuery

I want to add something regarding AngularJS difference with jQuery from a developer's perspective.

In AngularJS you have to have a very structured view and approach on what you want to accomplish. It is scarcely following a linear fashion to complete a task, but rather, the exchanges between various objects take care of the requests and actions, which, then, is necessary as angular is an MVC-Based framework. It also requires an at least general blueprint of the finalized application, since coding depends much on how you want the interactions to be completed.

jQuery is like a free poetry, you write lines and keep some relations and momentum appropriate for your task to be accomplished.

Though, in Angular JS, you should follow some rules as well as keeping the momentum and relations proper, maybe it is more like classical Spencerian sonnet (a famous classical poet) whose poem is structural and tied to many rules.

Compared against AngularJS, jQuery is more like a collection of codes and functions (which is, as already mentioned, great for DOM manipulation and fast-effect achievement), while AngularJS is a real framework which gives the developer the ability to build an enterprise web-application with a lot of data-binding and exchange within a superbly organized-routing and management.

Furthermore, AngularJS has no dependency on jQuery to complete its task. It has two very superb features which are not found in jQuery in any sense:

1- Angular JS teaches you how to CODE and accomplish a goal, not just accomplish a goal by any means. Worth to mention that AngularJS fully utilizes the core and heart of Javascripts and paves the way for you to incorporate in your app, the techniques such as DI (dependency-injection). To work with angularJS you should (or must) learn more elevated techniques of coding with Javascript.

2- Angular JS is fully independent to handle directives and structure your app; you might then simply claim that jQuery can do the same (independence), but, indeed, AngularJS, as several times mentioned within the above lines, has independence in the most excellent possible structurally MVC-Based way.

A last note is that, there is no war of Names, since it is far disturbing to be biased, or subjective. jQuery's magnitude and greatness has been proved, but their usages and limitations( of any framework or software) are the concerns of the discussion and similar debates around.

Update:

Using AngularJS is decisive as it is expensive in terms of implementation, but founds a strong base for future expansion, transformation and maintenance of the application. AngularJS is for the New World of Web. It is targeted toward building applications which are characterized by their least resource consumption (loading only necessary resources from the server), fast response time and high degree of maintainability and extendability wrapped around a structured system.

"cannot resolve symbol R" in Android Studio

Have you updated your SDK tools recently? Launch the android SDK manager and make sure you have the latest SDK tools, which is now separate from the platform tools. I had this same issue when I first updated my SDK manager, the SDK build tools package did not show up for install/update until I closed and reopened the SDK manager.

Apache Spark: The number of cores vs. the number of executors

Spark Dynamic allocation gives flexibility and allocates resources dynamically. In this number of min and max executors can be given. Also the number of executors that has to be launched at the starting of the application can also be given.

Read below on the same:

http://spark.apache.org/docs/latest/configuration.html#dynamic-allocation

Is there a way to perform "if" in python's lambda

Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.

a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))

Get all attributes of an element using jQuery

The attributes property contains them all:

$(this).each(function() {
  $.each(this.attributes, function() {
    // this.attributes is not a plain object, but an array
    // of attribute nodes, which contain both the name and value
    if(this.specified) {
      console.log(this.name, this.value);
    }
  });
});

What you can also do is extending .attr so that you can call it like .attr() to get a plain object of all attributes:

(function(old) {
  $.fn.attr = function() {
    if(arguments.length === 0) {
      if(this.length === 0) {
        return null;
      }

      var obj = {};
      $.each(this[0].attributes, function() {
        if(this.specified) {
          obj[this.name] = this.value;
        }
      });
      return obj;
    }

    return old.apply(this, arguments);
  };
})($.fn.attr);

Usage:

var $div = $("<div data-a='1' id='b'>");
$div.attr();  // { "data-a": "1", "id": "b" }

How to check whether particular port is open or closed on UNIX?

netstat -ano|grep 443|grep LISTEN

will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).

How to create string with multiple spaces in JavaScript

You can use the <pre> tag with innerHTML. The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre as a selector in your CSS file and style it as desired.

Ex:

var a = '<pre>something        something</pre>';
document.body.innerHTML = a;

Deploying my application at the root in Tomcat

In my server I am using this and root autodeploy works just fine:

   <Host name="mysite" autoDeploy="true" appBase="webapps" unpackWARs="true" deployOnStartup="true">
        <Alias>www.mysite.com</Alias>
        <Valve className="org.apache.catalina.valves.RemoteIpValve" protocolHeader="X-Forwarded-Proto"/>
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="mysite_access_log." suffix=".txt"
           pattern="%h %l %u %t &quot;%r&quot; %s %b"/>
        <Context path="/mysite" docBase="mysite" reloadable="true"/>
    </Host>

How can I extract all values from a dictionary in Python?

Call the values() method on the dict.

What is an idiomatic way of representing enums in Go?

I am sure we have a lot of good answers here. But, I just thought of adding the way I have used enumerated types

package main

import "fmt"

type Enum interface {
    name() string
    ordinal() int
    values() *[]string
}

type GenderType uint

const (
    MALE = iota
    FEMALE
)

var genderTypeStrings = []string{
    "MALE",
    "FEMALE",
}

func (gt GenderType) name() string {
    return genderTypeStrings[gt]
}

func (gt GenderType) ordinal() int {
    return int(gt)
}

func (gt GenderType) values() *[]string {
    return &genderTypeStrings
}

func main() {
    var ds GenderType = MALE
    fmt.Printf("The Gender is %s\n", ds.name())
}

This is by far one of the idiomatic ways we could create Enumerated types and use in Go.

Edit:

Adding another way of using constants to enumerate

package main

import (
    "fmt"
)

const (
    // UNSPECIFIED logs nothing
    UNSPECIFIED Level = iota // 0 :
    // TRACE logs everything
    TRACE // 1
    // INFO logs Info, Warnings and Errors
    INFO // 2
    // WARNING logs Warning and Errors
    WARNING // 3
    // ERROR just logs Errors
    ERROR // 4
)

// Level holds the log level.
type Level int

func SetLogLevel(level Level) {
    switch level {
    case TRACE:
        fmt.Println("trace")
        return

    case INFO:
        fmt.Println("info")
        return

    case WARNING:
        fmt.Println("warning")
        return
    case ERROR:
        fmt.Println("error")
        return

    default:
        fmt.Println("default")
        return

    }
}

func main() {

    SetLogLevel(INFO)

}

Capitalize first letter. MySQL

CREATE A FUNCTION:

CREATE DEFINER=`root`@`localhost` FUNCTION `UC_FIRST`(`oldWord` VARCHAR(255)) 

RETURNS varchar(255) CHARSET utf8

RETURN CONCAT( UCASE( LEFT(oldWord, 1)), LCASE(SUBSTRING(oldWord, 2)))

USE THE FUNCTION

UPDATE tbl_name SET col_name = UC_FIRST(col_name);

Simulating a click in jQuery/JavaScript on a link

Just

$("#your_item").trigger("click");

using .trigger() you can simulate many type of events, just passing it as the parameter.

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

Search for all occurrences of a string in a mysql database

Using the MySQL Workbench, you can search for a string from the "Database" -> "Search Table Data" menu option.

Specify LIKE %URL_TO_SEARCH% and on the left side select all the tables you want to search through. You can use "Cntrl + A" to select the whole tree on the left, and then deselect the objects you don't care about.

enter image description here

Spring JUnit: How to Mock autowired component in autowired component

Another approach in integration testing is to define a new Configuration class and provide it as your @ContextConfiguration. Into the configuration you will be able to mock your beans and also you must define all types of beans which you are using in test/s flow. To provide an example :

@RunWith(SpringRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class MockTest{
 @Configuration
 static class ContextConfiguration{
 // ... you beans here used in test flow
 @Bean
    public MockMvc mockMvc() {
        return MockMvcBuilders.standaloneSetup(/*you can declare your controller beans defines on top*/)
                .addFilters(/*optionally filters*/).build();
    }
 //Defined a mocked bean
 @Bean
    public MyService myMockedService() {
        return Mockito.mock(MyService.class);
    }
 }

 @Autowired
 private MockMvc mockMvc;

 @Autowired
 MyService myMockedService;

 @Before
 public void setup(){
  //mock your methods from MyService bean 
  when(myMockedService.myMethod(/*params*/)).thenReturn(/*my answer*/);
 }

 @Test
 public void test(){
  //test your controller which trigger the method from MyService
  MvcResult result = mockMvc.perform(get(CONTROLLER_URL)).andReturn();
  // do your asserts to verify
 }
}

How to wrap text using CSS?

This will work everywhere.

<body>
  <table style="table-layout:fixed;">
  <tr>
    <td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>
  </tr>
  </table>
 </body>

File count from a folder

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries

int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

For Swift 4.2 / Alamofire 4.7.3

Alamofire.upload(multipartFormData: { multipart in
    multipart.append(fileData, withName: "payload", fileName: "someFile.jpg", mimeType: "image/jpeg")
    multipart.append("comment".data(using: .utf8)!, withName :"comment")
}, to: "endPointURL", method: .post, headers: nil) { encodingResult in
    switch encodingResult {
    case .success(let upload, _, _):
        upload.response { answer in
            print("statusCode: \(answer.response?.statusCode)")
        }
        upload.uploadProgress { progress in
            //call progress callback here if you need it
        }
    case .failure(let encodingError):
        print("multipart upload encodingError: \(encodingError)")
    }
}

Also you could take a look at CodyFire lib it makes API calls easier using Codable for everything. Example for Multipart call using CodyFire

//Declare your multipart payload model
struct MyPayload: MultipartPayload {
    var attachment: Attachment //or you could use just Data instead
    var comment: String
}

// Prepare payload for request
let imageAttachment = Attachment(data: UIImage(named: "cat")!.jpeg(.high)!,
                                 fileName: "cat.jpg",
                                 mimeType: .jpg)
let payload = MyPayload(attachment: imageAttachment, comment: "Some text")

//Send request easily
APIRequest("endpoint", payload: payload)
    .method(.post)
    .desiredStatus(.created) //201 CREATED
    .onError { error in
        switch error.code {
        case .notFound: print("Not found")
        default: print("Another error: " + error.description)
        }
    }.onSuccess { result in
        print("here is your decoded result")
    }
//Btw normally it should be wrapped into an extension
//so it should look even easier API.some.upload(payload).onError{}.onSuccess{}

You could take a look at all the examples in lib's readme

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can use the os/signal package to handle incoming signals. Ctrl+C is SIGINT, so you can use this to trap os.Interrupt.

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func(){
    for sig := range c {
        // sig is a ^C, handle it
    }
}()

The manner in which you cause your program to terminate and print information is entirely up to you.

Bash ignoring error for a particular command

More concisely:

! particular_script

From the POSIX specification regarding set -e (emphasis mine):

When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.

how to pass value from one php page to another using session

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}

How to resolve Unneccessary Stubbing exception

As others pointed out it is usually the simplest to remove the line that is unnecessarily stubbing a method call.

In my case it was in a @BeforeEach and it was relevant most of the time. In the only test where that method was not used I reset the mock, e.g.:

myMock.reset()

Hope this helps others with the same problem.

(Note that if there are multiple mocked calls on the same mock this could be inconvenient as well since you'll have to mock all the other methods except the one that isn't called.)

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

Since unpaidMembers is a dictionary it always returns two values when called with .items() - (key, value). You may want to keep your data as a list of tuples [(name, email, lastname), (name, email, lastname)..].

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

Window.open as modal popup?

I agree with both previous answers. Basically, you want to use what is known as a "lightbox" - http://en.wikipedia.org/wiki/Lightbox_(JavaScript)

It is essentially a div than is created within the DOM of your current window/tab. In addition to the div that contains your dialog, a transparent overlay blocks the user from engaging all underlying elements. This can effectively create a modal dialog (i.e. user MUST make some kind of decision before moving on).

Should __init__() call the parent class's __init__()?

In Anon's answer:
"If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"

It's incredible: he is wording exactly the contrary of the principle of inheritance.


It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__

So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??

It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.
In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.
NOT the contrary.


Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ . That's exactly what is said in the official doc:

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance

That's all the story:

  • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class

  • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class

  • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__


What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

Simple solution for standard observablecollection that I've used:

DO NOT ADD to your property OR CHANGE it's inner items DIRECTLY, instead, create some temp collection like this

ObservableCollection<EntityViewModel> tmpList= new ObservableCollection<EntityViewModel>();

and add items or make changes to tmpList,

tmpList.Add(new EntityViewModel(){IsRowChecked=false}); //Example
tmpList[0].IsRowChecked= true; //Example
...

then pass it to your actual property by assignment.

ContentList=tmpList;

this will change whole property which causes notice the INotifyPropertyChanged as you need.

Ruby Hash to array of values

hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]] 

Enumerable#collect takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.

The Enumerable module is pretty awesome. Knowing it well can save you lots of time and lots of code.

Available text color classes in Bootstrap

The text at the navigation bar is normally colored by using one of the two following css classes in the bootstrap.css file.

Firstly, in case of using a default navigation bar (the gray one), the .navbar-default class will be used and the text is colored as dark gray.

.navbar-default .navbar-text {
  color: #777;
}

The other is in case of using an inverse navigation bar (the black one), the text is colored as gray60.

.navbar-inverse .navbar-text {
  color: #999;
}

So, you can change its color as you wish. However, I would recommend you to use a separate css file to change it.

NOTE: you could also use the customizer provided by Twitter Bootstrap, in the Navbar section.

R not finding package even after package installation

Do .libPaths(), close every R runing, check in the first directory, remove the zoo package restart R and install zoo again. Of course you need to have sufficient rights.

Print PHP Call Stack

please take a look at this utils class, may be helpful:

Usage:

<?php
/* first caller */
 Who::callme();

/* list the entire list of calls */
Who::followme();

Source class: https://github.com/augustowebd/utils/blob/master/Who.php

How to find files modified in last x minutes (find -mmin does not work as expected)

The problem is that

find . -mmin -60

outputs:

.
./file1
./file2

Note the line with one dot?
That makes ls list the whole directory exactly the same as when ls -l . is executed.

One solution is to list only files (not directories):

find . -mmin -60 -type f | xargs ls -l

But it is better to use directly the option -exec of find:

find . -mmin -60 -type f -exec ls -l {} \;

Or just:

find . -mmin -60 -type f -ls

Which, by the way is safe even including directories:

find . -mmin -60 -ls

"Repository does not have a release file" error

I opened up my Software & Updates program and switched from my country to the main servers like so:
Software & Updates screen

After I done this and run the sudo apt update commando again, my problems where gone.

Node Multer unexpected field

In my case, I had 2 forms in differents views and differents router files. The first router used the name field with view one and its file name was "inputGroupFile02". The second view had another name for file input. For some reason Multer not allows you set differents name in different views, so I dicided to use same name for the file input in both views.

enter image description here

Failed to run sdkmanager --list with Java 9

Short addition to the above for openJDK 11 with android sdk tools before upgrading to the latest version.

The above solutions didn't work for me

set DEFAULT_JVM_OPTS="-Dcom.android.sdklib.toolsdir=%~dp0\.."

To get this working I have installed the jaxb-ri (reference implementation) from the maven repo.

The information was given https://github.com/javaee/jaxb-v2 and links to the https://repo1.maven.org/maven2/com/sun/xml/bind/jaxb-ri/2.3.2/jaxb-ri-2.3.2.zip
This download includes a standalone runtime implementation in the mod-Folder.

I copied the mod-Folder to $android_sdk\tools\lib\ and added the following to classpath variable:

;%APP_HOME%\lib\mod\jakarta.xml.bind-api.jar;%APP_HOME%\lib\mod\jakarta.activation-api.jar;%APP_HOME%\lib\mod\jaxb-runtime.jar;%APP_HOME%\lib\mod\istack-commons-runtime.jar;

So finally it looks like:

set CLASSPATH=%APP_HOME%\lib\dvlib-26.0.0-dev.jar;%APP_HOME%\lib\jimfs-1.1.jar;%APP_HOME%\lib\jsr305-1.3.9.jar;%APP_HOME%\lib\repository-26.0.0-dev.jar;%APP_HOME%\lib\j2objc-annotations-1.1.jar;%APP_HOME%\lib\layoutlib-api-26.0.0-dev.jar;%APP_HOME%\lib\gson-2.3.jar;%APP_HOME%\lib\httpcore-4.2.5.jar;%APP_HOME%\lib\commons-logging-1.1.1.jar;%APP_HOME%\lib\commons-compress-1.12.jar;%APP_HOME%\lib\annotations-26.0.0-dev.jar;%APP_HOME%\lib\error_prone_annotations-2.0.18.jar;%APP_HOME%\lib\animal-sniffer-annotations-1.14.jar;%APP_HOME%\lib\httpclient-4.2.6.jar;%APP_HOME%\lib\commons-codec-1.6.jar;%APP_HOME%\lib\common-26.0.0-dev.jar;%APP_HOME%\lib\kxml2-2.3.0.jar;%APP_HOME%\lib\httpmime-4.1.jar;%APP_HOME%\lib\annotations-12.0.jar;%APP_HOME%\lib\sdklib-26.0.0-dev.jar;%APP_HOME%\lib\guava-22.0.jar;%APP_HOME%\lib\mod\jakarta.xml.bind-api.jar;%APP_HOME%\lib\mod\jakarta.activation-api.jar;%APP_HOME%\lib\mod\jaxb-runtime.jar;%APP_HOME%\lib\mod\istack-commons-runtime.jar;

Maybe I missed a lib due to some minor errors showing up. But sdkmanager.bat --update or --list is running now.

Play audio from a stream using C#

NAudio wraps the WaveOutXXXX API. I haven't looked at the source, but if NAudio exposes the waveOutWrite() function in a way that doesn't automatically stop playback on each call, then you should be able to do what you really want, which is to start playing the audio stream before you've received all the data.

Using the waveOutWrite() function allows you to "read ahead" and dump smaller chunks of audio into the output queue - Windows will automatically play the chunks seamlessly. Your code would have to take the compressed audio stream and convert it to small chunks of WAV audio on the fly; this part would be really difficult - all the libraries and components I've ever seen do MP3-to-WAV conversion an entire file at a time. Probably your only realistic chance is to do this using WMA instead of MP3, because you can write simple C# wrappers around the multimedia SDK.

How do I remove the top margin in a web page?

A lot of elements in CSS have default padding and margins set on them. So, when you start building a new site, it's always good to have a reset.css file ready. Add this to make to rub the default values, so you have more control over your web page.

/* CSS reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { 
    margin:0;
    padding:0;
}
html,body {
    margin:0;
    padding:0;
}


/* Extra options you might want to consider*/

table {
    border-collapse:collapse;
    border-spacing:0;
}
fieldset,img { 
    border:0;
}
input{
    border:1px solid #b0b0b0;
    padding:3px 5px 4px;
    color:#979797;
    width:190px;
}
address,caption,cite,code,dfn,th,var {
    font-style:normal;
    font-weight:normal;
}
ol,ul {
    list-style:none;
}
caption,th {
    text-align:left;
}
h1,h2,h3,h4,h5,h6 {
    font-size:100%;
    font-weight:normal;
}
q:before,q:after {
    content:'';
}
abbr,acronym { 
    border:0;
}

I hope this helps all fellow developers this is something that bugged for me a while when I was learning.

What is the symbol for whitespace in C?

The character representation of a Space is simply ' '.

void foo (const char *s)
{
    unsigned char c;
    ...
    if (c == ' ')
        ...
}

But if you are really looking for all whitespace, then C has a function (actually it's often a macro) for that:

#include <ctype.h>
...

void foo (const char *s)
{
    char c;
    ...
    if (isspace(c))
        ...
}

You can read about isspace here

If you really want to catch all non-printing characters, the function to use is isprint from the same library. This deals with all of the characters below 0x20 (the ASCII code for a space) and above 0x7E (0x7f is the code for DEL, and everything above that is an extension).

In raw code this is equivalent to:

if (c < ' ' || c >= 0x7f)
    // Deal with non-printing characters.

How to list the tables in a SQLite database file that was opened with ATTACH?

.da to see all databases - one called 'main'

tables of this database can be seen by

SELECT distinct tbl_name from sqlite_master order by 1;

The attached databases need prefixes you chose with AS in the statement ATTACH e.g. aa (, bb, cc...) so:

SELECT distinct tbl_name from aa.sqlite_master order by 1;

Note that here you get the views as well. To exclude these add where type = 'table' before ' order'

What is the default lifetime of a session?

The default in the php.ini for the session.gc_maxlifetime directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual:

http://www.php.net/manual/en/session.configuration.php

You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site:

php_value session.gc_maxlifetime "3600"

Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they should be kept). See the note on the manual page or this site for a better explanation.

The answer to this is to move your sessions to another directory using session.save_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory.

How can I change all input values to uppercase using Jquery?

Use css text-transform to display text in all input type text. In Jquery you can then transform the value to uppercase on blur event.

Css:

input[type=text] {
    text-transform: uppercase;
}

Jquery:

$(document).on('blur', "input[type=text]", function () {
    $(this).val(function (_, val) {
        return val.toUpperCase();
    });
});

How to enable explicit_defaults_for_timestamp?

On a Windows platform,

  1. Find your my.ini configuration file.
  2. In my.ini go to the [mysqld] section.
  3. Add explicit_defaults_for_timestamp=true without quotes and save the change.
  4. Start mysqld

This worked for me (windows 7 Ultimate 32bit)

How to check the version before installing a package using apt-get?

As posted somewhere else, this works, too:

apt-cache madison <package_name>

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Note: static synchronized methods and blocks work on the Class object.

public class MyClass {
   // locks MyClass.class
   public static synchronized void foo() {
// do something
   }

   // similar
   public static void foo() {
      synchronized(MyClass.class) {
// do something
      }
   }
}

How do you set the Content-Type header for an HttpClient request?

Some extra information about .NET Core (after reading erdomke's post about setting a private field to supply the content-type on a request that doesn't have content)...

After debugging my code, I can't see the private field to set via reflection - so I thought I'd try to recreate the problem.

I have tried the following code using .Net 4.6:

HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, @"myUrl");
httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpClient client = new HttpClient();
Task<HttpResponseMessage> response =  client.SendAsync(httpRequest);  //I know I should have used async/await here!
var result = response.Result;

And, as expected, I get an aggregate exception with the content "Cannot send a content-body with this verb-type."

However, if i do the same thing with .NET Core (1.1) - I don't get an exception. My request was quite happily answered by my server application, and the content-type was picked up.

I was pleasantly surprised about that, and I hope it helps someone!

Sum the digits of a number

You can try this

def sumDigits(number):
    sum = 0
    while(number>0):
        lastdigit = number%10
        sum += lastdigit
        number = number//10

    return sum

Convert MFC CString to integer

The problem with the accepted answer is that it cannot signal failure. There's strtol (STRing TO Long) which can. It's part of a larger family: wcstol (Wide Character String TO Long, e.g. Unicode), strtoull (TO Unsigned Long Long, 64bits+), wcstoull, strtof (TO Float) and wcstof.

Docker can't connect to docker daemon

If you get the message Can't connect to docker daemon. Is 'docker -d' running on this host?, you can check it by docker version.

If you see the information like Docker Client is running. but Docker Server is not, it's obviously you need to start the Docker server.

In CentOS, you can use service to start or stop the Docker server.

$ sudo service docker stop
$ sudo service docker start

Then, after you type docker version, you will get the information of Docker Client and Docker Server, and the Docker daemon has been started.

What are the differences between Deferred, Promise and Future in JavaScript?

In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.

If you're interested in the minutiae, then examine Promises/A+.


So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from @jfriend00:

Rather than directly passing callbacks to functions, something which can lead to tightly coupled interfaces, using promises allows one to separate concerns for code that is synchronous or asynchronous.

Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.

Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):

/* assume getScript has signature like: function (path, callback, context) 
   and listens to onload && onreadystatechange */
$(function () {
   getScript('path/to/CodeMirror', getJSMode);

   // onreadystate is not reliable for callback args.
   function getJSMode() {
       getScript('path/to/CodeMirror/mode/javascript/javascript.js', 
           ourAwesomeScript);
   };

   function ourAwesomeScript() {
       console.log("CodeMirror is awesome, but I'm too impatient.");
   };
});

To the promises formulated version (again, apologies, I'm not up to date on jQuery):

/* Assume getScript returns a promise object */
$(function () {
   $.when(
       getScript('path/to/CodeMirror'),
       getScript('path/to/CodeMirror/mode/javascript/javascript.js')
   ).then(function () {
       console.log("CodeMirror is awesome, but I'm too impatient.");
   });
});

Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.

Find where python is installed (if it isn't default dir)

Platform independent solution in one line is

Python 2:

python -c "import sys; print sys.executable"

Python 3:

python -c "import sys; print(sys.executable)"

How to auto import the necessary classes in Android Studio with shortcut?

To import classes on the fly :

On OSX press Alt(Option) + Enter.

CREATE DATABASE permission denied in database 'master' (EF code-first)

Step 1: Disconnect from your local account.

Step 2: Again Connect to Server with your admin user

Step 3: Object Explorer -> Security -> Logins -> Right click on your server name -> Properties -> Server Roles -> sysadmin -> OK

Step 4: Disconnect and connect to your local login and create database.

Why do package names often begin with "com"

Wikipedia, of all places, actually discusses this.

The idea is to make sure all package names are unique world-wide, by having authors use a variant of a DNS name they own to name the package. For example, the owners of the domain name joda.org created a number of packages whose names begin with org.joda, for example:

  • org.joda.time
  • org.joda.time.base
  • org.joda.time.chrono
  • org.joda.time.convert
  • org.joda.time.field
  • org.joda.time.format

Why do we need middleware for async flow in Redux?

When working in an enterprise project, there are many requirements available in middle-ware such as (saga) not available in simple asynchronous flow, below are some:

  • Running request in parallel
  • Pulling future actions without the need to wait
  • Non-blocking calls Race effect, example pickup first
  • response to initiate the process Sequencing your tasks (first in first call)
  • Composing
  • Task cancellation Dynamically forking the task.
  • Support Concurrency Running Saga outside the redux middleware.
  • Using channels

The list is long just review the advanced section in saga documentation

How to call a button click event from another method

For WPF:

YourButtonName.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));

How does the communication between a browser and a web server take place?

It depends on the web server, but if you're wondering what it looks like from the client side, just install Live Headers and Firebug for firefox. With the net tab in firebug and live headers open, it should be clear exactly how the two interact.

For a more in-depth look at the actual data going back and forth, use wireshark.

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

Selenium Webdriver: Entering text into text field

Agree with Subir Kumar Sao and Faiz.

element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);

Checking if a variable is an integer

There's var.is_a? Class (in your case: var.is_a? Integer); that might fit the bill. Or there's Integer(var), where it'll throw an exception if it can't parse it.

Android-java- How to sort a list of objects by a certain value within the object

I think this will help you better

Person p = new Person("Bruce", "Willis");
Person p1  = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas", "Cage");
Person p3 = new Person("John", "Travolta");

ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);

Collections.sort(list, new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
        return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
    }
});

Running .sh scripts in Git Bash

If by any chance you've changed the default open for .sh files to a text editor like I had, you can just "bash .\yourscript.sh", provided you have git bash installed and in path.

Perfect 100% width of parent container for a Bootstrap input?

Just add box-sizing:

input[type="text"] {
    box-sizing: border-box;
}

Align nav-items to right side in bootstrap-4

TL;DR:

Create another <ul class="navbar-nav ml-auto"> for the navbar items you want on the right.
ml-auto will pull your navbar-nav to the right where mr-auto will pull it to the left.

Tested against Bootstrap v4.5.2

_x000D_
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"/>
  <style>
    /* Stackoverflow preview fix, please ignore */
    .navbar-nav {
      flex-direction: row;
    }
    
    .nav-link {
      padding-right: .5rem !important;
      padding-left: .5rem !important;
    }
    
    /* Fixes dropdown menus placed on the right side */
    .ml-auto .dropdown-menu {
      left: auto !important;
      right: 0px;
    }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary rounded">
  <a class="navbar-brand" href="#">Navbar</a>
  <ul class="navbar-nav mr-auto">
    <li class="nav-item active">
      <a class="nav-link">Left Link 1</a>
    </li>
    <li class="nav-item">
      <a class="nav-link">Left Link 2</a>
    </li>
  </ul>
  <ul class="navbar-nav ml-auto">
    <li class="nav-item">
      <a class="nav-link">Right Link 1</a>
    </li>
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">            Dropdown on Right</a>
      <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action with a lot of text inside of an item</a>
      </div>
    </li>
  </ul>
</nav>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

As you can see additional styling rules have been added to account for some oddities in Stackoverflows preview box.
You should be able to safely ignore those rules in your project.

As of v4.0.0 this seems to be the official way to do it.

EDIT: I modified the Post to include a dropdown placed on the right side of the navbar as suggested by @Bruno. It needs its left and right attributes to be inverted. I added an extra snippet of css to the beginning of the example code.
Please note, that the example shows the mobile version when you click the Run code snippet button. To view the desktop version you must click the Expand snippet button.

.ml-auto .dropdown-menu {
    left: auto !important;
    right: 0px;
}

Including this in your stylesheet should do the trick.

Move textfield when keyboard appears swift

    func registerForKeyboardNotifications(){
        //Keyboard
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWasShown), name: UIKeyboardDidShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIKeyboardDidHideNotification, object: nil)


    }
    func deregisterFromKeyboardNotifications(){

        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)

    }
    func keyboardWasShown(notification: NSNotification){

        let userInfo: NSDictionary = notification.userInfo!
        let keyboardInfoFrame = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue()

        let windowFrame:CGRect = (UIApplication.sharedApplication().keyWindow!.convertRect(self.view.frame, fromView:self.view))

        let keyboardFrame = CGRectIntersection(windowFrame, keyboardInfoFrame!)

        let coveredFrame = UIApplication.sharedApplication().keyWindow!.convertRect(keyboardFrame, toView:self.view)

        let contentInsets = UIEdgeInsetsMake(0, 0, (coveredFrame.size.height), 0.0)
        self.scrollViewInAddCase .contentInset = contentInsets;
        self.scrollViewInAddCase.scrollIndicatorInsets = contentInsets;
        self.scrollViewInAddCase.contentSize = CGSizeMake((self.scrollViewInAddCase.contentSize.width), (self.scrollViewInAddCase.contentSize.height))

    }
    /**
     this method will fire when keyboard was hidden

     - parameter notification: contains keyboard details
     */
    func keyboardWillBeHidden (notification: NSNotification) {

        self.scrollViewInAddCase.contentInset = UIEdgeInsetsZero
        self.scrollViewInAddCase.scrollIndicatorInsets = UIEdgeInsetsZero

    }

RecyclerView inside ScrollView is not working

I used CustomLayoutManager to disable RecyclerView Scrolling. Also don't use Recycler View as WrapContent, use it as 0dp, Weight=1

public class CustomLayoutManager extends LinearLayoutManager {
    private boolean isScrollEnabled;

    // orientation should be LinearLayoutManager.VERTICAL or HORIZONTAL
    public CustomLayoutManager(Context context, int orientation, boolean isScrollEnabled) {
        super(context, orientation, false);
        this.isScrollEnabled = isScrollEnabled;
    }

    @Override
    public boolean canScrollVertically() {
        //Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
        return isScrollEnabled && super.canScrollVertically();
    }
}

Use CustomLayoutManager in RecyclerView:

CustomLayoutManager mLayoutManager = new CustomLayoutManager(getBaseActivity(), CustomLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(mLayoutManager);
        ((DefaultItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false); 
        recyclerView.setAdapter(statsAdapter);

UI XML:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background_main"
    android:fillViewport="false">


    <LinearLayout
        android:id="@+id/contParentLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <edu.aku.family_hifazat.libraries.mpchart.charts.PieChart
                android:id="@+id/chart1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/x20dp"
                android:minHeight="@dimen/x300dp">

            </edu.aku.family_hifazat.libraries.mpchart.charts.PieChart>


        </FrameLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">


        </android.support.v7.widget.RecyclerView>


    </LinearLayout>


</ScrollView>

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

How to shift a block of code left/right by one space in VSCode?

Current Version 1.38.1

I had a problem with intending. The default Command+] is set to 4 and I wanted it to be 2. Installed "Indent 4-to-2" but it changed the entire file and not the selected text.

I changed the tab spacing in settings and it was simple.

Go to Settings -> Text Editor -> Tab Size

Using DISTINCT and COUNT together in a MySQL Query

What the hell of all this work anthers

it's too simple

if you want a list of how much productId in each keyword here it's the code

SELECT count(productId),  keyword  FROM `Table_name` GROUP BY keyword; 

Convert StreamReader to byte[]

You can also use CopyTo:

var ms = new MemoryStream();
yourStreamReader.BaseStream.CopyTo(ms); // blocking call till the end of the stream
ms.GetBuffer().CopyTo(yourArray, ms.Length);

or

var ms = new MemoryStream();
var ct = yourStreamReader.BaseStream.CopyToAsync(ms);
await ct;
ms.GetBuffer().CopyTo(yourArray, ms.Length);

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013