Programs & Examples On #Auto generate

The automation of the creation of classes, files, documentation, or anything else for which manual creation is costly.

Auto generate function documentation in Visual Studio

Make that "three single comment-markers"

In C# it's ///

which as default spits out:

/// <summary>
/// 
/// </summary>
/// <returns></returns>

Here's some tips on editing VS templates.

Unexpected token ILLEGAL in webkit

You can use online Minify, it removes these invisible characters efficiently but also changes your code. So be careful.

http://jscompress.com/

In a javascript array, how do I get the last 5 elements, excluding the first element?

ES6 way:

I use destructuring assignment for array to get first and remaining rest elements and then I'll take last five of the rest with slice method:

_x000D_
_x000D_
const cutOffFirstAndLastFive = (array) => {_x000D_
  const [first, ...rest] = array;_x000D_
  return rest.slice(-5);_x000D_
}_x000D_
_x000D_
cutOffFirstAndLastFive([1, 55, 77, 88]);_x000D_
_x000D_
console.log(_x000D_
  'Tests:',_x000D_
  JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),_x000D_
  JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),_x000D_
  JSON.stringify(cutOffFirstAndLastFive([1]))_x000D_
);
_x000D_
_x000D_
_x000D_

How to read file from res/raw by name

Here are two approaches you can read raw resources using Kotlin.

You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.

Cheers mate

// R.raw.data_post

this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)

How do I check if string contains substring?

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

Syntax :-string.includes(searchString[, position])

searchString:-A string to be searched for within this string.

position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.

string = 'LOL';
console.log(string.includes('lol')); // returns false 
console.log(string.includes('LOL')); // returns true 

react-router getting this.props.location in child components

If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';


Using this you can export your child class as -

class MyApp extends Component{
    // your code
}

export default withRouter(MyApp);

And your class with Router -

// your code
<Router>
      ...
      <Route path="/myapp" component={MyApp} />
      // or if you are sending additional fields
      <Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>

How do I get the name of a Ruby class?

Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...

If you use Rails (ActiveSupport):

result.class.name.demodulize

If you use POR (plain-ol-Ruby):

result.class.name.split('::').last

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Boolean.parseBoolean("1") = false...?

I have a small utility function to convert all possible values into Boolean.

private boolean convertToBoolean(String value) {
    boolean returnValue = false;
    if ("1".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || 
        "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value))
        returnValue = true;
    return returnValue;
}

What does (function($) {})(jQuery); mean?

Type 3, in order to work would have to look like this:

(function($){
    //Attach this new method to jQuery
    $.fn.extend({     
        //This is where you write your plugin's name
        'pluginname': function(_options) {
            // Put defaults inline, no need for another variable...
            var options =  $.extend({
                'defaults': "go here..."
            }, _options);

            //Iterate over the current set of matched elements
            return this.each(function() {

                //code to be inserted here

            });
        }
    }); 
})(jQuery);

I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

List of standard lengths for database fields

UK Government Data Standards Catalogue details the UK standards for this kind of thing. It suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name, and 255 characters for an email address. Amongst other things..

Depend on a branch or tag using a git URL in a package.json?

If you want to use devel or feature branch, or you haven’t published a certain package to the NPM registry, or you can’t because it’s a private module, then you can point to a git:// URI instead of a version number in your package.json:

"dependencies": {
   "public": "git://github.com/user/repo.git#ref",
   "private": "git+ssh://[email protected]:user/repo.git#ref"
}

The #ref portion is optional, and it can be a branch (like master), tag (like 0.0.1) or a partial or full commit id.

How can I search sub-folders using glob.glob module?

In Python 3.5 and newer use the new recursive **/ functionality:

configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)

When recursive is set, ** followed by a path separator matches 0 or more subdirectories.

In earlier Python versions, glob.glob() cannot list files in subdirectories recursively.

In that case I'd use os.walk() combined with fnmatch.filter() instead:

import os
import fnmatch

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in fnmatch.filter(files, '*.txt')]

This'll walk your directories recursively and return all absolute pathnames to matching .txt files. In this specific case the fnmatch.filter() may be overkill, you could also use a .endswith() test:

import os

path = 'C:/Users/sam/Desktop/file1'

configfiles = [os.path.join(dirpath, f)
    for dirpath, dirnames, files in os.walk(path)
    for f in files if f.endswith('.txt')]

Adding n hours to a date in Java?

You can use the LocalDateTime class from Java 8. For eg :

long n = 4;
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.plusHours(n));

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

Try going to the Publish tab in the project properties and then select the Application Files button. Then set the following properties:

  • File Name of stdole.dll
  • Publish status to Include
  • Download Group to Required

After that you need to republish your application.

If the reference has CopyLocal=true, then the reference will be published with the application. If the reference has CopyLocal=false then the reference will be marked as a prerequisite. This means the assembly must be installed in the client's GAC before the ClickOnce application will install.

There are some assemblies that are installed into the GAC because of the Visual Studio install, not the .NET Framework install. This could be your situation.

Why compile Python code?

The .pyc file is Python that has already been compiled to byte-code. Python automatically runs a .pyc file if it finds one with the same name as a .py file you invoke.

"An Introduction to Python" says this about compiled Python files:

A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.

The advantage of running a .pyc file is that Python doesn't have to incur the overhead of compiling it before running it. Since Python would compile to byte-code before running a .py file anyway, there shouldn't be any performance improvement aside from that.

How much improvement can you get from using compiled .pyc files? That depends on what the script does. For a very brief script that simply prints "Hello World," compiling could constitute a large percentage of the total startup-and-run time. But the cost of compiling a script relative to the total run time diminishes for longer-running scripts.

The script you name on the command-line is never saved to a .pyc file. Only modules loaded by that "main" script are saved in that way.

how to count the total number of lines in a text file using python

count=0
with open ('filename.txt','rb') as f:
    for line in f:
        count+=1

print count

How to create a custom-shaped bitmap marker with Android map API v2

The alternative and easier solution that i also use is to create custom marker layout and convert it into a bitmap.

view_custom_marker.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_marker_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/marker_mask">

    <ImageView
        android:id="@+id/profile_image"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="center_horizontal"
        android:contentDescription="@null"
        android:src="@drawable/avatar" />
</FrameLayout>

Convert this view into bitmap by using the code below

 private Bitmap getMarkerBitmapFromView(@DrawableRes int resId) {

        View customMarkerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_custom_marker, null);
        ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.profile_image);
        markerImageView.setImageResource(resId);
        customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
        customMarkerView.buildDrawingCache();
        Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
        Drawable drawable = customMarkerView.getBackground();
        if (drawable != null)
            drawable.draw(canvas);
        customMarkerView.draw(canvas);
        return returnedBitmap;
    }

Add your custom marker in on Map ready callback.

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d(TAG, "onMapReady() called with");
    mGoogleMap = googleMap;
    MapsInitializer.initialize(this);
    addCustomMarker();
}
private void addCustomMarker() {
    Log.d(TAG, "addCustomMarker()");
    if (mGoogleMap == null) {
        return;
    }

    // adding a marker on map with image from  drawable
   mGoogleMap.addMarker(new MarkerOptions()
            .position(mDummyLatLng)
            .icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(R.drawable.avatar))));
}

For more details please follow the link below

How to create custom marker using layout?

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

This solved my issue,

We need to import the cert onto the local java. If not we could get the below exception.

    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)

SSLPOKE is a tool where you can test the https connectivity from your local machine.

Command to test the connectivity:

"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
    sun.security.validator.ValidatorException: PKIX path building failed: 
    sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
        at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
        at sun.security.validator.Validator.validate(Validator.java:260)
        at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
        at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
        at SSLPoke.main(SSLPoke.java:31)
    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to 
    requested target
        at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
        at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
        at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
        ... 15 more
keytool -import -alias <anyname> -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file <cert path>

this would first prompt to "Enter keystore password:" changeit is the default password. and finally a prompt "Trust this certificate? [no]:", provide "yes" to add the cert to keystore.

Verfication:

C:\tools>"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
Successfully connected    

react-native - Fit Image in containing View, not the whole screen size

the image has a property named Style ( like most of the react-native Compponents) and for Image's Styles, there is a property named resizeMode that takes values like: contain,cover,stretch,center,repeat

most of the time if you use center it will work for you

How to open a Bootstrap modal window using jQuery?

Try this. It's works for me well.

_x000D_
_x000D_
function clicked(item) {
         alert($(item).attr("id"));
        }
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-rtl/3.4.0/css/bootstrap-rtl.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<button onclick="clicked(this);" id="modalME">Click me</button>

<!-- Modal -->
  <div class="modal" id="modalME" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-header">
        <h2>Modal in CSS</h2>
        <a href="#close" class="btn-close" aria-hidden="true">×</a> <!--CHANGED TO "#close"-->
      </div>
      <div class="modal-body">
        <p>One modal example here.</p>
      </div>
      <div class="modal-footer">
        <a href="#close" class="btn">Nice!</a>  <!--CHANGED TO "#close"-->
      </div>
      </div>
    </div>
  </div>
  <!-- /Modal -->
_x000D_
_x000D_
_x000D_

Launch Image does not show up in my iOS App

I set up "LaunchImage" in my asset catalog and simply cleared the "Launch Screen" field et voila ! I had the launch images appear ...

How do I upload a file with the JS fetch API?

Here is my code:

html:

_x000D_
_x000D_
const upload = (file) => {_x000D_
    console.log(file);_x000D_
_x000D_
    _x000D_
_x000D_
    fetch('http://localhost:8080/files/uploadFile', { _x000D_
    method: 'POST',_x000D_
    // headers: {_x000D_
    //   //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",_x000D_
    //   "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" //  ? // multipart/form-data _x000D_
    // },_x000D_
    body: file // This is your file object_x000D_
  }).then(_x000D_
    response => response.json() // if the response is a JSON object_x000D_
  ).then(_x000D_
    success => console.log(success) // Handle the success response object_x000D_
  ).catch(_x000D_
    error => console.log(error) // Handle the error response object_x000D_
  );_x000D_
_x000D_
  //cvForm.submit();_x000D_
};_x000D_
_x000D_
const onSelectFile = () => upload(uploadCvInput.files[0]);_x000D_
_x000D_
uploadCvInput.addEventListener('change', onSelectFile, false);
_x000D_
<form id="cv_form" style="display: none;"_x000D_
          enctype="multipart/form-data">_x000D_
          <input id="uploadCV" type="file" name="file"/>_x000D_
          <button type="submit" id="upload_btn">upload</button>_x000D_
</form>_x000D_
<ul class="dropdown-menu">_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

You can create user with no password in phpmyadmin and it solves the problem! Lebbar Abdelhadi,

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

how to modify an existing check constraint?

No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)

How do I multiply each element in a list by a number?

With map (not as good, but another approach to the problem):

list(map(lambda x: x*5,[5, 10, 15, 20, 25]))

also, if you happen to be using numpy or numpy arrays, you could use this:

import numpy as np
list(np.array(x) * 5)

How to call any method asynchronously in c#

Here's a way to do it:

// The method to call
void Foo()
{
}


Action action = Foo;
action.BeginInvoke(ar => action.EndInvoke(ar), null);

Of course you need to replace Action by another type of delegate if the method has a different signature

Run an exe from C# code

Example:

System.Diagnostics.Process.Start("mspaint.exe");

Compiling the Code

Copy the code and paste it into the Main method of a console application. Replace "mspaint.exe" with the path to the application you want to run.

fatal error: Python.h: No such file or directory

try apt-file. It is difficult to remember the package name where the missing file resides. It is generic and useful for any package files.

For example:

root@ubuntu234:~/auto# apt-file search --regexp '/Python.h$'
pypy-dev: /usr/lib/pypy/include/Python.h
python2.7-dbg: /usr/include/python2.7_d/Python.h
python2.7-dev: /usr/include/python2.7/Python.h
python3.2-dbg: /usr/include/python3.2dmu/Python.h
python3.2-dev: /usr/include/python3.2mu/Python.h
root@ubuntu234:~/auto# 

Now you can make an expert guess as to which one to choose from.

How to add additional fields to form before submit?

Yes.You can try with some hidden params.

  $("#form").submit( function(eventObj) {
      $("<input />").attr("type", "hidden")
          .attr("name", "something")
          .attr("value", "something")
          .appendTo("#form");
      return true;
  });

Java int to String - Integer.toString(i) vs new Integer(i).toString()

new Integer(i).toString() first creates a (redundant) wrapper object around i (which itself may be a wrapper object Integer).

Integer.toString(i) is preferred because it doesn't create any unnecessary objects.

Difference between Iterator and Listiterator?

the following is that the difference between iterator and listIterator

iterator :

boolean hasNext();
E next();
void remove();

listIterator:

boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

Alternative to sp_defaultdb (which will be removed in a future version of Microsoft SQL Server) could be ALTER LOGIN:

ALTER LOGIN [my_user_name] WITH DEFAULT_DATABASE = [new_default_database]

Note: unlike the sp_defaultdb solution user and database names are provided without quotes. Brackets are needed if name had special chars (most common example will be domain user which is domain\username and won't work without brackets).

How to pass a value from one Activity to another in Android?

You can use Bundle to do the same in Android

Create the intent:

Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();

//Create the bundle
Bundle bundle = new Bundle();

//Add your data to bundle
bundle.putString(“stuff”, getrec);

//Add the bundle to the intent
i.putExtras(bundle);

//Fire that second activity
startActivity(i);

Now in your second activity retrieve your data from the bundle:

//Get the bundle
Bundle bundle = getIntent().getExtras();

//Extract the data…
String stuff = bundle.getString(“stuff”); 

How to save picture to iPhone photo library?

Just pass the images from an array to it like so

-(void) saveMePlease {

//Loop through the array here
for (int i=0:i<[arrayOfPhotos count]:i++){
         NSString *file = [arrayOfPhotos objectAtIndex:i];
         NSString *path = [get the path of the image like you would in DOCS FOLDER or whatever];
         NSString *imagePath = [path stringByAppendingString:file];
         UIImage *image = [[[UIImage alloc] initWithContentsOfFile:imagePath]autorelease];

         //Now it will do this for each photo in the array
         UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
}

Sorry for typo's kinda just did this on the fly but you get the point

iPhone App Minus App Store?

If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist.

Repeating a function every few seconds

For this the System.Timers.Timer works best

// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it        
myTimer.Enabled = true;

// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }

See Timer Class (.NET 4.6 and 4.5) for details

Ternary operator in AngularJS templates

Update: Angular 1.1.5 added a ternary operator, this answer is correct only to versions preceding 1.1.5. For 1.1.5 and later, see the currently accepted answer.

Before Angular 1.1.5:

The form of a ternary in angularjs is:

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

An example would be:

<ul class="nav">
    <li>
        <a   href="#/page1" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Goals</a>
    </li>
    <li>
        <a   href="#/page2" style="{{$location.path()=='/page2' && 'color:#fff;' || 'color:#000;'}}">Groups</a>
    </li>
</ul>

or:

 <li  ng-disabled="currentPage == 0" ng-click="currentPage=0"  class="{{(currentPage == 0) && 'disabled' || ''}}"><a> << </a></li>

How can I truncate a double to only two decimal places in Java?

      double value = 3.4555;
      String value1 =  String.format("% .3f", value) ;
      String value2 = value1.substring(0, value1.length() - 1);
      System.out.println(value2);         
      double doublevalue= Double.valueOf(value2);
      System.out.println(doublevalue);

Eclipse comment/uncomment shortcut?

Source -> Remove Block Comment

link

enter image description here

video as site background? HTML 5

First, your HTML markup looks like this:

<video id="awesome_video" src="first_video.mp4" autoplay />

Second, your JavaScript code will look like this:

<script type="text/javascript">
  var index = 1,
      playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
      video = document.getElementById('awesome_video');

  video.addEventListener('ended', rotate_video, false);

  function rotate_video() {
    video.setAttribute('src', playlist[index]);
    video.load();
    index++;
    if (index >= playlist.length) { index = 0; }
  }
</script>

And last but not least, your CSS:

#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.

How to show all of columns name on pandas dataframe?

Not a conventional answer, but I guess you could transpose the dataframe to look at the rows instead of the columns. I use this because I find looking at rows more 'intuitional' than looking at columns:

data_all2.T

This should let you view all the rows. This action is not permanent, it just lets you view the transposed version of the dataframe.

If the rows are still truncated, just use print(data_all2.T) to view everything.

Unresolved external symbol on static class members

In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]

Sorted array list in Java

Have a look at SortedList

This class implements a sorted list. It is constructed with a comparator that can compare two objects and sort objects accordingly. When you add an object to the list, it is inserted in the correct place. Object that are equal according to the comparator, will be in the list in the order that they were added to this list. Add only objects that the comparator can compare.


When the list already contains objects that are equal according to the comparator, the new object will be inserted immediately after these other objects.

How to Correctly Use Lists in R?

Regarding vectors and the hash/array concept from other languages:

  1. Vectors are the atoms of R. Eg, rpois(1e4,5) (5 random numbers), numeric(55) (length-55 zero vector over doubles), and character(12) (12 empty strings), are all "basic".

  2. Either lists or vectors can have names.

    > n = numeric(10)
    > n
     [1] 0 0 0 0 0 0 0 0 0 0
    > names(n)
    NULL
    > names(n) = LETTERS[1:10]
    > n
    A B C D E F G H I J 
    0 0 0 0 0 0 0 0 0 0
    
  3. Vectors require everything to be the same data type. Watch this:

    > i = integer(5)
    > v = c(n,i)
    > v
    A B C D E F G H I J           
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
    > class(v)
    [1] "numeric"
    > i = complex(5)
    > v = c(n,i)
    > class(v)
    [1] "complex"
    > v
       A    B    C    D    E    F    G    H    I    J                          
    0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i
    
  4. Lists can contain varying data types, as seen in other answers and the OP's question itself.

I've seen languages (ruby, javascript) in which "arrays" may contain variable datatypes, but for example in C++ "arrays" must be all the same datatype. I believe this is a speed/efficiency thing: if you have a numeric(1e6) you know its size and the location of every element a priori; if the thing might contain "Flying Purple People Eaters" in some unknown slice, then you have to actually parse stuff to know basic facts about it.

Certain standard R operations also make more sense when the type is guaranteed. For example cumsum(1:9) makes sense whereas cumsum(list(1,2,3,4,5,'a',6,7,8,9)) does not, without the type being guaranteed to be double.


As to your second question:

Lists can be returned from functions even though you never passed in a List when you called the function

Functions return different data types than they're input all the time. plot returns a plot even though it doesn't take a plot as an input. Arg returns a numeric even though it accepted a complex. Etc.

(And as for strsplit: the source code is here.)

How to write a multidimensional array to a text file?

I am not certain if this meets your requirements, given I think you are interested in making the file readable by people, but if that's not a primary concern, just pickle it.

To save it:

import pickle

my_data = {'a': [1, 2.0, 3, 4+6j],
           'b': ('string', u'Unicode string'),
           'c': None}
output = open('data.pkl', 'wb')
pickle.dump(my_data, output)
output.close()

To read it back:

import pprint, pickle

pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

pkl_file.close()

How do I use Notepad++ (or other) with msysgit?

UPDATE 2015

If you unpack/install Notepad++ into c:\utils\npp\ and rename notepad++.exe to npp.exe for simplicity, then all you have to do is

git config --global core.editor c:/utils/npp/npp.exe

No wrapper scripts or other trickery. No need to have Notepad++ in PATH.

How to rotate the background image in the container?

Very easy method, you rotate one way, and the contents the other. Requires a square though

#element{
    background : url('someImage.jpg');
}
#element:hover{
    transform: rotate(-30deg);
}
#element:hover >*{
    transform: rotate(30deg);
}

How to convert a structure to a byte array in C#?

@Abdel Olakara answer donese not work in .net 3.5, should be modified as below:

    public static void ByteArrayToStructure<T>(byte[] bytearray, ref T obj)
    {
        int len = Marshal.SizeOf(obj);
        IntPtr i = Marshal.AllocHGlobal(len);
        Marshal.Copy(bytearray, 0, i, len);
        obj = (T)Marshal.PtrToStructure(i, typeof(T));
        Marshal.FreeHGlobal(i);
    }

Regex matching beginning AND end strings

\bdbo\..*fn

I was looking through a ton of java code for a specific library: car.csclh.server.isr.businesslogic.TypePlatform (although I only knew car and Platform at the time). Unfortunately, none of the other suggestions here worked for me, so I figured I'd post this.

Here's the regex I used to find it:

\bcar\..*Platform

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

MySQL SELECT statement for the "length" of the field is greater than 1

How about:

SELECT * FROM sometable WHERE CHAR_LENGTH(LINK) > 1

Here's the MySql string functions page (5.0).

Note that I chose CHAR_LENGTH instead of LENGTH, as if there are multibyte characters in the data you're probably really interested in how many characters there are, not how many bytes of storage they take. So for the above, a row where LINK is a single two-byte character wouldn't be returned - whereas it would when using LENGTH.

Note that if LINK is NULL, the result of CHAR_LENGTH(LINK) will be NULL as well, so the row won't match.

Not able to access adb in OS X through Terminal, "command not found"

If you are using the Mac with the M1 chip add the below export command to the zshrc file using the nano command, if that file is not present the nano command will create it for you so run

nano ~/.zshrc

paste this command in that file without any modification

export PATH="/Users/$USER/Library/Android/sdk/platform-tools":$PATH

hit ctrl-x and then Hit y to save the changes and the hit return Key to close it without renaming the file.

then run

source ~/.zshrc

to refresh the .zshrc file

and then try runnning

adb

it should give you the desired output

What does $1 mean in Perl?

As others have pointed out, the $x are capture variables for regular expressions, allowing you to reference sections of a matched pattern.

Perl also supports named captures which might be easier for humans to remember in some cases.

Given input: 111 222

/(\d+)\s+(\d+)/

$1 is 111

$2 is 222

One could also say:

/(?<myvara>\d+)\s+(?<myvarb>\d+)/

$+{myvara} is 111

$+{myvarb} is 222

Can you run GUI applications in a Docker container?

I'm late to the party, but for Mac users who don't want to go down the XQuartz path, here is a working example that builds a Fedora Image, with a Desktop Environment (xfce) using Xvfb and VNC. It's simple, and works:

On a Mac, you can just access it using the Screen Sharing (default) application, connecting to localhost:5901.

Dockerfile:

FROM fedora

USER root

# Set root password, so I know it for the future
RUN echo "root:password123" | chpasswd

# Install Java, Open SSL, etc.
RUN dnf update -y --setopt=deltarpm=false  \
 && dnf install -y --setopt=deltarpm=false \
                openssl.x86_64             \
                java-1.8.0-openjdk.x86_64  \
                xorg-x11-server-Xvfb       \
                x11vnc                     \
                firefox                    \
                @xfce-desktop-environment  \
 && dnf clean all

# Create developer user (password: password123, uid: 11111)
RUN useradd -u 11111 -g users -d /home/developer -s /bin/bash -p $(echo password123 | openssl passwd -1 -stdin) developer

# Copy startup script over to the developer home
COPY start-vnc.sh /home/developer/start-vnc.sh
RUN chmod 700 /home/developer/start-vnc.sh
RUN chown developer.users /home/developer/start-vnc.sh

# Expose VNC, SSH
EXPOSE 5901 22

# Set up VNC Password and DisplayEnvVar to point to Display1Screen0
USER developer
ENV  DISPLAY :1.0
RUN  mkdir ~/.x11vnc
RUN  x11vnc -storepasswd letmein ~/.x11vnc/passwd

WORKDIR /home/developer
CMD ["/home/developer/start-vnc.sh"]

start-vnc.sh

#!/bin/sh

Xvfb :1 -screen 0 1024x768x24 &
sleep 5
x11vnc -noxdamage -many -display :1 -rfbport 5901 -rfbauth ~/.x11vnc/passwd -bg
sleep 2
xfce4-session &

bash
# while true; do sleep 1000; done

Check the linked readme for build and run commands if you want/need.

How can I retrieve a table from stored procedure to a datatable?

Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:

var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);

(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)

No module named setuptools

For python3 is:

sudo apt-get install -y python3-setuptools

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

Error: TypeError: $(...).dialog is not a function

I just experienced this with the line:

$('<div id="editor" />').dialogelfinder({

I got the error "dialogelfinder is not a function" because another component was inserting a call to load an older version of JQuery (1.7.2) after the newer version was loaded.

As soon as I commented out the second load, the error went away.

Java: Multiple class declarations in one file

1.Is there a tidy name for this technique (analogous to inner, nested, anonymous)?

Multi-class single-file demo.

2.The JLS says the system may enforce the restriction that these secondary classes can't be referred to by code in other compilation units of the package, e.g., they can't be treated as package-private. Is that really something that changes between Java implementations?

I'm not aware of any which don't have that restriction - all the file based compilers won't allow you to refer to source code classes in files which are not named the same as the class name. ( if you compile a multi-class file, and put the classes on the class path, then any compiler will find them )

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

Clear listview content?

As of Android versions M and N, following works for me and would be the correct approach. Emptying the ListView or setting the Adapter to null is not the right approach and would lead to null pointer issue, invalid ListView and/or crash of the app.

Simply do:

    mList.clear();
    mAdapter.notifyDataSetChanged();

i.e. first you clear the list altogether, and then let the adapter know about this change. Android will take care of correctly updating the UI with an empty list. In my case, my list is an ArrayList.

In case you are doing this operation from a different thread, run this code on the UI thread:

    runOnUiThread(mRunnable);

Where mRunnable would be:

    Runnable mRunnable = new Runnable() {
        public void run() {
            mList.clear();
            mAdapter.notifyDataSetChanged();
        }
    };;

Unsupported method: BaseConfig.getApplicationIdSuffix()

You can do this by changing the gradle file.

 build.gradle > change
    dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    }
    gradle-wrapper.properties > update
    distributionUrl=https://services.gradle.org/distributions/gradle-4.6-all.zip

How to access the php.ini file in godaddy shared hosting linux

Create a new php.ini file with your desired settings and upload it to public_html folder of your Godaddy Hosting Account.

By default, Godaddy doesn't allow to edit it's existing php.ini file. However, you can always upload your own copy of your php.ini file with your own settings.

Below is an example of a simple php.ini file with some custom values:

max_execution_time 600
memory_limit 128M
post_max_size 32M
upload_max_filesize 32M

Gson and deserializing an array of objects with arrays in it

Use your bean class like this, if your JSON data starts with an an array object. it helps you.

Users[] bean = gson.fromJson(response,Users[].class);

Users is my bean class.

Response is my JSON data.

How to check if a value exists in a dictionary (python)

In Python 3 you can use the values() function of the dictionary. It returns a view object of the values. This, in turn, can be passed to the iter function which returns an iterator object. The iterator can be checked using in, like this,

'one' in iter(d.values())

Or you can use the view object directly since it is similar to a list

'one' in d.values()

Netbeans - class does not have a main method

I had this issue as well (Error: Could not find or load main class test.Test). I'll explain this relatively basically since I know I would have appreciated someone doing that when I was looking for my answer.

When I right-clicked on the project (left hand side of the screen unless you got rid of the projects tab) and went to properties and then run, the main class had the projectname.classname, which is what confused me. For example, I created a project "test" to test this out, and when I went to

(right-click) test or Source Packages -> properties -> run -> main class

had Test.test in that field, which is what the problem was. the class is test, not Test.test, so I clicked browse to its right, and the only thing in the list to select from was test, and when I selected that and tried rerunning it, it finally worked.

Additionally, I found that when you create a new project in Netbeans, one of the things it originally gives you (in my case of the project named test) is package test;. If you are having this problem, then like me, you probably originally got rid of that line seeing it as just another line of code you didn't need. That line of code is what enabled your main class which in my case was Test.test to find the main class *test from that.

NumPy array initialization (fill with identical values)

NumPy 1.8 introduced np.full(), which is a more direct method than empty() followed by fill() for creating an array filled with a certain value:

>>> np.full((3, 5), 7)
array([[ 7.,  7.,  7.,  7.,  7.],
       [ 7.,  7.,  7.,  7.,  7.],
       [ 7.,  7.,  7.,  7.,  7.]])

>>> np.full((3, 5), 7, dtype=int)
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])

This is arguably the way of creating an array filled with certain values, because it explicitly describes what is being achieved (and it can in principle be very efficient since it performs a very specific task).

How to get the start time of a long-running Linux process?

You can specify a formatter and use lstart, like this command:

ps -eo pid,lstart,cmd

The above command will output all processes, with formatters to get PID, command run, and date+time started.

Example (from Debian/Jessie command line)

$ ps -eo pid,lstart,cmd
  PID CMD                                          STARTED
    1 Tue Jun  7 01:29:38 2016 /sbin/init                  
    2 Tue Jun  7 01:29:38 2016 [kthreadd]                  
    3 Tue Jun  7 01:29:38 2016 [ksoftirqd/0]               
    5 Tue Jun  7 01:29:38 2016 [kworker/0:0H]              
    7 Tue Jun  7 01:29:38 2016 [rcu_sched]                 
    8 Tue Jun  7 01:29:38 2016 [rcu_bh]                    
    9 Tue Jun  7 01:29:38 2016 [migration/0]               
   10 Tue Jun  7 01:29:38 2016 [kdevtmpfs]                 
   11 Tue Jun  7 01:29:38 2016 [netns]                     
  277 Tue Jun  7 01:29:38 2016 [writeback]                 
  279 Tue Jun  7 01:29:38 2016 [crypto]                    
      ...

You can read ps's manpage or check Opengroup's page for the other formatters.

Using margin / padding to space <span> from the rest of the <p>

Overall just add display:block; to your span. You can leave your html unchanged.

Demo

You can do it with the following css:

p {
    font-size:24px; 
    font-weight: 300; 
    -webkit-font-smoothing: subpixel-antialiased; 
    margin-top:0px;
}

p span {
    font-size:16px; 
    font-style: italic; 
    margin-top:20px; 
    padding-left:10px; 
    display:inline-block;
}

Where are logs located?

In Laravel 6, by default the logs are in:

storage/logs/laravel.log

How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer

If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:

var myname varchar2(20);

exec :myname := 'Tom';

SELECT *
FROM   Customers
WHERE  Name = :myname;

In many tools (such as Toad and SQL Developer), omitting the var and exec statements will cause the program to prompt you for the value.


Original Answer

A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT (roughly equivalent to print) to output the variable:

DECLARE
   myname varchar2(20);
BEGIN
     myname := 'Tom';

     dbms_output.print_line(myname);
END;

This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:

CREATE FUNCTION my_function (myname in varchar2)
     my_refcursor out sys_refcursor
BEGIN
     open my_refcursor for
     SELECT *
     FROM   Customers
     WHERE  Name = myname;

     return my_refcursor;
END my_function;

How do I get the current location of an iframe?

I did some tests in Firefox 3 comparing the value of .src and .documentWindow.location.href in an iframe. (Note: The documentWindow is called contentDocument in Chrome, so instead of .documentWindow.location.href in Chrome it will be .contentDocument.location.href.)

src is always the last URL that was loaded in the iframe without user interaction. I.e., it contains the first value for the URL, or the last value you set up with Javascript from the containing window doing:

document.getElementById("myiframe").src = 'http://www.google.com/';

If the user navigates inside the iframe, you can't anymore access the value of the URL using src. In the previous example, if the user goes away from www.google.com and you do:

alert(document.getElementById("myiframe").src);

You will still get "http://www.google.com".

documentWindow.location.href is only available if the iframe contains a page in the same domain as the containing window, but if it's available it always contains the right value for the URL, even if the user navigates in the iframe.

If you try to access documentWindow.location.href (or anything under documentWindow) and the iframe is in a page that doesn't belong to the domain of the containing window, it will raise an exception:

document.getElementById("myiframe").src = 'http://www.google.com/';
alert(document.getElementById("myiframe").documentWindow.location.href);
Error: Permission denied to get property Location.href

I have not tested any other browser.

Hope it helps!

C pass int array pointer as parameter into a function

If you actually want to pass an array pointer, it's

#include <stdio.h>

void func(int (*B)[10]){   // ptr to array of 10 ints.
        (*B)[0] = 5;   // note, *B[0] means *(B[0])
         //B[0][0] = 5;  // same, but could be misleading here; see below.
}

int main(void){

        int B[10] = {0};   // not NULL, which is for pointers.
        printf("b[0] = %d\n\n", B[0]);
        func(&B);            // &B is ptr to arry of 10 ints.
        printf("b[0] = %d\n\n", B[0]);

        return 0;
}

But as mentioned in other answers, it's not that common to do this. Usually a pointer-to-array is passed only when you want to pass a 2d array, where it suddenly looks a lot clearer, as below. A 2D array is actually passed as a pointer to its first row.

void func( int B[5][10] )  // this func is actually the same as the one above! 
{
         B[0][0] = 5;
}

int main(void){
    int Ar2D[5][10];
    func(Ar2D);   // same as func( &Ar2D[0] )
}

The parameter of func may be declared as int B[5][10], int B[][10], int (*B)[10], all are equivalent as parameter types.

Addendum: you can return a pointer-to-array from a function, but the syntax to declare the function is very awkward, the [10] part of the type has to go after the parameter list:

int MyArr[5][10];
int MyRow[10];

int (*select_myarr_row( int i ))[10] { // yes, really
   return (i>=0 && i<5)? &MyArr[i] : &MyRow;
}

This is usually done as below, to avoid eyestrain:

typedef int (*pa10int)[10];

pa10int select_myarr_row( int i ) {
   return (i>=0 && i<5)? &MyArr[i] : &MyRow;
}

Intel X86 emulator accelerator (HAXM installer) VT/NX not enabled

From the Intel Instructions

"The SDK Manager will download the installer to the "extras" directory, under the main SDK directory. Even though the SDK manager says "Installed" it actually means that the Intel HAXM executable was downloaded. You will still need to run the installer from the "extras" directory to finish installation.

Extract the installer inside the "extras" directory and follow the installation instructions for your platform."

How to uncheck checkbox using jQuery Uniform library

A simpler solution is to do this rather than using uniform:

$('#check1').prop('checked', true); // will check the checkbox with id check1
$('#check1').prop('checked', false); // will uncheck the checkbox with id check1

This will not trigger any click action defined.

You can also use:

$('#check1').click(); // 

This will toggle the check/uncheck for the checkbox but this will also trigger any click action you have defined. So be careful.

EDIT: jQuery 1.6+ uses prop() not attr() for checkboxes checked value

How do I get the list of keys in a Dictionary?

List<string> keyList = new List<string>(this.yourDictionary.Keys);

How to convert ZonedDateTime to Date?

If you are interested in now only, then simply use:

Date d = new Date();

Connect to mysql on Amazon EC2 from a remote server

I know this is an old post but...

I'm experiencing this issue and I've established that my problem is in fact not the EC2 instance. It seems like it might be a bug in the MySQL client driver software. I haven't done thorough research yet but I went as far as to install MySQL Workbench on the EC2 instance and IT also is erratic - it intermittently fails to connect (error is "connection cancelled"). This link suggests a possible bug lower down the stack, not EC2.

Of course, I have not done exhaustive research and my post might actually be off the mark, but worth noting and/or exploring anyway, IMHO.

Executing multiple commands from a Windows cmd script

When you call another .bat file, I think you need "call" in front of the call:

call otherCommand.bat

Responsive design with media query : screen size?

The screen widths Bootstrap v3.x uses are as follows:

  • Extra small devices Phones (<768px) / .col-xs-
  • Small devices Tablets (=768px) / .col-sm-
  • Medium devices Desktops (=992px) / .col-md-
  • Large devices Desktops (=1200px) / .col-lg-

So, these are good to use and work well in practice.

How do I change the default port (9000) that Play uses when I execute the "run" command?

Play 2.0-RC4

It is important to include quotes around the play command you want to run. In my case without the quotes play would still run on port 9000.

play "run 8080"

Alternatively you could run the following from the play console (type 'play' to get to the console)

run 8080

How to force a component's re-rendering in Angular 2?

tx, found the workaround I needed:

  constructor(private zone:NgZone) {
    // enable to for time travel
    this.appStore.subscribe((state) => {
        this.zone.run(() => {
            console.log('enabled time travel');
        });
    });

running zone.run will force the component to re-render

Use multiple custom fonts using @font-face?

If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.

The easiest way I found to find this out was to install the font and see what display name is given.

For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.

Hope that helps.

MVC ajax post to controller action method

It's due to you sending one object, and you're expecting two parameters.

Try this and you'll see:

public class UserDetails
{
   public string username { get; set; }
   public string password { get; set; }
}

public JsonResult Login(UserDetails data)
{
   string error = "";
   //the rest of your code
}

javascript window.location in new tab

We have to dynamically set the attribute target="_blank" and it will open it in new tab. document.getElementsByTagName("a")[0].setAttribute('target', '_blank')

document.getElementsByTagName("a")[0].click()

If you want to open in new window, get the href link and use window.open

var link = document.getElementsByTagName("a")[0].getAttribute("href");

window.open(url, "","height=500,width=500");

Don't provide the second parameter as _blank in the above.

Is there a way to make HTML5 video fullscreen?

Most of the answers here are outdated.

It's now possible to bring any element into fullscreen using the Fullscreen API, although it's still quite a mess because you can't just call div.requestFullScreen() in all browsers, but have to use browser specific prefixed methods.

I've created a simple wrapper screenfull.js that makes it easier to use the Fullscreen API.

Current browser support is:

  • Chrome 15+
  • Firefox 10+
  • Safari 5.1+

Note that many mobile browsers don't seem to support a full screen option yet.

Passive Link in Angular 2 - <a href=""> equivalent

There are ways of doing it with angular2, but I strongly disagree this is a bug. I'm not familiarized with angular1, but this seems like a really wrong behavior even though as you claim is useful in some cases, but clearly this should not be the default behavior of any framework.

Disagreements aside you can write a simple directive that grabs all your links and check for href's content and if the length of it it's 0 you execute preventDefault(), here's a little example.

@Directive({
  selector : '[href]',
  host : {
    '(click)' : 'preventDefault($event)'
  }
})
class MyInhertLink {
  @Input() href;
  preventDefault(event) {
    if(this.href.length == 0) event.preventDefault();
  }
}

You can make it to work across your application by adding this directive in PLATFORM_DIRECTIVES

bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: MyInhertLink, multi: true})]);

Here's a plnkr with an example working.

How do I install jmeter on a Mac?

after

brew install jmeter

then

open /usr/local/bin/jmeter

How to Get a Specific Column Value from a DataTable?

Datatables have a .Select method, which returns a rows array according to the criteria you specify. Something like this:

Dim oRows() As DataRow

oRows = dtCountries.Select("CountryName = '" & userinput & "'")

If oRows.Count = 0 Then
   ' No rows found
Else
   ' At least one row found. Could be more than one
End If

Of course, if userinput contains ' character, it would raise an exception (like if you query the database). You should escape the ' characters (I use a function to do that).

How to get file path in iPhone app

You need to use the URL for the link, such as this:

NSURL *path = [[NSBundle mainBundle] URLForResource:@"imagename" withExtension:@"jpg"];

It will give you a proper URL ref.

python: order a list of numbers without built-in sort, min, max function

data = [3, 1, 5, 2, 4]
n = len(data)
    for i in range(n):
        for j in range(1,n):
            if data[j-1] > data[j]:
                (data[j-1], data[j]) = (data[j], data[j-1])
    print(data)

How to set environment variables in Jenkins?

In my case, I had configure environment variables using the following option and it worked-

Manage Jenkins -> Configure System -> Global Properties -> Environment Variables -> Add

GridView - Show headers on empty data source

I found a very simple solution to the problem. I simply created two GridViews. The first GridView called a DataSource with a query that was designed to return no rows. It simply contained the following:

    <Columns>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left">
            <HeaderTemplate>

               <asp:Label ID="lbl0" etc.>  </asp:Label>
               <asp:Label ID="lbl1" etc.>  </asp:Label>

            </HeaderTemplate>
        </asp:TemplateField>
    </Columns>

Then I created a div with the following characteristics and I place a GridView inside of it with ShowHeader="false" so that the top row is the same size as all the other rows.

<div style="overflow: auto; height: 29.5em; width: 100%">
    <asp:GridView ID="Rollup" runat="server" ShowHeader="false" DataSourceID="ObjectDataSource">
        <Columns>
            <asp:TemplateField HeaderStyle-HorizontalAlign="Left">
                <ItemTemplate>

               <asp:Label ID="lbl0" etc.>  </asp:Label>
               <asp:Label ID="lbl1" etc.>  </asp:Label>

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

AddRange to a Collection

Agree with some guys above and Lipert's opinion. In my case, it's quite often to do like this:

ICollection<int> A;
var B = new List<int> {1,2,3,4,5};
B.ForEach(A.Add);

To have an extension method for such operation a bit redundant in my view.

How to insert values in two dimensional array programmatically?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).

But you can chain the index operator for array element access.

String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];

x[0][0] = "a1";
    // No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";

Note the dimensions of the child arrays don't need to match.

How to call a function within class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...

How to convert float to varchar in SQL Server

Useful topic thanks.

If you want like me remove leadings zero you can use that :

DECLARE @MyFloat [float];
SET @MyFloat = 1000109360.050;
SELECT REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(STR(@MyFloat, 38, 16), '0', ' '))), ' ', '0'),'.',' ')),' ',',')

grant remote access of MySQL database from any IP address

Use this command:

GRANT ALL ON yourdatabasename.* TO root@'%' IDENTIFIED BY 'yourRootPassword';

Then:

FLUSH PRIVILEGES; 

Then comment out the below line in file "/etc/mysql/mysql.conf.d/mysqld.cnf" (is required!):

bind-address = 127.0.0.1 

Works for me!

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?

  • Check the other server's network configuration in SQL Server.
  • Check the other machines FIREWALL. SQL Server does not open ports automatically, so the windows firewall normally blocks access..

How to add a right button to a UINavigationController?

@Artilheiro : If its a navigationbased project, u can create BaseViewController. All other view will inherit this BaseView. In BaseView u can define generic methods to add right button or to change left button text.

ex:

@interface BaseController : UIViewController {

} - (void) setBackButtonCaption:(NSString *)caption;

(void) setRightButtonCaption:(NSString *)caption selectot:(SEL )selector;

@end // In BaseView.M

(void) setBackButtonCaption:(NSString *)caption {

UIBarButtonItem *backButton =[[UIBarButtonItem alloc] init];

backButton.title= caption;
self.navigationItem.backBarButtonItem = backButton;
[backButton release];

} - (void) setRightButtonCaption:(NSString *)caption selectot:(SEL )selector {

  UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] init];
rightButton.title = caption;

rightButton.target= self;

[rightButton setAction:selector];

self.navigationItem.rightBarButtonItem= rightButton;

[rightButton release];

}

And now in any custom view, implement this base view call the methods:

@interface LoginView : BaseController {

In some method call base method as:

SEL sel= @selector(switchToForgotPIN);

[super setRightButtonCaption:@"Forgot PIN" selectot:sel];

Most efficient way to find mode in numpy array

Check scipy.stats.mode() (inspired by @tom10's comment):

import numpy as np
from scipy import stats

a = np.array([[1, 3, 4, 2, 2, 7],
              [5, 2, 2, 1, 4, 1],
              [3, 3, 2, 2, 1, 1]])

m = stats.mode(a)
print(m)

Output:

ModeResult(mode=array([[1, 3, 2, 2, 1, 1]]), count=array([[1, 2, 2, 2, 1, 2]]))

As you can see, it returns both the mode as well as the counts. You can select the modes directly via m[0]:

print(m[0])

Output:

[[1 3 2 2 1 1]]

Can I apply a CSS style to an element name?

if in case you are not using name in input but other element, then you can target other element with there attribute.

_x000D_
_x000D_
    [title~=flower] {_x000D_
      border: 5px solid yellow;_x000D_
    }
_x000D_
    <img src="klematis.jpg" title="klematis flower" width="150" height="113">_x000D_
    <img src="img_flwr.gif" title="flower" width="224" height="162">_x000D_
    <img src="img_flwr.gif" title="flowers" width="224" height="162">
_x000D_
_x000D_
_x000D_

hope its help. Thank you

MetadataException when using Entity Framework Entity Connection

I had the same problem with three projects in one solution and all of the suggestions didn't work until I made a reference in the reference file of the web site project to the project where the edmx file sits.

How to get an Android WakeLock to work?

To achieve the same programmatic you can use following

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

or adding following in layout also will perform the above task

 android:keepScreenOn="true"

The details you can get from following url http://developer.android.com/training/scheduling/wakelock.html

I have used combination of following to wake my screen when keyguard locked and keep my screen on

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

Call JavaScript function on DropDownList SelectedIndexChanged Event:

You can use the ScriptManager.RegisterStartupScript(); to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();, you can do this:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}

To be exact for you, do this...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}

MySQL ORDER BY multiple column ASC and DESC

group by default order by pk id,so the result
username point avg_time
demo123 100 90 ---> id = 4
demo123456 100 100 ---> id = 7
demo 90 120 ---> id = 1

How to Flatten a Multidimensional Array?

This can be achieved by using array_walk_recursive

$a = array(1,2,array(3,4, array(5,6,7), 8), 9);
array_walk_recursive($a, function($v) use (&$r){$r[]=$v;});
print_r($r);

Working example :- https://3v4l.org/FpIrG

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.
</xsl:if>

How can I insert vertical blank space into an html document?

i always use this cheap word for vertical spaces.

    <p>Q1</p>
    <br>
    <p>Q2</p>

ViewDidAppear is not called when opening app from background

try adding this in AppDelegate applicationWillEnterForeground.

func applicationWillEnterForeground(_ application: UIApplication) {        
    // makes viewWillAppear run
    self.window?.rootViewController?.beginAppearanceTransition(true, animated: false)
    self.window?.rootViewController?.endAppearanceTransition()
}

How to add a 'or' condition in #ifdef

May use this-

#if defined CONDITION1 || defined CONDITION2
//your code here
#endif

This also does the same-

#if defined(CONDITION1) || defined(CONDITION2)
//your code here
#endif

Further-

  • AND: #if defined CONDITION1 && defined CONDITION2
  • XOR: #if defined CONDITION1 ^ defined CONDITION2
  • AND NOT: #if defined CONDITION1 && !defined CONDITION2

Find rows that have the same value on a column in MySQL

This works best

Screenshot enter image description here

SELECT RollId, count(*) AS c 
    FROM `tblstudents` 
    GROUP BY RollId 
    HAVING c > 1 
    ORDER BY c DESC

Get all messages from Whatsapp

Edit

As WhatsApp put some effort into improving their encryption system, getting the data is not that easy anymore. With newer versions of WhatsApp it is no longer possible to use adb backup. Apps can deny backups and the WhatsApp client does that. If you happen to have a rooted phone, you can use a root shell to get the unencrypted database file.

If you do not have root, you can still decrypt the data if you have an old WhatsApp APK. Find a version that still allows backups. Then you can make a backup of the app's data folder, which will contain an encryption key named, well, key.

Now you'll need the encrypted database. Use a file explorer of your choice or, if you like the command line more, use adb:

adb pull /sdcard/WhatsApp/Databases/msgstore.db.crypt12

Using the two files, you could now use https://gitlab.com/digitalinternals/whatsapp-crypt12 to get the plain text database. It is no longer possible to use Linux board tools like openssl because WhatsApp seems to use a modified version of the Spongy Castle API for cryptography that openssl does not understand.

Original Answer (only for the old crypt7)

As whatsapp is now using the crypt7 format, it is not that easy to get and decrypt the database anymore. There is a working approach using ADB and USB debugging.

You can either get the encryption keys via ADB and decrypt the message database stored on /sdcard, or you just get the plain version of the database via ADB backup, what seems to be the easier option.

To get the database, do the following:

Connect your Android phone to your computer. Now run

adb backup -f whatsapp_backup.ab -noapk com.whatsapp

to backup all files WhatsApp has created in its private folder.
You will get a zlib compressed file using tar format with some ADB headers. We need to get rid of those headers first as they confuse the decompression command:

dd if=whatsapp_backup.ab ibs=1 skip=24 of=whatsapp_backup.ab.nohdr

The file can now be decompressed:

cat whatsapp_backup.ab.nohdr | python -c "import zlib,sys;sys.stdout.write(zlib.decompress(sys.stdin.read()))" 1> whatsapp_backup.tar

This command runs Python and decompresses the file using zlib to whatsapp_backup.tar
Now we can unTAR the file:

tar xf whatsapp_backup.tar

The archive is now extracted to your current working directory and you can find the databases (msgstore.db and wa.db) in apps/com.whatsapp/db/

Sending mail attachment using Java

For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.

If you want both attachment and text try this based on the accepted answer :

    Properties props = new java.util.Properties();
    props.put("mail.smtp.host", "yourHost");
    props.put("mail.smtp.port", "yourHostPort");
    props.put("mail.smtp.auth", "true");             
    props.put("mail.smtp.starttls.enable", "true");


    // Session session = Session.getDefaultInstance(props, null);
    Session session = Session.getInstance(props,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("user", "password");
                }
              });


    Message msg = new MimeMessage(session);
    try {
        msg.setFrom(new InternetAddress(mailFrom));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        msg.setSubject("your subject");

        Multipart multipart = new MimeMultipart();

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText("your text");

        MimeBodyPart attachmentBodyPart= new MimeBodyPart();
        DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"

        multipart.addBodyPart(textBodyPart);  // add the text part
        multipart.addBodyPart(attachmentBodyPart); // add the attachement part

        msg.setContent(multipart);


        Transport.send(msg);
    } catch (MessagingException e) {
        LOGGER.log(Level.SEVERE,"Error while sending email",e);
    }

Update :

If you want to send a mail as an html content formated you have to do

    MimeBodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setContent(content, "text/html");

So basically setText is for raw text and will be well display on every server email including gmail, setContent is more for an html template and if you content is formatted as html it will maybe also works in gmail

Where does the @Transactional annotation belong?

@Transactional Annotations should be placed around all operations that are inseparable. Using @Transactional transaction propagation are handled automatically.In this case if another method is called by current method,then that method will have the option of joining the ongoing transaction.

So lets take example:

We have 2 model's i.e. Country and City. Relational Mapping of Country and City model is like one Country can have multiple Cities so mapping is like,

@OneToMany(fetch = FetchType.LAZY, mappedBy="country")
private Set<City> cities;

Here Country mapped to multiple cities with fetching them Lazily. So here comes role of @Transactinal when we retrieve Country object from database then we will get all the data of Country object but will not get Set of cities because we are fetching cities LAZILY.

//Without @Transactional
public Country getCountry(){
   Country country = countryRepository.getCountry();
   //After getting Country Object connection between countryRepository and database is Closed 
}

When we want to access Set of Cities from country object then we will get null values in that Set because object of Set created only this Set is not initialize with there data to get values of Set we use @Transactional i.e.,

//with @Transactional
@Transactional
public Country getCountry(){
   Country country = countryRepository.getCountry();
   //below when we initialize cities using object country so that directly communicate with database and retrieve all cities from database this happens just because of @Transactinal
   Object object = country.getCities().size();   
}

So basically @Transactional is Service can make multiple call in single transaction without closing connection with end point.

AngularJS - Multiple ng-view in single template

You cant have multiple ng-view. Below is my use case where I solved my requirement. I wanted to have tabbed behavior in my model dialog. I was facing issue as click on tabs having hyperlink which will invoke router links. I solved this using button and css for tabs. When user clicks on tab, it actually will not call any hyperlink which will always invoke the ng-router. When user click on tab it will call a method, where I dynamcilly load html. Below is the function on click of tab

self.submit = function(form) {
                $templateRequest('resources/items/employee/test_template.html').then(function(template){
                var compiledeHTML = $compile(template)($scope);
                $("#d").replaceWith(compiledeHTML);
});

User $templateRequest. In test_template.html page add your html content. This html content will be bind to your controller.

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

It's the Simple way to convert to format

 DateTime.Now.ToString("yyyyMMdd");

Reset select value to default

For those who are working with Bootstrap-select, you might want to use this:

$('#mySelect').selectpicker('render');

How do I avoid the specification of the username and password at every git push?

If you already have your SSH keys set up and are still getting the password prompt, make sure your repo URL is in the form

git+ssh://[email protected]/username/reponame.git

as opposed to

https://github.com/username/reponame.git

To see your repo URL, run:

git remote show origin

You can change the URL with git remote set-url like so:

git remote set-url origin git+ssh://[email protected]/username/reponame.git

add new element in laravel collection object

It looks like you have everything correct according to Laravel docs, but you have a typo

$item->push($product);

Should be

$items->push($product);

I also want to think the actual method you're looking for is put

$items->put('products', $product);

Send JSON data from Javascript to PHP?

    <html>
<script type="text/javascript">
var myJSONObject = {"bindings": 11};
alert(myJSONObject);

var stringJson =JSON.stringify(myJSONObject);
alert(stringJson);
</script>
</html>

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

T-SQL Substring - Last 3 Characters

You can use either way:

SELECT RIGHT(RTRIM(columnName), 3)

OR

SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)

What is the difference between Integer and int in Java?

int is a primitive type that represent an integer. whereas Integer is an Object that wraps int. The Integer object gives you more functionality, such as converting to hex, string, etc.

You can also use OOP concepts with Integer. For example, you can use Integer for generics (i.e. Collection<Integer>).

GitHub: How to make a fork of public repository private?

There is one more option now ( January-2015 )

  1. Create a new private repo
  2. On the empty repo screen there is an "import" option/button enter image description here
  3. click it and put the existing github repo url There is no github option mention but it works with github repos too. enter image description here
  4. DONE

How do I purge a linux mail box with huge number of emails?

alternative way:

mail -N
d *
quit

-N Inhibits the initial display of message headers when reading mail or editing a mail folder.
d * delete all mails

How to automatically insert a blank row after a group of data

I have a large file in excel dealing with purchase and sale of mutual fund units. Number of rows in a worksheet exceeds 4000. I have no experience with VBA and would like to work with basic excel. Taking the cue from the solutions suggested above, I tried to solve the problem ( to insert blank rows automatically) in the following manner:

  1. I sorted my file according to control fields
  2. I added a column to the file
  3. I used the "IF" function to determine when there is a change in the control data .
  4. If there is a change the result will indicate "yes", otherwise "no"
  5. Then I filtered the data to group all "yes" items
  6. I copied mutual fund names, folio number etc (no financial data)
  7. Then I removed the filter and sorted the file again. The result is a row added at the desired place. (It is not entirely a blank row, because if it is fully blank, sorting will not place the row at the desired place.)
  8. After sorting, you can easily delete all values to get a completely blank row.

This method also may be tried by the readers.

Converting JSONarray to ArrayList

Instead of converting the JSON string to an ArrayList or even a Map, you can just create a JSONObject itself. This object has the ability to get string values by key, as you want and also to remove objects.

To create a JSONObject from a properly formatted JSON string, you simply call the appropriate constructor.

JSONObject json = new JSONObject(jsonString);

Internal vs. Private Access Modifiers

private - encapsulations in class/scope/struct ect'.

internal - encapsulation in assemblies.

Webdriver and proxy server for firefox

Preferences -> Advanced -> Network -> Connection (Configure how Firefox connects to the Internet)

How to update value of a key in dictionary in c#?

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5

How to change identity column values programmatically?

This can be done using a temporary table.

The idea

  • disable constraints (in case your id is referenced by a foreign key)
  • create a temp table with the new id
  • delete the table content
  • copy back data from the copied table to your original table
  • enable previsously disabled constraints

SQL Queries

Let's say your test table have two additional columns (column2 and column3) and that there are 2 tables having foreign keys referencing test called foreign_table1 and foreign_table2 (because real life issues are never simple).

alter table test nocheck constraint all;
alter table foreign_table1 nocheck constraint all;
alter table foreign_table2 nocheck constraint all;
set identity_insert test on;

select id + 1 as id, column2, column3 into test_copy from test v;
delete from test;
insert into test(id, column2, column3)
select id, column2, column3 from test_copy

alter table test check constraint all;
alter table foreign_table1 check constraint all;
alter table foreign_table2 check constraint all;
set identity_insert test off;
drop table test_copy;

That's it.

How to import an Oracle database from dmp file and log file?

All this peace of code put into *.bat file and run all at once:

My code for creating user in oracle. crate_drop_user.sql file

drop user "USER" cascade;
DROP TABLESPACE "USER";

CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE 
    AUTOEXTEND 
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    SEGMENT SPACE MANAGEMENT  AUTO
/ 

CREATE  TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE 
    'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    UNIFORM SIZE 1M    
/

CREATE USER "USER"  PROFILE "DEFAULT" 
    IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER" 
    TEMPORARY TABLESPACE "USER_TEMP" 
/    

alter user USER quota unlimited on "USER";

GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";

create file import.bat and put this lines in it:

SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log

Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.

Good luck, Ivan

'Java' is not recognized as an internal or external command

In case you are using a laptop and do not have the Pause\Break button. For windows 10 users with 20h2 and above:

1 WIN ? type "About your PC" ? scroll at the bottom ? Advanced system settings ? Environment variables or WIN+R ? shell:::{bb06c0e4-d293-4f75-8a90-cb05b6477eee} to open Classic System Properties ? on the left side ? Advanced system settings ? Environment variables

Also for Windows 10 and Windows 7:

1 WIN ? This PC ? properties ? Advanced system settings ? Environment variables

  1. In the System variables section click on New…
  2. In Variable name write: JAVA_HOME
  3. In Variable value write: C:\Program Files\Java\jdk-15.0.2\bin, press OK

I have taken steps 2-4 from Vijay Bhatt

Adding a new system variable in UI

There is a bit faster way to set a system variable. Run a console (terminal) as an administrator.

General command synax to add a new variable:

setx variableName value /M

In our example, we would need to set it as

setx JAVA_HOME "C:\Program Files\Java\jdk-15.0.2\bin" /M`

Like this: Adding a new system variable using admin console

/M - flag specifies to set the variable in the system environment. After command execution, you should see the message: SUCCESS: Specified value was saved.

How can I check that it is added?

  1. Close your active terminal;
  2. Open your favorite terminal;
  3. Type java -version.

You should see something similar to this: Result image

Notice: User variables can be created w/o having a root (administrator privileges), whereas to create System variable; You need to open a console as a root.

I have used C:\Program Files\Java\jdk-15.0.2\bin as an example, in your case, it could be different from mine.

ImportError: No module named site on Windows

I had the same problem. My solution was to repair the Python installation. (It was a new installation so I did not expect a problem but now it is solved.)

To repair (Windows 7):

  1. go to Control Panel -> Programs -> Programs and Features
  2. click on the Python version installed and then press Uninstall/Change.
  3. follow the instructions to repair the installation.

AngularJS does not send hidden field value

Below Code will work for this IFF it in the same order as its mentionened make sure you order is type then name, ng-model ng-init, value. thats It.

Declaring a boolean in JavaScript using just var

You can use and test uninitialized variables at least for their 'definedness'. Like this:

var iAmNotDefined;
alert(!iAmNotDefined); //true
//or
alert(!!iAmNotDefined); //false

Furthermore, there are many possibilites: if you're not interested in exact types use the '==' operator (or ![variable] / !![variable]) for comparison (that is what Douglas Crockford calls 'truthy' or 'falsy' I think). In that case assigning true or 1 or '1' to the unitialized variable always returns true when asked. Otherwise [if you need type safe comparison] use '===' for comparison.

var thisMayBeTrue;

thisMayBeTrue = 1;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false

thisMayBeTrue = '1';
alert(thisMayBeTrue == true); //=> true 
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, in this case, using == or !! '1' is implicitly 
// converted to 1 and 1 is implicitly converted to true)

thisMayBeTrue = true;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> true

thisMayBeTrue = 'true';
alert(thisMayBeTrue == true); //=> false
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, here's no implicit conversion of the string 'true'
// it's also a demonstration of the fact that the 
// ! or !! operator tests the 'definedness' of a variable.

PS: you can't test 'definedness' for nonexisting variables though. So:

alert(!!HelloWorld);

gives a reference Error ('HelloWorld is not defined')

(is there a better word for 'definedness'? Pardon my dutch anyway;~)

Java "?" Operator for checking null - What is it? (Not Ternary!)

It is possible to define util methods which solves this in an almost pretty way with Java 8 lambda.

This is a variation of H-MANs solution but it uses overloaded methods with multiple arguments to handle multiple steps instead of catching NullPointerException.

Even if I think this solution is kind of cool I think I prefer Helder Pereira's seconds one since that doesn't require any util methods.

void example() {
    Entry entry = new Entry();
    // This is the same as H-MANs solution 
    Person person = getNullsafe(entry, e -> e.getPerson());    
    // Get object in several steps
    String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());
    // Call void methods
    doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt());        
}

/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */
public static <R, T1> R getNullsafe(T1 o1, Function<T1, R> f1) {
    if (o1 != null) return f1.apply(o1);
    return null; 
}

public static <R, T0, T1> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, R> f2) {
    return getNullsafe(getNullsafe(o0, f1), f2);
}

public static <R, T0, T1, T2> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Function<T2, R> f3) {
    return getNullsafe(getNullsafe(o0, f1, f2), f3);
}


/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */
public static <T1> void doNullsafe(T1 o1, Consumer<T1> f1) {
    if (o1 != null) f1.accept(o1);
}

public static <T0, T1> void doNullsafe(T0 o0, Function<T0, T1> f1, Consumer<T1> f2) {
    doNullsafe(getNullsafe(o0, f1), f2);
}

public static <T0, T1, T2> void doNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Consumer<T2> f3) {
    doNullsafe(getNullsafe(o0, f1, f2), f3);
}


class Entry {
    Person getPerson() { return null; }
}

class Person {
    Name getName() { return null; }
}

class Name {
    void nameIt() {}
    String getGivenName() { return null; }
}

CONVERT Image url to Base64

<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
  function encodeImageFileAsURL() {

    var filesSelected = document.getElementById("inputFileToLoad").files;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0];

      var fileReader = new FileReader();

      fileReader.onload = function(fileLoadedEvent) {
        var srcData = fileLoadedEvent.target.result; // <--- data: base64

        var newImage = document.createElement('img');
        newImage.src = srcData;

        document.getElementById("imgTest").innerHTML = newImage.outerHTML;
        alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
        console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
      }
      fileReader.readAsDataURL(fileToLoad);
    }
  }
</script>

Google Script to see if text contains a value

I used the Google Apps Script method indexOf() and its results were wrong. So I wrote the small function Myindexof(), instead of indexOf:

function Myindexof(s,text)
{
  var lengths = s.length;
  var lengtht = text.length;
  for (var i = 0;i < lengths - lengtht + 1;i++)
  {
    if (s.substring(i,lengtht + i) == text)
      return i;
  }
  return -1;
}

var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
   Logger.log('yes');
else
   Logger.log('no');

Eclipse Java Missing required source folder: 'src'

I was confused by this for hours.

Right click on project -> Build Path -> Configure Build Path -> Add Folder

Should Jquery code go in header or footer?

Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?

There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.

Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.

In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Checking session if empty or not

You should first check if Session["emp_num"] exists in the session.

You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])

package R does not exist

What files are you importing into the files getting the R error?

My understanding of the R file are that they are automatically generated reference lists to all attributes within the Android app. Therefore, you can't change it yourself.

Are you using Eclipse to build this project? Were the older projects getting these errors made before updating Eclipse? What are the references that are getting errors?

Check to make sure that you've not imported another R file from other copied code in another app.

How to enable remote access of mysql in centos?

In case of Allow IP to mysql server linux machine. you can do following command--

 nano /etc/httpd/conf.d/phpMyAdmin.conf  and add Desired IP.

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8
   Order allow,deny
   allow from all
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>

    Require ip 192.168.9.1(Desired IP)

</RequireAny>
   </IfModule>
 <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     #Allow from All

     Allow from 192.168.9.1(Desired IP)

</IfModule>

And after Update, please restart using following command--

sudo systemctl restart httpd.service

Read response headers from API response - Angular 5 + TypeScript

You can get headers using below code

let main_headers = {}
this.http.post(url,
  {email: this.username, password: this.password},
  {'headers' : new HttpHeaders ({'Content-Type' : 'application/json'}), 'responseType': 'text', observe:'response'})
  .subscribe(response => {
    const keys = response.headers.keys();
    let headers = keys.map(key => {
      `${key}: ${response.headers.get(key)}`
        main_headers[key] = response.headers.get(key)
       }
      );
  });

later we can get the required header form the json object.

header_list['X-Token']

Running java with JAVA_OPTS env variable has no effect

You can setup _JAVA_OPTIONS instead of JAVA_OPTS. This should work without $_JAVA_OPTIONS.

What's the best way to check if a file exists in C?

FILE *file;
    if((file = fopen("sample.txt","r"))!=NULL)
        {
            // file exists
            fclose(file);
        }
    else
        {
            //File not found, no memory leak since 'file' == NULL
            //fclose(file) would cause an error
        }

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

What are the differences between "git commit" and "git push"?

git commit is nothing but saving our changes officially, for every commit we give commit message, once we are done with commits we can push it to remote to see our change globally

which means we can do numerous commits before we push to remote (we can see the list of commits happened and the messages too) git saves each commit with commit id which is a 40 digit code

and I use git push only when i wanted to see my change in remote (There after i will check whether my code worked in jenkins)

How do you access a website running on localhost from iPhone browser

If you are using Mac, go to System Preferences > Network and use your IP address instead of localhost. You can also use port number. In my case, I have a server running on port 1448 and I can preview 192.168.1.241:1448 using iPhone.

MacOsNetworkSettings

Error: Cannot find module html

Simple way is to use the EJS template engine for serving .html files. Put this line right next to your view engine setup:

app.engine('html', require('ejs').renderFile);

Error inflating class android.support.v7.widget.Toolbar?

Sorry Guys. I have solved this Issue long ago. I did a lot of changes. So I can't figure out which one does the trick.

  1. I have changed the id as suggested by Jared Burrows.

  2. Removed my support library and cleaned my project and Re added it.

  3. Go to File -> Invalidate Caches/Restart.

Hope it works.

This is how my code looks now

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/toolbar_actionbar"
        layout="@layout/toolbar_default"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar_actionbar">

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <fragment
            android:id="@+id/fragment_drawer"
            android:name="com.arul.anahy.drawer.NavigationDrawerFragment"
            android:layout_width="@dimen/navigation_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/fragment_navigation_drawer"/>
    </android.support.v4.widget.DrawerLayout>
</RelativeLayout>

toolbar_default.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    style="@style/ToolBarStyle"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="@dimen/abc_action_bar_default_height_material"/>

ToolBarStyle

<style name="ToolBarStyle" parent="">
        <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
 </style>

Find running median from a stream of integers

If you can't hold all the items in memory at once, this problem becomes much harder. The heap solution requires you to hold all the elements in memory at once. This is not possible in most real world applications of this problem.

Instead, as you see numbers, keep track of the count of the number of times you see each integer. Assuming 4 byte integers, that's 2^32 buckets, or at most 2^33 integers (key and count for each int), which is 2^35 bytes or 32GB. It will likely be much less than this because you don't need to store the key or count for those entries that are 0 (ie. like a defaultdict in python). This takes constant time to insert each new integer.

Then at any point, to find the median, just use the counts to determine which integer is the middle element. This takes constant time (albeit a large constant, but constant nonetheless).

How can I get the count of line in a file in an efficient way?

The buffered reader is overkill

Reader r = new FileReader("f.txt");

int count = 0;
int nextchar = 0;
while (nextchar != -1){
        nextchar = r.read();
        if (nextchar == Character.getNumericValue('\n') ){
            count++;
        }
    }

My search for a simple example has createde one thats actually quite poor. calling read() repeadedly for a single character is less than optimal. see here for examples and measurements.

How to see indexes for a database or table in MySQL?

To query the index information of a table, you use the SHOW INDEXES statement as follows:

 SHOW INDEXES FROM table_name;

You can specify the database name if you are not connected to any database or you want to get the index information of a table in a different database:

SHOW INDEXES FROM table_name 
IN database_name;

The following query is similar to the one above:

SHOW INDEXES FROM database_name.table_name;

Note that INDEX and KEYS are the synonyms of the INDEXES, IN is the synonym of the FROM, therefore, you can use these synonyms in the SHOW INDEXES column instead. For example:

SHOW INDEX IN table_name 
FROM database_name;

Or

 SHOW KEYS FROM tablename
 IN databasename;

iOS application: how to clear notifications?

Most likely because Notification Center is a relatively new feature, Apple didn't necessarily want to push a whole new paradigm for clearing notifications. So instead, they multi-purposed [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0]; to clear said notifications. It might seem a bit weird, and Apple might provide a more intuitive way to do this in the future, but for the time being it's the official way.

Myself, I use this snippet:

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

which never fails to clear all of the app's notifications from Notification Center.

How to create a JQuery Clock / Timer

var eventdate = new Date("January 01, 2014 00:00:00");

function toSt(n) {
 s=""
 if(n<10) s+="0"
 return s+n.toString();
}

function countdown() {
 cl=document.clock;
 d=new Date();
 count=Math.floor((eventdate.getTime()-d.getTime())/1000);
 if(count<=0)
   {cl.days.value ="----";
    cl.hours.value="--";
    cl.mins.value="--";
    cl.secs.value="--";
    return;
  }
 cl.secs.value=toSt(count%60);
 count=Math.floor(count/60);
 cl.mins.value=toSt(count%60);
 count=Math.floor(count/60);
 cl.hours.value=toSt(count%24);
 count=Math.floor(count/24);
 cl.days.value=count;    

 setTimeout("countdown()",500);
}

Hello, I've a similar assignment which involved creating a Javascript Countdown Clock. Here's the code I used. Plug the above code between the < script language="Javascript" >< /script > tags. Keep in mind that just having this javascript won't do much if you don't have the html to display the clock. I'll leave writing the html to you. Design the clock however you wish.

How to count down in for loop?

First I recommand you can try use print and observe the action:

for i in range(0, 5, 1):
    print i

the result:

0
1
2
3
4

You can understand the function principle. In fact, range scan range is from 0 to 5-1. It equals 0 <= i < 5

When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.

You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.

for i in range(5, 0, -1):
    print i

the result:

5
4
3
2
1

Thus it can be seen, it equals 5 >= i > 0

You want to implement your java code in python:

for (int index = last-1; index >= posn; index--)

It should code this:

for i in range(last-1, posn-1, -1)

Is it possible to have empty RequestParam values use the defaultValue?

You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
    if(i == null) {
        i = 10;
    }
    // ...
}

I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

http://example.com/test

How do you get the current time of day?

I'm experimenting with this also and find these pages helpful as well. First the main class... https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx

Now some specifier formats for the ToString method... https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo(v=vs.110).aspx

Example:

using System;

namespace JD
{
    class Program
    {
        public static DateTime get_UTCNow()
        {
            DateTime UTCNow = DateTime.UtcNow;
            int year = UTCNow.Year;
            int month = UTCNow.Month;
            int day = UTCNow.Day;
            int hour = UTCNow.Hour;
            int min = UTCNow.Minute;
            int sec = UTCNow.Second;
            DateTime datetime = new DateTime(year, month, day, hour, min, sec);
            return datetime;
        }

        static void Main(string[] args)
        {
            DateTime datetime = get_UTCNow();            

            string time_UTC = datetime.TimeOfDay.ToString();
            Console.WriteLine(time_UTC);

            Console.ReadLine();

        }
    }
}

I threw that TimeOfDay method in there just to show that you get a default of 24 hour time as is stated "the time from midnight"

You may use my geter method(); :-D

How to view the committed files you have not pushed yet?

I'm not great with Git, but this is what I do. This does not necessarily compare with the remote repo, but you can modify the git diff with the appropriate commit hash from the remote.

Say you made one commit that you haven't pushed...

First find the last two commits...

git log -2

This shows the last commit first, and descends from there...

[jason:~/git/my_project] git log -2
commit ea7937edc8b10
Author: xyz
Date:   Wed Jul 27 14:06:41 2016 -0500

    Made a change in July

commit 52f9bf7956f0
Author: xyz
Date:   Tue Jun 14 14:29:52 2016 -0500

    Made a change in June

Now just use the two commit hashes (which I abbreviated) to run a diff:

git diff 52f9bf7956f0 ea7937edc8b10

jQuery get values of checked checkboxes into array

DEMO: http://jsfiddle.net/PBhHK/

$(document).ready(function(){

    var searchIDs = $('input:checked').map(function(){

      return $(this).val();

    });
    console.log(searchIDs.get());

});

Just call get() and you'll have your array as it is written in the specs: http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

SET NAMES utf8 in MySQL?

It is needed whenever you want to send data to the server having characters that cannot be represented in pure ASCII, like 'ñ' or 'ö'.

That if the MySQL instance is not configured to expect UTF-8 encoding by default from client connections (many are, depending on your location and platform.)

Read http://www.joelonsoftware.com/articles/Unicode.html in case you aren't aware how Unicode works.

Read Whether to use "SET NAMES" to see SET NAMES alternatives and what exactly is it about.

What is the difference between cache and persist?

Spark gives 5 types of Storage level

  • MEMORY_ONLY
  • MEMORY_ONLY_SER
  • MEMORY_AND_DISK
  • MEMORY_AND_DISK_SER
  • DISK_ONLY

cache() will use MEMORY_ONLY. If you want to use something else, use persist(StorageLevel.<*type*>).

By default persist() will store the data in the JVM heap as unserialized objects.

Rename a file in C#

When C# doesn't have some feature, I use C++ or C:

public partial class Program
{
    [DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
    public static extern int rename(
            [MarshalAs(UnmanagedType.LPStr)]
            string oldpath,
            [MarshalAs(UnmanagedType.LPStr)]
            string newpath);

    static void FileRename()
    {
        while (true)
        {
            Console.Clear();
            Console.Write("Enter a folder name: ");
            string dir = Console.ReadLine().Trim('\\') + "\\";
            if (string.IsNullOrWhiteSpace(dir))
                break;
            if (!Directory.Exists(dir))
            {
                Console.WriteLine("{0} does not exist", dir);
                continue;
            }
            string[] files = Directory.GetFiles(dir, "*.mp3");

            for (int i = 0; i < files.Length; i++)
            {
                string oldName = Path.GetFileName(files[i]);
                int pos = oldName.IndexOfAny(new char[] { '0', '1', '2' });
                if (pos == 0)
                    continue;

                string newName = oldName.Substring(pos);
                int res = rename(files[i], dir + newName);
            }
        }
        Console.WriteLine("\n\t\tPress any key to go to main menu\n");
        Console.ReadKey(true);
    }
}

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

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

What's the best practice for putting multiple projects in a git repository?

While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.

Solution 1

A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.

git checkout --orphan BRANCHNAME

This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.

Now for whatever reason, git needs a bit of cleanup after an orphan checkout.

rm .git/index
rm -r *

Make sure everything is committed before deleting

Once the orphan branch is clean, you can use it normally.

Solution 2

Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.

# repo 1
git push origin master:master-1

# repo 2
git push origin master:master-2

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

What do 3 dots next to a parameter type mean in Java?

String... is the same as String[]

import java.lang.*;

public class MyClassTest {

    //public static void main(String... args) { 

    public static void main(String[] args) {
        for(String str: args) {
            System.out.println(str);
        }
    }
}

HRESULT: 0x800A03EC on Worksheet.range

This type of error can also occur when the excel file is corrupted for some reason

Google Spreadsheet, Count IF contains a string

Try using wildcards directly in the COUNTIF function :

=(COUNTIF(A2:A51,"=*iPad*")/COUNTA(A2:A51))*1

lambda expression join multiple tables with select and where clause

I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.

    var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
    .Select (m => new 
    {
        UserName = u.UserProfile.UserName,
        RoleName = u.Roles.RoleName
    });

Use string in switch case in java

Just to make concrete emory's answer, the executable code is the following :

  Map<String,Callable<USer>> map = new HashMap<String,Callable<User>>();
  map.put( "test" , new Callable<User> () { public User call (){ return fillUser("test" ); }} ) ;
  map.put( "admin" , new Callable<Utente> () { public Utente call (){  return fillUser("admin" ); }} ) ;

where user is a POJO, and then

  User user = map.get(USERNAME).call();

finally the called method is somewhere :

 private User fillUser(String x){        
        User user = new User();
        // set something in User
        return user;
}

Concatenating strings in Razor

You can give like this....

<a href="@(IsProduction.IsProductionUrl)Index/LogOut">

What does servletcontext.getRealPath("/") mean and when should I use it

There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?

Can I use library that used android support with Androidx projects.

I had a problem like this before, it was the gradle.properties file doesn't exist, only the gradle.properties.txt , so i went to my project folder and i copied & pasted the gradle.properties.txt file but without .txt extension then it finally worked.

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

Server unable to read htaccess file, denying access to be safe

I had the same problem on a rackspeed server after changing the php version in the cpanel. Turned out it also changed the permissions of the folder... I set the permission of the folder to 755 with

chmod 755 folder_name

How to get a property value based on the name

In addition other guys answer, its Easy to get property value of any object by use Extension method like:

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
        }

    }

Usage is:

Car foo = new Car();
var balbal = foo.GetPropertyValue("Make");

When does a cookie with expiration time 'At end of session' expire?

Cookies that 'expire at end of the session' expire unpredictably from the user's perspective!

On iOS with Safari they expire whenever you switch apps!

On Android with Chrome they don't expire when you close the browser.

On Windows desktop running Chrome they expire when you close the browser. That's not when you close your website's tab; its when you close all tabs. Nor do they expire if there are any other browser windows open. If users run web apps as windows they might not even know they are browser windows. So your cookie's life depends on what the user is doing with some apparently unrelated app.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

Well I am not sure what actual cause is but I have done this way for the same error. I have comment out this annotation for the servelet and its working.

//@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {

Dont know that could be proper solution of not. but this worked and another thing that can be test is add servlet jar into class path. That might work.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How do I specify the platform for MSBuild?

In MSBuild or Teamcity use command line

MSBuild yourproject.sln /property:Configuration=Release /property:Platform=x64

or use shorter form:

MSBuild yourproject.sln /p:Configuration=Release /p:Platform=x64

However you need to set up platform in your project anyway, see the answer by Julien Hoarau.

Re-ordering columns in pandas dataframe based on column name

print df.sort_index(by='Frequency',ascending=False)

where by is the name of the column,if you want to sort the dataset based on column

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

Integration Services project templates are now available in the latest release of SSDT for Visual Studio 2017.

Note: if you have recently installed SSDT for Visual Studio 2017. You need to remove the Reporting Services and Analysis Services installations before you proceed with installing SSDT.

Jetty: HTTP ERROR: 503/ Service Unavailable

None of these answers worked for me.

I had to remove all deployed java web app:

  • Windows/Show View/Other...
  • Go the the Server folder and select "Servers"
  • Right-click on the J2EE Preview at localhost
  • Click to Add and Remove... Click Remove all

Then run the project on the server

The Error is gone!

You will have to stop the server before deploying another project because it will not be found by the server. Otherwise you will get a 404 error

SQL Server: Importing database from .mdf?

To perform this operation see the next images:

enter image description here

and next step is add *.mdf file,

very important, the .mdf file must be located in C:......\MSSQL12.SQLEXPRESS\MSSQL\DATA

enter image description here

Now remove the log file

enter image description here

Open Cygwin at a specific folder

From the cygwin terminal, run this command:

echo "cd your_path" >> ~/.bashrc

The .bashrc script is run when you open a new bash session. The code above with change to the your_path directory when you open a new cygwin session.

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

Here are some methods that may help others, though they aren't really services as much as they may be described as "methods that may, after some torture of effort or logic, lead to a claim of on-demand access to Mac OS X" (no doubt I should patent that phrase).

Fundamentally, I am inclined to believe that on-demand (per-hour) hosting does not exist, and @Erik has given information for the shortest feasible services, i.e. monthly hosting.


It seems that one may use EC2 itself, but install OS X on the instance through a lot of elbow grease.

  • This article on Lifehacker.com gives instructions for setting up OSX under Virtual Box and depends on hardware virtualization. It seems that the Cluster Compute instances (and Cluster GPU, but ignore these) are the only ones supporting hardware virtualization.
  • This article gives instructions for transferring a VirtualBox image to EC2.

Where this gets tricky is I'm not sure if this will work for a cluster compute instance. In fact, I think this is likely to be a royal pain. A similar approach may work for Rackspace or other cloud services.

I found only this site claiming on-demand Mac hosting, with a Mac Mini. It doesn't look particularly accurate: it offers free on-demand access to a Mini if one pays for a month of bandwidth. That's like free bandwidth if one rents a Mini for a month. That's not really how "on-demand" works.


Update 1: In the end, it seems that nobody offers a comparable service. An outfit called Media Temple claims they will offer the first virtual servers using Parallels, OS X Leopard, and some other stuff (in other words, I wonder if there is some caveat that makes them unique, but, without that caveat, someone else may have a usable offering).

After this search, I think that a counterpart to EC2 does not exist for the OS X operating system. It is extraordinarily unlikely that one would exist, offer a scalable solution, and yet be very difficult to find. One could set it up internally, but there's no reseller/vendor offering on-demand, hourly virtual servers. This may be disappointing, but not surprising - apparently iCloud is running on Amazon and Microsoft systems.

mysql stored-procedure: out parameter

I know this is an old thread, but if anyone is looking for an answer of why their procedures doesn't work in the workbench and think the only result is "Query canceled" or anything like that without clues:

the output with errors or problems is hiddenl. I do not know why, I do understand it's annoying, but it is there. just move your cursor above the line above the message, it will turn in an double arrow (up and down) you can then click and drag that line up, then you will see a console with the message you missed!

Oracle SQL update based on subquery between two tables

There are two ways to do what you are trying

One is a Multi-column Correlated Update

UPDATE PRODUCTION a
SET (name, count) = (
  SELECT name, count
  FROM STAGING b
  WHERE a.ID = b.ID);

DEMO

You can use merge

MERGE INTO PRODUCTION a
USING ( select id, name, count 
          from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN 
UPDATE SET  a.name = b.name,
            a.count = b.count

DEMO

Javascript : array.length returns undefined

An easy fix to this question is to add '[' in the start of your json file, and ending it with a ']'. This solved it for me.