Programs & Examples On #Database indexes

An index contains keys built from one or more columns in the table, or view, and pointers that map to the storage location of the specified data.

How does database indexing work?

Just a quick suggestion.. As indexing costs you additional writes and storage space, so if your application requires more insert/update operation, you might want to use tables without indexes, but if it requires more data retrieval operations, you should go for indexed table.

Add item to Listview control

The ListView control uses the Items collection to add items to listview in the control and is able to customize items.

Android WebView style background-color:transparent ignored on android 2.2

If webview is scrollable:

  1. Add this to the Manifest:

    android:hardwareAccelerated="false"
    

OR

  1. Add the following to WebView in the layout:

    android:background="@android:color/transparent"
    android:layerType="software"
    
  2. Add the following to the parents scroll view:

    android:layerType="software"
    

Show just the current branch in Git

I'm using

/etc/bash_completion.d/git

It came with Git and provides a prompt with branch name and argument completion.

Best way to change font colour halfway through paragraph?

You can also simply add the font tag inside the p tag.

CSS sheet:

<style type="text/css">
   p { font:15px Arial; color:white; }
</style>

and in HTML page:

<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. 
    <font color="red"> 
          Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris     nisi ut aliquip ex ea commodo consequat. 
    </font>
Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>

It works for me. But, in case you need modification, see w3schools for more usage :)

Best way to handle list.index(might-not-exist) in python?

I don't know why you should think it is dirty... because of the exception? if you want a oneliner, here it is:

thing_index = thing_list.index(elem) if thing_list.count(elem) else -1

but i would advise against using it; I think Ross Rogers solution is the best, use an object to encapsulate your desiderd behaviour, don't try pushing the language to its limits at the cost of readability.

Making authenticated POST requests with Spring RestTemplate for Android

I was recently dealing with an issue when I was trying to get past authentication while making a REST call from Java, and while the answers in this thread (and other threads) helped, there was still a bit of trial and error involved in getting it working.

What worked for me was encoding credentials in Base64 and adding them as Basic Authorization headers. I then added them as an HttpEntity to restTemplate.postForEntity, which gave me the response I needed.

Here's the class I wrote for this in full (extending RestTemplate):

public class AuthorizedRestTemplate extends RestTemplate{

    private String username;
    private String password;

    public AuthorizedRestTemplate(String username, String password){
        this.username = username;
        this.password = password;
    }

    public String getForObject(String url, Object... urlVariables){
        return authorizedRestCall(this, url, urlVariables);
    }

    private String authorizedRestCall(RestTemplate restTemplate, 
            String url, Object... urlVariables){
        HttpEntity<String> request = getRequest();
        ResponseEntity<String> entity = restTemplate.postForEntity(url, 
                request, String.class, urlVariables);
        return entity.getBody();
    }

    private HttpEntity<String> getRequest(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + getBase64Credentials());
        return new HttpEntity<String>(headers);
    }

    private String getBase64Credentials(){
        String plainCreds = username + ":" + password;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        return new String(base64CredsBytes);
    }
}

Print to the same line and not a new line?

It's called the carriage return, or \r

Use

print i/len(some_list)*100," percent complete         \r",

The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)

Also, don't forget to terminate with a print "" to get at least a finalizing newline!

Opening a folder in explorer and selecting a file

Using Process.Start on explorer.exe with the /select argument oddly only works for paths less than 120 characters long.

I had to use a native windows method to get it to work in all cases:

[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);

[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);

public static void OpenFolderAndSelectItem(string folderPath, string file)
{
    IntPtr nativeFolder;
    uint psfgaoOut;
    SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);

    if (nativeFolder == IntPtr.Zero)
    {
        // Log error, can't find folder
        return;
    }

    IntPtr nativeFile;
    SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);

    IntPtr[] fileArray;
    if (nativeFile == IntPtr.Zero)
    {
        // Open the folder without the file selected if we can't find the file
        fileArray = new IntPtr[0];
    }
    else
    {
        fileArray = new IntPtr[] { nativeFile };
    }

    SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);

    Marshal.FreeCoTaskMem(nativeFolder);
    if (nativeFile != IntPtr.Zero)
    {
        Marshal.FreeCoTaskMem(nativeFile);
    }
}

How to add Google Maps Autocomplete search box?

So I've been playing around with this and it seems you need both places and js maps api activated. Then use the following:

HTML:

<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">

JS:

<script>
function initMap() {
  var input = document.getElementById('searchTextField');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    document.getElementById("address").value = JSON.stringify(place.address_components);
  });
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>

How to check if a service is running via batch file and start it, if it is not running?

Language independent version.

@Echo Off
Set ServiceName=Jenkins


SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
    echo %ServiceName% not running 
    echo Start %ServiceName%

    Net start "%ServiceName%">nul||(
        Echo "%ServiceName%" wont start 
        exit /b 1
    )
    echo "%ServiceName%" started
    exit /b 0
)||(
    echo "%ServiceName%" working
    exit /b 0
)

Regular expression for checking if capital letters are found consecutively in a string?

If you want to get all Employee name in mysql which having at least one uppercase letter than apply this query.

SELECT * FROM registration WHERE `name` REGEXP BINARY '[A-Z]';

How do operator.itemgetter() and sort() work?

#sorting first by age then profession,you can change it in function "fun".
a = []

def fun(v):
    return (v[1],v[2])

# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])

a.sort(key=fun)


print a

How do I export html table data as .csv file?

I've briefly covered a simple way to do this with Google Spreadsheets (importHTML) and in Python (Pandas read_html and to_csv) as well as an example Python script in my SO answer here: https://stackoverflow.com/a/28083469/1588795.

Getting json body in aws Lambda via API gateway

You may have forgotten to define the Content-Type header. For example:

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ items }),
  }

Postgres user does not exist?

The solution is simple:
log in as root
and after:

su - postgres

psql

SQL Query to add a new column after an existing column in SQL Server 2005

First add the new column to the old table through SSMStudio. Go to the database >> table >> columns. Right click on columns and choose new column. Follow the wizard. Then create the new table with the columns ordered as desired as follows:

select * into my_new_table from (
select old_col1, my_new_col, old_col2, old_col3
from my_old_table 
) as A
;

Then rename the tables as desired through SSMStudio. Go to the database >> table >> choose rename.

Disable and enable buttons in C#

In your button1_click function you are using '==' for button2.Enabled == true;

This should be button2.Enabled = true;

What is the idiomatic Go equivalent of C's ternary operator?

As pointed out (and hopefully unsurprisingly), using if+else is indeed the idiomatic way to do conditionals in Go.

In addition to the full blown var+if+else block of code, though, this spelling is also used often:

index := val
if val <= 0 {
    index = -val
}

and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b, you can create a function to hold it:

func min(a, b int) int {
    if a <= b {
        return a
    }
    return b
}

...

value := min(a, b)

The compiler will inline such simple functions, so it's fast, more clear, and shorter.

fs.writeFile in a promise, asynchronous-synchronous stuff

Because fs.writefile is a traditional asynchronous callback - you need to follow the promise spec and return a new promise wrapping it with a resolve and rejection handler like so:

return new Promise(function(resolve, reject) {
    fs.writeFile("<filename.type>", data, '<file-encoding>', function(err) {
        if (err) reject(err);
        else resolve(data);
    });
});

So in your code you would use it like so right after your call to .then():

 .then(function(results) {
    return new Promise(function(resolve, reject) {
            fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
               if (err) reject(err);
               else resolve(data);
            });
    });
  }).then(function(results) {
       console.log("results here: " + results)
  }).catch(function(err) {
       console.log("error here: " + err);
  });

element not interactable exception in selenium web automation

you may also try full xpath, I had a similar issue where I had to click on an element which has a property javascript onclick function. the full xpath method worked and no interactable exception was thrown.

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

How to add an image to a JPanel?

You can subclass JPanel - here is an extract from my ImagePanel, which puts an image in any one of 5 locations, top/left, top/right, middle/middle, bottom/left or bottom/right:

protected void paintComponent(Graphics gc) {
    super.paintComponent(gc);

    Dimension                           cs=getSize();                           // component size

    gc=gc.create();
    gc.clipRect(insets.left,insets.top,(cs.width-insets.left-insets.right),(cs.height-insets.top-insets.bottom));
    if(mmImage!=null) { gc.drawImage(mmImage,(((cs.width-mmSize.width)/2)       +mmHrzShift),(((cs.height-mmSize.height)/2)        +mmVrtShift),null); }
    if(tlImage!=null) { gc.drawImage(tlImage,(insets.left                       +tlHrzShift),(insets.top                           +tlVrtShift),null); }
    if(trImage!=null) { gc.drawImage(trImage,(cs.width-insets.right-trSize.width+trHrzShift),(insets.top                           +trVrtShift),null); }
    if(blImage!=null) { gc.drawImage(blImage,(insets.left                       +blHrzShift),(cs.height-insets.bottom-blSize.height+blVrtShift),null); }
    if(brImage!=null) { gc.drawImage(brImage,(cs.width-insets.right-brSize.width+brHrzShift),(cs.height-insets.bottom-brSize.height+brVrtShift),null); }
    }

How to fill background image of an UIView

The marked answer is fine, but it makes the image stretched. In my case I had a small tile image that I wanted repeat not stretch. And the following code was the best way for me to solve the black background issue:

UIImage *tileImage = [UIImage imageNamed:@"myTileImage"];
UIColor *color = [UIColor colorWithPatternImage:tileImage];
UIView  *backgroundView = [[UIView alloc] initWithFrame:self.view.frame];
[backgroundView setBackgroundColor:color];
//backgroundView.alpha = 0.1; //use this if you want to fade it away.
[self.view addSubview:backgroundView];
[self.view sendSubviewToBack:backgroundView];

URLEncoder not able to translate space character

This class perform application/x-www-form-urlencoded-type encoding rather than percent encoding, therefore replacing with + is a correct behaviour.

From javadoc:

When encoding a String, the following rules apply:

  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same.
  • The special characters ".", "-", "*", and "_" remain the same.
  • The space character " " is converted into a plus sign "+".
  • All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

Invalid http_host header

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart

Connect to sqlplus in a shell script and run SQL scripts

Some of the other answers here inspired me to write a script for automating the mixed sequential execution of SQL tasks using SQLPLUS along with shell commands for a project, a process that was previously manually done. Maybe this (highly sanitized) example will be useful to someone else:

#!/bin/bash
acreds="user_a/supergreatpassword"
bcreds="user_b/anothergreatpassword"
hoststring='fancyoraclehoststring'

runsql () {
  # param 1 is $1
sqlplus -S /nolog << EOF
CONNECT $1@$hoststring;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
$2
exit;
EOF
}

echo "TS::$(date): Starting SCHEM_A.PROC_YOU_NEED()..."
runsql "$acreds" "execute SCHEM_A.PROC_YOU_NEED();"

echo "TS::$(date): Starting superusefuljob..."
/var/scripts/superusefuljob.sh

echo "TS::$(date): Starting SCHEM_B.SECRET_B_PROC()..."
runsql "$bcreds" "execute SCHEM_B.SECRET_B_PROC();"

echo "TS::$(date): DONE"

runsql allows you to pass a credential string as the first argument, and any SQL you need as the second argument. The variables containing the credentials are included for illustration, but for security I actually source them from another file. If you wanted to handle multiple database connections, you could easily modify the function to accept the hoststring as an additional parameter.

How to count duplicate rows in pandas dataframe?

None of the existing answers quite offers a simple solution that returns "the number of rows that are just duplicates and should be cut out". This is a one-size-fits-all solution that does:

# generate a table of those culprit rows which are duplicated:
dups = df.groupby(df.columns.tolist()).size().reset_index().rename(columns={0:'count'})

# sum the final col of that table, and subtract the number of culprits:
dups['count'].sum() - dups.shape[0]

Duplicate and rename Xcode project & associated folders

This answer is the culmination of various other StackOverflow posts and tutorials around the internet brought into one place for my future reference, and to help anyone else who may be facing the same issue. All credit is given for other answers at the end.

Duplicating an Xcode Project

  • In the Finder, duplicate the project folder to the desired location of your new project. Do not rename the .xcodeproj file name or any associated folders at this stage.

  • In Xcode, rename the project. Select your project from the navigator pane (left pane). In the Utilities pane (right pane) rename your project, Accept the changes Xcode proposes.

  • In Xcode, rename the schemes in "Manage Schemes", also rename any targets you may have.

  • If you're not using the default Bundle Identifier which contains the current PRODUCT_NAME at the end (so will update automatically), then change your Bundle Identifier to the new one you will be using for your duplicated project.

Renaming the source folder

So after following the above steps you should have a duplicated and renamed Xcode project that should build and compile successfully, however your source code folder will still be named as it was in the original project. This doesn't cause any compiler issues, but it's not the clearest file structure for people to navigate in SCM, etc. To rename this folder without breaking all your file links, follow these steps:

  • In the Finder, rename the source folder. This will break your project, because Xcode won't automatically detect the changes. All of your xcode file listings will lose their links with the actual files, so will all turn red.

  • In Xcode, click on the virtual folder which you renamed (This will likely be right at the top, just under your actual .xcodeproject) Rename this to match the name in the Finder, this won't fix anything and strictly isn't a required step but it's nice to have the file names matching.

  • In Xcode, Select the folder you just renamed in the navigation pane. Then in the Utilities pane (far right) click the icon that looks like dark grey folder, just underneath the 'Location' drop down menu. From here, navigate to your renamed folder in the finder and click 'Choose'. This will automagically re-associate all your files, and they should no longer appear red within the Xcode navigation pane.

Icon to click

  • In your project / targets build settings, search for the old folder name and manually rename any occurrences you find. Normally there is one for the prefix.pch and one for the info.plist, but there may be more.

  • If you are using any third party libraries (Testflight/Hockeyapp/etc) you will also need to search for 'Library Search Paths' and rename any occurrences of the old file name here too.

  • Repeat this process for any unit test source code folders your project may contain, the process is identical.

This should allow you to duplicate & rename an xcode project and all associated files without having to manually edit any xcode files, and risk messing things up.

Credits

Many thanks is given to Nick Lockwood, and Pauly Glott for providing the separate answers to this problem.

How can I use pointers in Java?

Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null, and the original object will still exist (pending garbage collection).

What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.

If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.

Python: Find in list

Another alternative: you can check if an item is in a list with if item in list:, but this is order O(n). If you are dealing with big lists of items and all you need to know is whether something is a member of your list, you can convert the list to a set first and take advantage of constant time set lookup:

my_set = set(my_list)
if item in my_set:  # much faster on average than using a list
    # do something

Not going to be the correct solution in every case, but for some cases this might give you better performance.

Note that creating the set with set(my_list) is also O(n), so if you only need to do this once then it isn't any faster to do it this way. If you need to repeatedly check membership though, then this will be O(1) for every lookup after that initial set creation.

Git - Won't add files?

I recently experienced this issue on my computer running Windows 7. I am using the git command window interface. The solution was to be very careful about the case sensitivity of the file and directory names when doing the git add. Although git would not complain when the case did not exactly match the case of the Windows file system file and directory names it also would not add the files. There would be nothing to commit. Once I typed the file names with the exactly correct case they would be added and listed under the changes to be committed as I intended.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

Load a HTML page within another HTML page

Why don't you use

_x000D_
_x000D_
function jsredir() {_x000D_
  window.location.href = "https://stackoverflow.com";_x000D_
}
_x000D_
<button onclick="jsredir()">Click Me!</button>
_x000D_
_x000D_
_x000D_

How do I use a custom Serializer with Jackson?

In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                    <property name="serializers">
                        <array>
                            <bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
                        </array>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

was in unexplained way overwritten back to default by something.

This worked for me:

CustomObject.java

@JsonSerialize(using = CustomObjectSerializer.class)
public class CustomObject {

    private Long value;

    public Long getValue() {
        return value;
    }

    public void setValue(Long value) {
        this.value = value;
    }
}

CustomObjectSerializer.java

public class CustomObjectSerializer extends JsonSerializer<CustomObject> {

    @Override
    public void serialize(CustomObject value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeNumberField("y", value.getValue());
        jgen.writeEndObject();
    }

    @Override
    public Class<CustomObject> handledType() {
        return CustomObject.class;
    }
}

No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>) is needed in my solution.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Terminating a Java Program

System.exit() terminates the JVM. Nothing after System.exit() is executed. Return is generally used for exiting a method. If the return type is void, then you could use return; But I don't think is a good practice to do it in the main method. You don't have to do anything for terminate a program, unless infinite loop or some strange other execution flows.

How to get the IP address of the docker host from inside a docker container

This is a minimalistic implementation in Node.js for who is running the host on AWS EC2 instances, using the afore mentioned EC2 Metadata instance

const cp = require('child_process');
const ec2 = function (callback) {
    const URL = 'http://169.254.169.254/latest/meta-data/local-ipv4';
    // we make it silent and timeout to 1 sec
    const args = [URL, '-s', '--max-time', '1'];
    const opts = {};
    cp.execFile('curl', args, opts, (error, stdout) => {
        if (error) return callback(new Error('ec2 ip error'));
        else return callback(null, stdout);
    })
        .on('error', (error) => callback(new Error('ec2 ip error')));
}//ec2

and used as

ec2(function(err, ip) {
        if(err) console.log(err)
        else console.log(ip);
    })

Plot multiple lines in one graph

Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions:

tab<-read.delim(text="
Company 2011 2013
Company1 300 350
Company2 320 430
Company3 310 420
",as.is=TRUE,sep=" ",row.names=1)

tab<-t(tab)

plot(tab[,1],type="b",ylim=c(min(tab),max(tab)),col="red",lty=1,ylab="Value",lwd=2,xlab="Year",xaxt="n")
lines(tab[,2],type="b",col="black",lty=2,lwd=2)
lines(tab[,3],type="b",col="blue",lty=3,lwd=2)
grid()
legend("topleft",legend=colnames(tab),lty=c(1,2,3),col=c("red","black","blue"),bg="white",lwd=2)
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

R multiple lines plot

if statement in ng-click

You can put conditionals inside tags. Try:

ng-class="{true:'active',false:'disable'}[list_status=='show']"

WordPress path url in js script file

    wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
    wp_enqueue_script('custom-js');

    $wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
    wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );

and in custom.js

alert(wnm_custom.template_url);

Vue is not defined

I found two main problems with that implementation. First, when you import the vue.js script you use type="JavaScript" as content-type which is wrong. You should remove this type parameter because by default script tags have text/javascript as default content-type. Or, just replace the type parameter with the correct content-type which is type="text/javascript".

The second problem is that your script is embedded in the same HTML file means that it may be triggered first and probably the vue.js file was not loaded yet. You can fix this using a jQuery snippet $(function(){ /* ... */ }); or adding a javascript function as shown in this example:

_x000D_
_x000D_
// Verifies if the document is ready_x000D_
function ready(f) {_x000D_
  /in/.test(document.readyState) ? setTimeout('ready(' + f + ')', 9) : f();_x000D_
}_x000D_
_x000D_
ready(function() {_x000D_
  var demo = new Vue({_x000D_
    el: '#demo',_x000D_
    data: {_x000D_
      message: 'Hello Vue.js!'_x000D_
    }_x000D_
  })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="demo">_x000D_
  <p>{{message}}</p>_x000D_
  <input v-model="message">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Oracle pl-sql escape character (for a " ' ")

In SQL, you escape a quote by another quote:

SELECT 'Alex''s Tea Factory' FROM DUAL

Android/Eclipse: how can I add an image in the res/drawable folder?

When inserting an image into the drawable folders, another import point in addition to the "no capital letters" rule is that the image name cannot contain dashes or other special characters.

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

How to get char from string by index?

First make sure the required number is a valid index for the string from beginning or end , then you can simply use array subscript notation. use len(s) to get string length

>>> s = "python"
>>> s[3]
'h'
>>> s[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[0]
'p'
>>> s[-1]
'n'
>>> s[-6]
'p'
>>> s[-7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> 

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

Scanner vs. StringTokenizer vs. String.Split

I recently did some experiments about the bad performance of String.split() in highly performance sensitive situations. You may find this useful.

http://eblog.chrononsystems.com/hidden-evils-of-javas-stringsplit-and-stringr

The gist is that String.split() compiles a Regular Expression pattern each time and can thus slow down your program, compared to if you use a precompiled Pattern object and use it directly to operate on a String.

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

How can I pass a parameter in Action?

You're looking for Action<T>, which takes a parameter.

How to hide only the Close (x) button?

We can hide close button on form by setting this.ControlBox=false;

Note that this hides all of those sizing buttons. Not just the X. In some cases that may be fine.

Memory address of an object in C#

There's a better solution if you don't really need the memory address but rather some means of uniquely identifying a managed object:

using System.Runtime.CompilerServices;

public static class Extensions
{
    private static readonly ConditionalWeakTable<object, RefId> _ids = new ConditionalWeakTable<object, RefId>();

    public static Guid GetRefId<T>(this T obj) where T: class
    {
        if (obj == null)
            return default(Guid);

        return _ids.GetOrCreateValue(obj).Id;
    }

    private class RefId
    {
        public Guid Id { get; } = Guid.NewGuid();
    }
}

This is thread safe and uses weak references internally, so you won't have memory leaks.

You can use any key generation means that you like. I'm using Guid.NewGuid() here because it's simple and thread safe.

Update

I went ahead and created a Nuget package Overby.Extensions.Attachments that contains some extension methods for attaching objects to other objects. There's an extension called GetReferenceId() that effectively does what the code in this answer shows.

TCPDF Save file to folder?

Only thing that worked for me:

// save file
$pdf->Output(__DIR__ . '/example_001.pdf', 'F');
exit();

How to save a spark DataFrame as csv on disk?

I had similar issue where i had to save the contents of the dataframe to a csv file of name which i defined. df.write("csv").save("<my-path>") was creating directory than file. So have to come up with the following solutions. Most of the code is taken from the following dataframe-to-csv with little modifications to the logic.

def saveDfToCsv(df: DataFrame, tsvOutput: String, sep: String = ",", header: Boolean = false): Unit = {
    val tmpParquetDir = "Posts.tmp.parquet"

    df.repartition(1).write.
        format("com.databricks.spark.csv").
        option("header", header.toString).
        option("delimiter", sep).
        save(tmpParquetDir)

    val dir = new File(tmpParquetDir)
    val newFileRgex = tmpParquetDir + File.separatorChar + ".part-00000.*.csv"
    val tmpTsfFile = dir.listFiles.filter(_.toPath.toString.matches(newFileRgex))(0).toString
    (new File(tmpTsvFile)).renameTo(new File(tsvOutput))

    dir.listFiles.foreach( f => f.delete )
    dir.delete
    }

How to use BOOLEAN type in SELECT statement

From documentation:

You cannot insert the values TRUE and FALSE into a database column. You cannot select or fetch column values into a BOOLEAN variable. Functions called from a SQL query cannot take any BOOLEAN parameters. Neither can built-in SQL functions such as TO_CHAR; to represent BOOLEAN values in output, you must use IF-THEN or CASE constructs to translate BOOLEANvalues into some other type, such as 0 or 1, 'Y' or 'N', 'true' or 'false', and so on.

You will need to make a wrapper function that takes an SQL datatype and use it instead.

Inserting code in this LaTeX document with indentation

Use listings package.

Simple configuration for LaTeX header (before \begin{document}):

\usepackage{listings}
\usepackage{color}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{frame=tb,
  language=Java,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\small\ttfamily},
  numbers=none,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{blue},
  commentstyle=\color{dkgreen},
  stringstyle=\color{mauve},
  breaklines=true,
  breakatwhitespace=true,
  tabsize=3
}

You can change default language in the middle of document with \lstset{language=Java}.

Example of usage in the document:

\begin{lstlisting}
// Hello.java
import javax.swing.JApplet;
import java.awt.Graphics;

public class Hello extends JApplet {
    public void paintComponent(Graphics g) {
        g.drawString("Hello, world!", 65, 95);
    }    
}
\end{lstlisting}

Here's the result:

Example image

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

In my case I used google play services...I increase library service it solved

implementation 'com.google.android.gms:play-services-auth:16.0.0'

Google play service must be same in library and app modules

Reference

How to correctly iterate through getElementsByClassName

You could always use array methods:

var slides = getElementsByClassName("slide");
Array.prototype.forEach.call(slides, function(slide, index) {
    Distribute(slides.item(index));
});

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

Go to the preview version of tomcat e.g. : tomcat 8.3 and copy catalina.jar file and paste into the existing tomcat which you have facing the issue

MySQL Multiple Where Clause

May be using this query you don't get any result or empty result. You need to use OR instead of AND in your query like below.

$query = mysql_query("SELECT image_id FROM list WHERE (style_id = 24 AND style_value = 'red') OR (style_id = 25 AND style_value = 'big') OR (style_id = 27 AND style_value = 'round');

Try out this query.

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

For Chrome on Android, you can use the -webkit-tap-highlight-color CSS property:

-webkit-tap-highlight-color is a non-standard CSS property that sets the color of the highlight that appears over a link while it's being tapped. The highlighting indicates to the user that their tap is being successfully recognized, and indicates which element they're tapping on.

To remove the highlighting completely, you can set the value to transparent:

-webkit-tap-highlight-color: transparent;

Be aware that this might have consequences on accessibility: see outlinenone.com

$rootScope.$broadcast vs. $scope.$emit

They are not doing the same job: $emit dispatches an event upwards through the scope hierarchy, while $broadcast dispatches an event downwards to all child scopes.

To show error message without alert box in Java Script

First you are trying to write to the innerHTML of the input field. This will not work. You need to have a div or span to write to. Try something like:

First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<div id="fname_error"></div>

Then change your validate function to read

if(myform.fname.value.length==0)
    {
    document.getElementById("fname_error").innerHTML="this is invalid name ";
    }

Second, I'm always hesitant about using onBlur for this kind of thing. It is possible to submit a form without exiting the field (e.g. return key) in which case your validation code will not be executed. I prefer to run the validation from the button that submits the form and then call the submit() from within the function only if the document has passed validation.

How to vertically center a container in Bootstrap?

The Flexible box way

Vertical alignment is now very simple by the use of Flexible box layout. Nowadays, this method is supported in a wide range of web browsers except Internet Explorer 8 & 9. Therefore we'd need to use some hacks/polyfills or different approaches for IE8/9.

In the following I'll show you how to do that in only 3 lines of text (regardless of old flexbox syntax).

Note: it's better to use an additional class instead of altering .jumbotron to achieve the vertical alignment. I'd use vertical-center class name for instance.

Example Here (A Mirror on jsbin).

<div class="jumbotron vertical-center"> <!-- 
                      ^--- Added class  -->
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  min-height: 100%;  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh; /* These two lines are counted as one :-)       */

  display: flex;
  align-items: center;
}

Important notes (Considered in the demo):

  1. A percentage values of height or min-height properties is relative to the height of the parent element, therefore you should specify the height of the parent explicitly.

  2. Vendor prefixed / old flexbox syntax omitted in the posted snippet due to brevity, but exist in the online example.

  3. In some of old web browsers such as Firefox 9 (in which I've tested), the flex container - .vertical-center in this case - won't take the available space inside the parent, therefore we need to specify the width property like: width: 100%.

  4. Also in some of web browsers as mentioned above, the flex item - .container in this case - may not appear at the center horizontally. It seems the applied left/right margin of auto doesn't have any effect on the flex item.
    Therefore we need to align it by box-pack / justify-content.

For further details and/or vertical alignment of columns, you could refer to the topic below:


The traditional way for legacy web browsers

This is the old answer I wrote at the time I answered this question. This method has been discussed here and it's supposed to work in Internet Explorer 8 and 9 as well. I'll explain it in short:

In inline flow, an inline level element can be aligned vertically to the middle by vertical-align: middle declaration. Spec from W3C:

middle
Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

In cases that the parent - .vertical-center element in this case - has an explicit height, by any chance if we could have a child element having the exact same height of the parent, we would be able to move the baseline of the parent to the midpoint of the full-height child and surprisingly make our desired in-flow child - the .container - aligned to the center vertically.

Getting all together

That being said, we could create a full-height element within the .vertical-center by ::before or ::after pseudo elements and also change the default display type of it and the other child, the .container to inline-block.

Then use vertical-align: middle; to align the inline elements vertically.

Here you go:

<div class="jumbotron vertical-center">
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  height:100%;
  width:100%;

  text-align: center;  /* align the inline(-block) elements horizontally */
  font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.vertical-center:before {    /* create a full-height inline block pseudo=element */
  content: " ";
  display: inline-block;
  vertical-align: middle;    /* vertical alignment of the inline element */
  height: 100%;
}

.vertical-center > .container {
  max-width: 100%;

  display: inline-block;
  vertical-align: middle;  /* vertical alignment of the inline element */
                           /* reset the font property */
  font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
}

WORKING DEMO.

Also, to prevent unexpected issues in extra small screens, you can reset the height of the pseudo-element to auto or 0 or change its display type to none if needed so:

@media (max-width: 768px) {
  .vertical-center:before {
    height: auto;
    /* Or */
    display: none;
  }
}

UPDATED DEMO

And one more thing:

If there are footer/header sections around the container, it's better to position that elements properly (relative, absolute? up to you.) and add a higher z-index value (for assurance) to keep them always on the top of the others.

Share Text on Facebook from Android App via ACTION_SEND

So I have a work around, but it assumes you have control over the page you're sharing...

If you format your EXTRA_TEXT like so...

String myText = "Hey!\nThis is a neat pic!";
String extraText = "http://www.example.com/myPicPage.html?extraText=\n\n" + myText;

... then on non-Facebook apps, your text should appear something like this:

http://www.example.com/myPicPage.html?extraText=

Hey!
This is a neat pic!

Now if you update your website such that requests with the extraText query parameter return the contents of extraText in the page's meta data.

<!-- Make sure to sanitize your inputs! e.g. http://xkcd.com/327/ -->
<meta name="title" content="Hey! this is a neat pic!">

Then when Facebook escapes that url to generate the dialog, it'll read the title meta data and embed it into your share dialog.

I realize this is a pretty yuck solution, so take with a grain of salt...

Nginx no-www to www and www to no-www

If you are having trouble getting this working, you may need to add the IP address of your server. For example:

server {
listen XXX.XXX.XXX.XXX:80;
listen XXX.XXX.XXX.XXX:443 ssl;
ssl_certificate /var/www/example.com/web/ssl/example.com.crt;
ssl_certificate_key /var/www/example.com/web/ssl/example.com.key;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}

where XXX.XXX.XXX.XXX is the IP address (obviously).

Note: ssl crt and key location must be defined to properly redirect https requests

Don't forget to restart nginx after making the changes:

service nginx restart

PyCharm import external library

Answer for PyCharm 2016.1 on OSX: (This is an update to the answer by @GeorgeWilliams993's answer above, but I don't have the rep yet to make comments.)

Go to Pycharm menu --> Preferences --> Project: (projectname) --> Project Interpreter

At the top is a popup for "Project Interpreter," and to the right of it is a button with ellipses (...) - click on this button for a different popup and choose "More" (or, as it turns out, click on the main popup and choose "Show All").

This shows a list of interpreters, with one selected. At the bottom of the screen are a set of tools... pick the rightmost one:

Show path for the selected interpreter button

Now you should see all the paths pycharm is searching to find imports, and you can use the "+" button at the bottom to add a new path.

I think the most significant difference from @GeorgeWilliams993's answer is that the gear button has been replaced by a set of ellipses. That threw me off.

How can I disable an <option> in a <select> based on its value in JavaScript?

You can also use this function,

function optionDisable(selectId, optionIndices)
{
    for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
    {
        document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
        document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
        document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
    }
}

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

Readably print out a python dict() sorted by key

I wrote the following function to print dicts, lists, and tuples in a more readable format:

def printplus(obj):
    """
    Pretty-prints the object passed in.

    """
    # Dict
    if isinstance(obj, dict):
        for k, v in sorted(obj.items()):
            print u'{0}: {1}'.format(k, v)

    # List or tuple            
    elif isinstance(obj, list) or isinstance(obj, tuple):
        for x in obj:
            print x

    # Other
    else:
        print obj

Example usage in iPython:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> printplus(dict_example)
a: 3
b: 2
c: 1

>>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
>>> printplus(tuple_example)
(1, 2)
(3, 4)
(5, 6)
(7, 8)

sql query with multiple where statements

You need to consider that GROUP BY happens after the WHERE clause conditions have been evaluated. And the WHERE clause always considers only one row, meaning that in your query, the meta_key conditions will always prevent any records from being selected, since one column cannot have multiple values for one row.

And what about the redundant meta_value checks? If a value is allowed to be both smaller and greater than a given value, then its actual value doesn't matter at all - the check can be omitted.

According to one of your comments you want to check for places less than a certain distance from a given location. To get correct distances, you'd actually have to use some kind of proper distance function (see e.g. this question for details). But this SQL should give you an idea how to start:

SELECT items.* FROM items i, meta_data m1, meta_data m2
    WHERE i.item_id = m1.item_id and i.item_id = m2.item_id
    AND m1.meta_key = 'lat' AND m1.meta_value >= 55 AND m1.meta_value <= 65
    AND m2.meta_key = 'lng' AND m2.meta_value >= 20 AND m2.meta_value <= 30

BackgroundWorker vs background Thread

If it ain't broke - fix it till it is...just kidding :)

But seriously BackgroundWorker is probably very similar to what you already have, had you started with it from the beginning maybe you would have saved some time - but at this point I don't see the need. Unless something isn't working, or you think your current code is hard to understand, then I would stick with what you have.

Spring Data and Native Query with pagination

This worked for me (I am using Postgres) in Groovy:

@RestResource(path="namespaceAndNameAndRawStateContainsMostRecentVersion", rel="namespaceAndNameAndRawStateContainsMostRecentVersion")
    @Query(nativeQuery=true,
            countQuery="""
            SELECT COUNT(1) 
            FROM 
            (
                SELECT
                ROW_NUMBER() OVER (
                    PARTITION BY name, provider_id, state
                    ORDER BY version DESC) version_partition,
                *
                FROM mydb.mytable
                WHERE
                (name ILIKE ('%' || :name || '%') OR (:name = '')) AND
                (namespace ILIKE ('%' || :namespace || '%') OR (:namespace = '')) AND
                (state = :state OR (:state = ''))
            ) t
            WHERE version_partition = 1
            """,
            value="""
            SELECT id, version, state, name, internal_name, namespace, provider_id, config, create_date, update_date 
            FROM 
            (
                SELECT 
                ROW_NUMBER() OVER (
                    PARTITION BY name, provider_id, state
                    ORDER BY version DESC) version_partition,
                *
                FROM mydb.mytable
                WHERE 
                (name ILIKE ('%' || :name || '%') OR (:name = '')) AND
                (namespace ILIKE ('%' || :namespace || '%') OR (:namespace = '')) AND
                (state = :state OR (:state = ''))       
            ) t            
            WHERE version_partition = 1             
            /*#{#pageable}*/
            """)
    public Page<Entity> findByNamespaceContainsAndNameContainsAndRawStateContainsMostRecentVersion(@Param("namespace")String namespace, @Param("name")String name, @Param("state")String state, Pageable pageable)

The key here was to use: /*#{#pageable}*/

It allows me to do sorting and pagination. You can test it by using something like this: http://localhost:8080/api/v1/entities/search/namespaceAndNameAndRawStateContainsMostRecentVersion?namespace=&name=&state=published&page=0&size=3&sort=name,desc

Watch out for this issue: Spring Pageable does not translate @Column name

Differences between dependencyManagement and dependencies in Maven

In the parent POM, the main difference between the <dependencies> and <dependencyManagement> is this:

Artifacts specified in the <dependencies> section will ALWAYS be included as a dependency of the child module(s).

Artifacts specified in the <dependencyManagement> section will only be included in the child module if they were also specified in the section of the child module itself. Why is it good you ask? because you specify the version and/or scope in the parent, and you can leave them out when specifying the dependencies in the child POM. This can help you use unified versions for dependencies for child modules, without specifying the version in each child module.

Why must wait() always be in synchronized block

What is the potential damage if it was possible to invoke wait() outside a synchronized block, retaining it's semantics - suspending the caller thread?

Let's illustrate what issues we would run into if wait() could be called outside of a synchronized block with a concrete example.

Suppose we were to implement a blocking queue (I know, there is already one in the API :)

A first attempt (without synchronization) could look something along the lines below

class BlockingQueue {
    Queue<String> buffer = new LinkedList<String>();

    public void give(String data) {
        buffer.add(data);
        notify();                   // Since someone may be waiting in take!
    }

    public String take() throws InterruptedException {
        while (buffer.isEmpty())    // don't use "if" due to spurious wakeups.
            wait();
        return buffer.remove();
    }
}

This is what could potentially happen:

  1. A consumer thread calls take() and sees that the buffer.isEmpty().

  2. Before the consumer thread goes on to call wait(), a producer thread comes along and invokes a full give(), that is, buffer.add(data); notify();

  3. The consumer thread will now call wait() (and miss the notify() that was just called).

  4. If unlucky, the producer thread won't produce more give() as a result of the fact that the consumer thread never wakes up, and we have a dead-lock.

Once you understand the issue, the solution is obvious: Use synchronized to make sure notify is never called between isEmpty and wait.

Without going into details: This synchronization issue is universal. As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.


A paragraph from the link posted by @Willie summarizes it quite well:

You need an absolute guarantee that the waiter and the notifier agree about the state of the predicate. The waiter checks the state of the predicate at some point slightly BEFORE it goes to sleep, but it depends for correctness on the predicate being true WHEN it goes to sleep. There's a period of vulnerability between those two events, which can break the program.

The predicate that the producer and consumer need to agree upon is in the above example buffer.isEmpty(). And the agreement is resolved by ensuring that the wait and notify are performed in synchronized blocks.


This post has been rewritten as an article here: Java: Why wait must be called in a synchronized block

Android - Set text to TextView

Why don´t you try to assign the textview contents onStart() rather than onCreate()

How can I get the order ID in WooCommerce?

it worked. Just modified it

global $woocommerce, $post;

$order = new WC_Order($post->ID);

//to escape # from order id 

$order_id = trim(str_replace('#', '', $order->get_order_number()));

Missing visible-** and hidden-** in Bootstrap v4

Update for Bootstrap 5 (2020)

Bootstrap 5 (currently alpha) has a new xxl breakpoint. Therefore display classes have a new tier to support this:

Hidden only on xxl: d-xxl-none
Visible only on xxl: d-none d-xxl-block

Bootstrap 4 (2018)

The hidden-* and visible-* classes no longer exist in Bootstrap 4. If you want to hide an element on specific tiers or breakpoints in Bootstrap 4, use the d-* display classes accordingly.

Remember that extra-small/mobile (formerly xs) is the default (implied) breakpoint, unless overridden by a larger breakpoint. Therefore, the -xs infix no longer exists in Bootstrap 4.

Show/hide for breakpoint and down:

  • hidden-xs-down (hidden-xs) = d-none d-sm-block
  • hidden-sm-down (hidden-sm hidden-xs) = d-none d-md-block
  • hidden-md-down (hidden-md hidden-sm hidden-xs) = d-none d-lg-block
  • hidden-lg-down = d-none d-xl-block
  • hidden-xl-down (n/a 3.x) = d-none (same as hidden)

Show/hide for breakpoint and up:

  • hidden-xs-up = d-none (same as hidden)
  • hidden-sm-up = d-sm-none
  • hidden-md-up = d-md-none
  • hidden-lg-up = d-lg-none
  • hidden-xl-up (n/a 3.x) = d-xl-none

Show/hide only for a single breakpoint:

  • hidden-xs (only) = d-none d-sm-block (same as hidden-xs-down)
  • hidden-sm (only) = d-block d-sm-none d-md-block
  • hidden-md (only) = d-block d-md-none d-lg-block
  • hidden-lg (only) = d-block d-lg-none d-xl-block
  • hidden-xl (n/a 3.x) = d-block d-xl-none
  • visible-xs (only) = d-block d-sm-none
  • visible-sm (only) = d-none d-sm-block d-md-none
  • visible-md (only) = d-none d-md-block d-lg-none
  • visible-lg (only) = d-none d-lg-block d-xl-none
  • visible-xl (n/a 3.x) = d-none d-xl-block

Demo of the responsive display classes in Bootstrap 4

Also, note that d-*-block can be replaced with d-*-inline, d-*-flex, d-*-table-cell, d-*-table etc.. depending on the display type of the element. Read more on the display classes

Is it possible to disable scrolling on a ViewPager

New class ViewPager2 from androidx allows to disable scrolling with method setUserInputEnabled(false)

private val pager: ViewPager2 by bindView(R.id.pager)

override fun onCreate(savedInstanceState: Bundle?) {
    pager.isUserInputEnabled = false
}

How to run html file using node js

You can use built-in nodejs web server.

Add file server.js for example and put following code:

var http = require('http');
var fs = require('fs');

const PORT=8080; 

fs.readFile('./index.html', function (err, html) {

    if (err) throw err;    

    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(PORT);
});

And after start server from console with command node server.js. Your index.html page will be available on URL http://localhost:8080

Python: tf-idf-cosine: to find document similarity

First off, if you want to extract count features and apply TF-IDF normalization and row-wise euclidean normalization you can do it in one operation with TfidfVectorizer:

>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()

>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
    with 1787553 stored elements in Compressed Sparse Row format>

Now to find the cosine distances of one document (e.g. the first in the dataset) and all of the others you just need to compute the dot products of the first vector with all of the others as the tfidf vectors are already row-normalized.

As explained by Chris Clark in comments and here Cosine Similarity does not take into account the magnitude of the vectors. Row-normalised have a magnitude of 1 and so the Linear Kernel is sufficient to calculate the similarity values.

The scipy sparse matrix API is a bit weird (not as flexible as dense N-dimensional numpy arrays). To get the first vector you need to slice the matrix row-wise to get a submatrix with a single row:

>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
    with 89 stored elements in Compressed Sparse Row format>

scikit-learn already provides pairwise metrics (a.k.a. kernels in machine learning parlance) that work for both dense and sparse representations of vector collections. In this case we need a dot product that is also known as the linear kernel:

>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1.        ,  0.04405952,  0.11016969, ...,  0.04433602,
    0.04457106,  0.03293218])

Hence to find the top 5 related documents, we can use argsort and some negative array slicing (most related documents have highest cosine similarity values, hence at the end of the sorted indices array):

>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([    0,   958, 10576,  3277])
>>> cosine_similarities[related_docs_indices]
array([ 1.        ,  0.54967926,  0.32902194,  0.2825788 ])

The first result is a sanity check: we find the query document as the most similar document with a cosine similarity score of 1 which has the following text:

>>> print twenty.data[0]
From: [email protected] (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15

 I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.

Thanks,
- IL
   ---- brought to you by your neighborhood Lerxst ----

The second most similar document is a reply that quotes the original message hence has many common words:

>>> print twenty.data[958]
From: [email protected] (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: [email protected]
Organization: Reed College, Portland, OR
Lines: 26

In article <[email protected]> [email protected] (where's my
thing) writes:
>
>  I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.

Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.

>    ---- brought to you by your neighborhood Lerxst ----

Rush fan?

--
Robert Seymour              [email protected]
Physics and Philosophy, Reed College    (NeXTmail accepted)
Artificial Life Project         Reed College
Reed Solar Energy Project (SolTrain)    Portland, OR

Java best way for string find and replace?

Try this:

public static void main(String[] args) {
    String str = "My name is Milan, people know me as Milan Vasic.";

    Pattern p = Pattern.compile("(Milan)(?! Vasic)");
    Matcher m = p.matcher(str);

    StringBuffer sb = new StringBuffer();

    while(m.find()) {
        m.appendReplacement(sb, "Milan Vasic");
    }

    m.appendTail(sb);
    System.out.println(sb);
}

Run an exe from C# code

Example:

Process process = Process.Start(@"Data\myApp.exe");
int id = process.Id;
Process tempProc = Process.GetProcessById(id);
this.Visible = false;
tempProc.WaitForExit();
this.Visible = true;

'uint32_t' identifier not found error

I had to run project in VS2010 and I could not introduce any modifications in the code. My solution was to install vS2013 and in VS2010 point VC++ Directories->IncludeDirectories to Program Files(x86)\Microsoft Visual Studio 12.0\VC\include. Then my project compiled without any issues.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

Just do select date(timestamp_column) and you would get the only the date part. Sometimes doing select timestamp_column::date may return date 00:00:00 where it doesn't remove the 00:00:00 part. But I have seen date(timestamp_column) to work perfectly in all the cases. Hope this helps.

update listview dynamically with adapter

add and remove methods are easier to use. They update the data in the list and call notifyDataSetChanged in background.

Sample code:

adapter.add("your object");
adapter.remove("your object");

git remove merge commit from history

Do git rebase -i <sha before the branches diverged> this will allow you to remove the merge commit and the log will be one single line as you wanted. You can also delete any commits that you do not want any more. The reason that your rebase wasn't working was that you weren't going back far enough.

WARNING: You are rewriting history doing this. Doing this with changes that have been pushed to a remote repo will cause issues. I recommend only doing this with commits that are local.

How to confirm RedHat Enterprise Linux version?

That's the RHEL release version.

You can see the kernel version by typing uname -r. It'll be 2.6.something.

How can I display the current branch and folder path in terminal?

For Mac Catilina 10.15.5 and later version:

add in your ~/.zshrc file

function parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}

setopt PROMPT_SUBST
export PROMPT='%F{grey}%n%f %F{cyan}%~%f %F{green}$(parse_git_branch)%f %F{normal}$%f '

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

I use std::string::compare wrapped in utility method like below:

static bool startsWith(const string& s, const string& prefix) {
    return s.size() >= prefix.size() && s.compare(0, prefix.size(), prefix) == 0;
}

arranging div one below the other

If you want the two divs to be displayed one above the other, the simplest answer is to remove the float: left;from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.

Alternatively, you could simply add clear:both; to the divs, which will force the floated content to clear previous floats.

C# declare empty string array

The following should work fine.

string[] arr = new string[] {""};

AngularJS : Why ng-bind is better than {{}} in angular?

Visibility:

While your angularjs is bootstrapping, the user might see your placed brackets in the html. This can be handled with ng-cloak. But for me this is a workaround, that I don't need to use, if I use ng-bind.


Performance:

The {{}} is much slower.

This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.


I am currently building a big single page app (~500 bindings per view). Changing from {{}} to strict ng-bind did save us about 20% in every scope.$digest.


Suggestion:

If you use a translation module such as angular-translate, always prefer directives before brackets annotation.

{{'WELCOME'|translate}} => <span ng-translate="WELCOME"></span>

If you need a filter function, better go for a directive, that actually just uses your custom filter. Documentation for $filter service


UPDATE 28.11.2014 (but maybe off the topic):

In Angular 1.3x the bindonce functionality was introduced. Therefore you can bind the value of an expression/attribute once (will be bound when != 'undefined').

This is useful when you don't expect your binding to change.

Usage: Place :: before your binding:

<ul>  
  <li ng-repeat="item in ::items">{{item}}</li>
</ul>  
<a-directive name="::item">
<span data-ng-bind="::value"></span>

Example:

ng-repeat to output some data in the table, with multiple bindings per row. Translation-bindings, filter outputs, which get executed in every scope digest.

What are ABAP and SAP?

I have worked with SAP since 1998. SAP is a type of software called ERP (Enterprise Resource Planning) that large companies use to manage their day to day affairs. On the macro, the software can be split into two categories: Technical and Functional

Let's go Technical first, as it answers the "What is ABAP" part of your question.

Technical

There are two technical "stacks" within the SAP software, the first is the ABAP stack which is inclusive of all the original technology that SAP was. ABAP is the proprietary coding language for SAP to develop RICEFW objects (Reports, Interfaces, Conversions, Extensions, Forms and Workflows) within the ABAP stack.

The ABAP stack is traditionally navigated via Transaction Codes (T-Codes) to take you to different screens within the SAP Environment. From a technical perspective, you will do all of your performance and tuning of the WORK PROCESSES in the SAP system here, as well as configuring all of the system RFCs, building user profiles and also doing the necessary interfacing between the OS (usually Windows or HPUX) and the Oracle Database (currently Enterprise 11g).

The JAVA stack controls the "Netweaver" aspect of SAP which encapsulates SAP's ability to be accessed via the Internet via SAP Portal and it's ability to interface with other SAP and non-SAP legacy systems via Process Integration (PI).

SAP also has extensive capabilities in the Business Intelligence Field (BI) by accessing information stored within the Business Warehouse (BW). Currently, there is a new technology called HANA 1.0 that compresses the time to run reports against these repositories.

There are two primarily technologists that run ALL of these functions, they are called SAP Basis (Netweaver) Administrators and ABAP Developers.

Functional

SAP has specific pre-populated functional packages for different business areas. For example, Exxon runs the "IS Oil & Gas" package while Bank of America runs the "Banking" package, while further still Lockheed Martin runs the "Aerospace & Defense" package. These packages were developed over time by the amalgamation of intelligent functional customizations that could be intelligently ported to the system via inclusion in dot releases.

However, there are some vanilla functional modules that almost all entities run, regardless of their specific industry:

  • HR: Human Resources
  • PM: Project Management
  • FI: Financial
  • CO: Controllers
  • MM: Materials Management
  • SD: Sales and Distribution
  • PP: Production Planning

and finally the biggie:

  • MDM: Master Data Management which encapsulates the data for customer/vendor/material etc.

PHP cURL, extract an XML response

<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}

How to set the From email address for mailx command?

In case you also want to include your real name in the from-field, you can use the following format

mailx -r "[email protected] (My Name)" -s "My Subject" ...

If you happen to have non-ASCII characters in you name, like My AEÆoeøaaå (Æ= C3 86, ø= C3 B8, å= C3 A5), you have to encode them like this:

mailx -r "[email protected] (My =?utf-8?Q?AE=C3=86oe=C3=B8aa=C3=A5?=)" -s "My Subject" ...

Hope this can save someone an hour of hard work/research!

Python: URLError: <urlopen error [Errno 10060]

Answer (Basic is advance!):

Error: 10060 Adding a timeout parameter to request solved the issue for me.

Example 1

import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g, timeout=20)

Example 2

A similar error also occurred while I was making a GET request. Again, passing a timeout parameter solved the 10060 Error.

response = requests.get(param_url, timeout=20)

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

If you use the credential file at ~/.aws/credentials and use the default profile as below:

[default]
aws_access_key_id=<your access key>
aws_secret_access_key=<your secret access key>

You do not need to use BasicAWSCredential or AWSCredentialsProvider. The SDK can pick up the credentials from the default profile, just by initializing the client object with the default constructor. Example below:

AmazonEC2Client ec2Client = new AmazonEC2Client();

In addition sometime you would need to initialize the client with the ClientConfiguration to provide proxy settings etc. Example below.

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("proxyhost");
clientConfiguration.setProxyPort(proxyport);
AmazonEC2Client ec2Client = new AmazonEC2Client(clientConfiguration);

How to make an HTTP request + basic auth in Swift

I am calling the json on login button click

@IBAction func loginClicked(sender : AnyObject){

var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.


var session = NSURLSession.sharedSession()

request.HTTPMethod = "POST"

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
 //   println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")       
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary

println("json2 :\(json2)")

if(err) {
    println(err!.localizedDescription)
}
else {
    var success = json2["success"] as? Int
    println("Succes: \(success)")
}
})

task.resume()

}

Here, I have made a seperate dictionary for the parameters.

var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
     return params
}

Remove scrollbars from textarea

I was able to get rid of my scroll bar on the body of text by removing my max-height attribute of my class.

How do I install Composer on a shared hosting?

SIMPLE SOLUTION (tested on Red Hat):

run command: curl -sS https://getcomposer.org/installer | php

to use it: php composer.phar

SYSTEM WIDE SOLLUTION (tested on Red Hat):

run command: mv composer.phar /usr/local/bin/composer

to use it: composer update

now you can call composer from any directory.

Source: http://www.agix.com.au/install-composer-on-centosredhat/

When should I use semicolons in SQL Server?

I still have a lot to learn about T-SQL, but in working up some code for a transaction (and basing code on examples from stackoverflow and other sites) I found a case where it seems a semicolon is required and if it is missing, the statement does not seem to execute at all and no error is raised. This doesn't seem to be covered in any of the above answers. (This was using MS SQL Server 2012.)

Once I had the transaction working the way I wanted, I decided to put a try-catch around it so if there are any errors it gets rolled back. Only after doing this, the transaction was not committed (SSMS confirms this when trying to close the window with a nice message alerting you to the fact that there is an uncommitted transaction.

So this

COMMIT TRANSACTION 

outside a BEGIN TRY/END TRY block worked fine to commit the transaction, but inside the block it had to be

COMMIT TRANSACTION;

Note there is no error or warning provided and no indication that the transaction is still uncommitted until attempting to close the query tab.

Fortunately this causes such a huge problem that it is immediately obvious that there is a problem. Unfortunately since no error (syntax or otherwise) is reported it was not immediately obvious what the problem was.

Contrary-wise, ROLLBACK TRANSACTION seems to work equally well in the BEGIN CATCH block with or without a semicolon.

There may be some logic to this but it feels arbitrary and Alice-in-Wonderland-ish.

Adding to the classpath on OSX

If you want to make a certain set of JAR files (or .class files) available to every Java application on the machine, then your best bet is to add those files to /Library/Java/Extensions.

Or, if you want to do it for every Java application, but only when your Mac OS X account runs them, then use ~/Library/Java/Extensions instead.

EDIT: If you want to do this only for a particular application, as Thorbjørn asked, then you will need to tell us more about how the application is packaged.

Add back button to action bar

After setting

 actionBar.setHomeButtonEnabled(true);

You have to configure the parent activity in your AndroidManifest.xml

<activity
    android:name="com.example.MainActivity"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat" />
<activity
    android:name="com.example.SecondActivity"
    android:theme="@style/Theme.AppCompat" >
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.MainActivity" />
</activity>

Look here for more information http://developer.android.com/training/implementing-navigation/ancestral.html

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Get data from fs.readFile

you can read file by

var readMyFile = function(path, cb) {
      fs.readFile(path, 'utf8', function(err, content) {
        if (err) return cb(err, null);
        cb(null, content);
      });
    };

Adding on you can write to file,

var createMyFile = (path, data, cb) => {
  fs.writeFile(path, data, function(err) {
    if (err) return console.error(err);
    cb();
  });
};

and even chain it together

var readFileAndConvertToSentence = function(path, callback) {
  readMyFile(path, function(err, content) {
    if (err) {
      callback(err, null);
    } else {
      var sentence = content.split('\n').join(' ');
      callback(null, sentence);
    }
  });
};

R solve:system is exactly singular

Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

Verify External Script Is Loaded

Create the script tag with a specific ID and then check if that ID exists?

Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?

Edit: following feedback that a code example would be useful:

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts       = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    if(scripts.length){
        for(var scriptIndex in scripts) {
            if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
                alreadyLoaded = true;
            }
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    for(var scriptIndex in document.scripts) {
        if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
            alreadyLoaded = true;
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

How to check if String is null

You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:

textBox1.Text = s ?? "Is null";

The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.

More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx

And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015

textBox1.Text = customer?.orders?[0].description ?? "n/a";

This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.

More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

Up, Down, Left and Right arrow keys do not trigger KeyDown event

I had a similar issue when calling the WPF window out of WinForms.

var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.Show();

However, showing window as a dialog, it worked

var wpfwindow = new ScreenBoardWPF.IzbiraProjekti();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.ShowDialog();

Hope this helps.

Removing all empty elements from a hash / YAML?

In Simple one liner for deleting null values in Hash,

rec_hash.each {|key,value| rec_hash.delete(key) if value.blank? } 

What is SOA "in plain english"?

As far as I understand, the basic concept there is that you create small "services" that provide something useful to other systems and avoid building large systems that tend to do everything inside the system.

So you define a protocol which you will use for interaction (say, it might be SOAP web services) and let your "system-that-does-some-business-work" to interact with the small services to achieve your "big goal".

error: strcpy was not declared in this scope

Observations:

  • #include <cstring> should introduce std::strcpy().
  • using namespace std; (as written in medico.h) introduces any identifiers from std:: into the global namespace.

Aside from using namespace std; being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using in a header file (see below!), using namespace does not affect identifiers introduced after the statement.

(using namespace std is written in the header, which is included in medico.cpp, but #include <cstring> comes after that.)

My advice: Put the using namespace std; (if you insist on using it at all) into medico.cpp, after any includes, and use explicit std:: in medico.h.


strcmpi() is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.

(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)


warning: deprecated conversion from string constant to ‘char*’

A "string constant" is when you write a string literal (e.g. "Hello") in your code. Its type is const char[], i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *, i.e. removing the const qualifier, generates the warning you are seeing.


OT clarification: using in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string and a self-written ::string just perfectly in my code, unless I include your medico.h, because then the two classes will clash.

Don't use using in header files.

And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.

Spring MVC: How to return image in @ResponseBody?

Non of the answers worked for me, so I've managed to do it like that:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("your content type here"));
headers.set("Content-Disposition", "attachment; filename=fileName.jpg");
headers.setContentLength(fileContent.length);
return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);

Setting Content-Disposition header I was able to download the file with the @ResponseBody annotation on my method.

How can two strings be concatenated?

Another way:

sprintf("%s you can add other static strings here %s",string1,string2)

It sometimes useful than paste() function. %s denotes the place where the subjective strings will be included.

Note that this will come in handy as you try to build a path:

sprintf("/%s", paste("this", "is", "a", "path", sep="/"))

output

/this/is/a/path

How do I use arrays in C++?

Array creation and initialization

As with any other kind of C++ object, arrays can be stored either directly in named variables (then the size must be a compile-time constant; C++ does not support VLAs), or they can be stored anonymously on the heap and accessed indirectly via pointers (only then can the size be computed at runtime).

Automatic arrays

Automatic arrays (arrays living "on the stack") are created each time the flow of control passes through the definition of a non-static local array variable:

void foo()
{
    int automatic_array[8];
}

Initialization is performed in ascending order. Note that the initial values depend on the element type T:

  • If T is a POD (like int in the above example), no initialization takes place.
  • Otherwise, the default-constructor of T initializes all the elements.
  • If T provides no accessible default-constructor, the program does not compile.

Alternatively, the initial values can be explicitly specified in the array initializer, a comma-separated list surrounded by curly brackets:

    int primes[8] = {2, 3, 5, 7, 11, 13, 17, 19};

Since in this case the number of elements in the array initializer is equal to the size of the array, specifying the size manually is redundant. It can automatically be deduced by the compiler:

    int primes[] = {2, 3, 5, 7, 11, 13, 17, 19};   // size 8 is deduced

It is also possible to specify the size and provide a shorter array initializer:

    int fibonacci[50] = {0, 1, 1};   // 47 trailing zeros are deduced

In that case, the remaining elements are zero-initialized. Note that C++ allows an empty array initializer (all elements are zero-initialized), whereas C89 does not (at least one value is required). Also note that array initializers can only be used to initialize arrays; they cannot later be used in assignments.

Static arrays

Static arrays (arrays living "in the data segment") are local array variables defined with the static keyword and array variables at namespace scope ("global variables"):

int global_static_array[8];

void foo()
{
    static int local_static_array[8];
}

(Note that variables at namespace scope are implicitly static. Adding the static keyword to their definition has a completely different, deprecated meaning.)

Here is how static arrays behave differently from automatic arrays:

  • Static arrays without an array initializer are zero-initialized prior to any further potential initialization.
  • Static POD arrays are initialized exactly once, and the initial values are typically baked into the executable, in which case there is no initialization cost at runtime. This is not always the most space-efficient solution, however, and it is not required by the standard.
  • Static non-POD arrays are initialized the first time the flow of control passes through their definition. In the case of local static arrays, that may never happen if the function is never called.

(None of the above is specific to arrays. These rules apply equally well to other kinds of static objects.)

Array data members

Array data members are created when their owning object is created. Unfortunately, C++03 provides no means to initialize arrays in the member initializer list, so initialization must be faked with assignments:

class Foo
{
    int primes[8];

public:

    Foo()
    {
        primes[0] = 2;
        primes[1] = 3;
        primes[2] = 5;
        // ...
    }
};

Alternatively, you can define an automatic array in the constructor body and copy the elements over:

class Foo
{
    int primes[8];

public:

    Foo()
    {
        int local_array[] = {2, 3, 5, 7, 11, 13, 17, 19};
        std::copy(local_array + 0, local_array + 8, primes + 0);
    }
};

In C++0x, arrays can be initialized in the member initializer list thanks to uniform initialization:

class Foo
{
    int primes[8];

public:

    Foo() : primes { 2, 3, 5, 7, 11, 13, 17, 19 }
    {
    }
};

This is the only solution that works with element types that have no default constructor.

Dynamic arrays

Dynamic arrays have no names, hence the only means of accessing them is via pointers. Because they have no names, I will refer to them as "anonymous arrays" from now on.

In C, anonymous arrays are created via malloc and friends. In C++, anonymous arrays are created using the new T[size] syntax which returns a pointer to the first element of an anonymous array:

std::size_t size = compute_size_at_runtime();
int* p = new int[size];

The following ASCII art depicts the memory layout if the size is computed as 8 at runtime:

             +---+---+---+---+---+---+---+---+
(anonymous)  |   |   |   |   |   |   |   |   |
             +---+---+---+---+---+---+---+---+
               ^
               |
               |
             +-|-+
          p: | | |                               int*
             +---+

Obviously, anonymous arrays require more memory than named arrays due to the extra pointer that must be stored separately. (There is also some additional overhead on the free store.)

Note that there is no array-to-pointer decay going on here. Although evaluating new int[size] does in fact create an array of integers, the result of the expression new int[size] is already a pointer to a single integer (the first element), not an array of integers or a pointer to an array of integers of unknown size. That would be impossible, because the static type system requires array sizes to be compile-time constants. (Hence, I did not annotate the anonymous array with static type information in the picture.)

Concerning default values for elements, anonymous arrays behave similar to automatic arrays. Normally, anonymous POD arrays are not initialized, but there is a special syntax that triggers value-initialization:

int* p = new int[some_computed_size]();

(Note the trailing pair of parenthesis right before the semicolon.) Again, C++0x simplifies the rules and allows specifying initial values for anonymous arrays thanks to uniform initialization:

int* p = new int[8] { 2, 3, 5, 7, 11, 13, 17, 19 };

If you are done using an anonymous array, you have to release it back to the system:

delete[] p;

You must release each anonymous array exactly once and then never touch it again afterwards. Not releasing it at all results in a memory leak (or more generally, depending on the element type, a resource leak), and trying to release it multiple times results in undefined behavior. Using the non-array form delete (or free) instead of delete[] to release the array is also undefined behavior.

How to add a browser tab icon (favicon) for a website?

For Chrome to display the page icon (favicon), you need to check your website from a hosting server or you can use local host while developing and testing your website on your PC.

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty("User-Agent", "Mozilla ...") now works just fine and doesn't append java/xx at the end! At least with Java 1.6.30 and newer.

I listened on my machine with netcat(a port listener):

$ nc -l -p 8080

It simply listens on the port, so you see anything which gets requested, like raw http-headers.

And got the following http-headers without setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

And WITH setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

As you can see the user agent was properly set.

Full example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}

Convert string with comma to integer

If someone is looking to sub out more than a comma I'm a fan of:

"1,200".chars.grep(/\d/).join.to_i

dunno about performance but, it is more flexible than a gsub, ie:

"1-200".chars.grep(/\d/).join.to_i

clear form values after submission ajax

Using ajax reset() method you can clear the form after submit

example from your script above:

const form = document.getElementById(cform).reset();

How to redirect stdout to both file and console with scripting?

Based on Brian Burns edited answer, I created a single class that is easier to call:

class Logger(object):

    """
    Class to log output of the command line to a log file

    Usage:
    log = Logger('logfile.log')
    print("inside file")
    log.stop()
    print("outside file")
    log.start()
    print("inside again")
    log.stop()
    """

    def __init__(self, filename):
        self.filename = filename

    class Transcript:
        def __init__(self, filename):
            self.terminal = sys.stdout
            self.log = open(filename, "a")
        def __getattr__(self, attr):
            return getattr(self.terminal, attr)
        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)
        def flush(self):
            pass

    def start(self):
        sys.stdout = self.Transcript(self.filename)

    def stop(self):
        sys.stdout.log.close()
        sys.stdout = sys.stdout.terminal

How do I print out the contents of a vector?

My solution is simple.h, which is part of scc package. All std containers, maps, sets, c-arrays are printable.

DateTime.ToString() format that can be used in a filename or extension?

You can try with

var result = DateTime.Now.ToString("yyyy-MM-d--HH-mm-ss");

Getting all selected checkboxes in an array

On checking add the value for checkbox and on dechecking subtract the value

_x000D_
_x000D_
$('#myDiv').change(function() {_x000D_
  var values = 0.00;_x000D_
  {_x000D_
    $('#myDiv :checked').each(function() {_x000D_
      //if(values.indexOf($(this).val()) === -1){_x000D_
      values=values+parseFloat(($(this).val()));_x000D_
      // }_x000D_
    });_x000D_
    console.log( parseFloat(values));_x000D_
  }_x000D_
});
_x000D_
<div id="myDiv">_x000D_
  <input type="checkbox" name="type" value="4.00" />_x000D_
  <input type="checkbox" name="type" value="3.75" />_x000D_
  <input type="checkbox" name="type" value="1.25" />_x000D_
  <input type="checkbox" name="type" value="5.50" />_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Where is the syntax for TypeScript comments documented?

Future

The TypeScript team, and other TypeScript involved teams, plan to create a standard formal TSDoc specification. The 1.0.0 draft hasn't been finalised yet: https://github.com/Microsoft/tsdoc#where-are-we-on-the-roadmap

enter image description here

Current

TypeScript uses JSDoc. e.g.

/** This is a description of the foo function. */
function foo() {
}

To learn jsdoc : https://jsdoc.app/

Demo

But you don't need to use the type annotation extensions in JSDoc.

You can (and should) still use other jsdoc block tags like @returns etc.

Example

Just an example. Focus on the types (not the content).

JSDoc version (notice types in docs):

/**
 * Returns the sum of a and b
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function sum(a, b) {
    return a + b;
}

TypeScript version (notice the re-location of types):

/**
 * Takes two numbers and returns their sum
 * @param a first input to sum
 * @param b second input to sum
 * @returns sum of a and b
 */
function sum(a: number, b: number): number {
    return a + b;
}

Powershell script does not run via Scheduled Tasks

In my case it was related to a .ps1 referral inside the ps1 script which was not signed (you need to unblock it at the file properties) , also I added as first line:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force

Then it worked

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

Sort a Map<Key, Value> by values

map = your hashmap;

List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(list, new cm());//IMP

HashMap<String, Integer> sorted = new LinkedHashMap<String, Integer>();
for(Map.Entry<String, Integer> en: list){
    sorted.put(en.getKey(),en.getValue());
}

System.out.println(sorted);//sorted hashmap

create new class

class cm implements Comparator<Map.Entry<String, Integer>>{
    @Override
    public int compare(Map.Entry<String, Integer> a, 
                            Map.Entry<String, Integer> b)
    {
        return (a.getValue()).compareTo(b.getValue());
    }
}

C# Numeric Only TextBox Control

TRY THIS CODE

// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;
    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if (e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (nonNumberEntered == true)
    {
       MessageBox.Show("Please enter number only..."); 
       e.Handled = true;
    }
}


Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx

How to get all Errors from ASP.Net MVC modelState?

As I discovered having followed the advice in the answers given so far, you can get exceptions occuring without error messages being set, so to catch all problems you really need to get both the ErrorMessage and the Exception.

String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors)
                                                           .Select( v => v.ErrorMessage + " " + v.Exception));

or as an extension method

public static IEnumerable<String> GetErrors(this ModelStateDictionary modelState)
{
      return modelState.Values.SelectMany(v => v.Errors)
                              .Select( v => v.ErrorMessage + " " + v.Exception).ToList();

}

How can I safely create a nested directory?

The relevant Python documentation suggests the use of the EAFP coding style (Easier to Ask for Forgiveness than Permission). This means that the code

try:
    os.makedirs(path)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise
    else:
        print "\nBE CAREFUL! Directory %s already exists." % path

is better than the alternative

if not os.path.exists(path):
    os.makedirs(path)
else:
    print "\nBE CAREFUL! Directory %s already exists." % path

The documentation suggests this exactly because of the race condition discussed in this question. In addition, as others mention here, there is a performance advantage in querying once instead of twice the OS. Finally, the argument placed forward, potentially, in favour of the second code in some cases --when the developer knows the environment the application is running-- can only be advocated in the special case that the program has set up a private environment for itself (and other instances of the same program).

Even in that case, this is a bad practice and can lead to long useless debugging. For example, the fact we set the permissions for a directory should not leave us with the impression permissions are set appropriately for our purposes. A parent directory could be mounted with other permissions. In general, a program should always work correctly and the programmer should not expect one specific environment.

Alternative to file_get_contents?

Yes, if you have URL wrappers disabled you should use sockets or, even better, the cURL library.

If it's part of your site then refer to it with the file system path, not the web URL. /var/www/..., rather than http://domain.tld/....

How to change the port number for Asp.Net core app?

Go to your program.cs file add UseUrs method to set your url, make sure you don't use a reserved url or port

 public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()

                // params string[] urls
                .UseUrls(urls: "http://localhost:10000")

                .Build();
    }

Updating Python on Mac

Echoing above on not messing with OS X install. Have been faced with a couple of reinstalls thinking I could beat the system. The 3.1 install Scott Griffiths offers above works fine with Yosemite, for any Beta testers out there.. Yosemite has Python 2.7.6 as part of OS install, and typing "python3.1" from terminal launches Python 3.1. Same for Python 3.4 (install here).

Bring a window to the front in WPF

Well, since this is such a hot topic... here is what works for me. I got errors if I didn't do it this way because Activate() will error out on you if you cannot see the window.

Xaml:

<Window .... 
        Topmost="True" 
        .... 
        ContentRendered="mainWindow_ContentRendered"> .... </Window>

Codebehind:

private void mainWindow_ContentRendered(object sender, EventArgs e)
{
    this.Topmost = false;
    this.Activate();
    _UsernameTextBox.Focus();
}

This was the only way for me to get the window to show on top. Then activate it so you can type in the box without having to set focus with the mouse. control.Focus() wont work unless the window is Active();

Format date as dd/MM/yyyy using pipes

If anyone can looking to display date with time in AM or PM in angular 6 then this is for you.

{{date | date: 'dd/MM/yyyy hh:mm a'}}

Output

enter image description here

Pre-defined format options

Examples are given in en-US locale.

'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

Reference Link

How to restore/reset npm configuration to default values?

npm config edit

Opens the config file in an editor. Use the --global flag to edit the global config. now you can delete what ever the registry's you don't want and save file.

npm config list will display the list of available now.

How to Handle Button Click Events in jQuery?

$(document).ready(function(){

     $('your selector').bind("click",function(){
            // your statements;
     });

     // you can use the above or the one shown below

     $('your selector').click(function(e){
         e.preventDefault();
         // your statements;
     });


});

How can I view all historical changes to a file in SVN

There's no built-in command for it, so I usually just do something like this:

#!/bin/bash

# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs.  The first revision of the file is emitted as
# full text since there's not previous version to compare it to.

function history_of_file() {
    url=$1 # current url of file
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {

#       first revision as full text
        echo
        read r
        svn log -r$r $url@HEAD
        svn cat -r$r $url@HEAD
        echo

#       remaining revisions as differences to previous revision
        while read r
        do
            echo
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD
            echo
        done
    }
}

Then, you can call it with:

history_of_file $1

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

I resolved this issue by making some changes in build.gradle file

Changes in root build.gradle are as follows:

subprojects {
   afterEvaluate { 
     project -> if (project.hasProperty("android")) { 
       android { 
        compileSdkVersion 26 
        buildToolsVersion '26.0.1' 
       } 
      }
    } 
}

Changes in build.gradle are as follows:

compileSdkVersion 26 
buildToolsVersion "26.0.1"

and

dependencies {
    compile 'com.android.support:appcompat-v7:26.0.1'
}

Convert HTML Character Back to Text Using Java Standard Library

java.net.URLDecoder deals only with the application/x-www-form-urlencoded MIME format (e.g. "%20" represents space), not with HTML character entities. I don't think there's anything on the Java platform for that. You could write your own utility class to do the conversion, like this one.

Get Today's date in Java at midnight time

If you are able to add external libs to your project. I would recommend that you try out Joda-time. It has a very clever way of working with dates.

http://joda-time.sourceforge.net/

How to concatenate a std::string and an int?

This is the easiest way:

string s = name + std::to_string(age);

builder for HashMap

Underscore-java can build hashmap.

Map<String, Object> value = U.objectBuilder()
        .add("firstName", "John")
        .add("lastName", "Smith")
        .add("age", 25)
        .add("address", U.arrayBuilder()
            .add(U.objectBuilder()
                .add("streetAddress", "21 2nd Street")
                .add("city", "New York")
                .add("state", "NY")
                .add("postalCode", "10021")))
        .add("phoneNumber", U.arrayBuilder()
            .add(U.objectBuilder()
                .add("type", "home")
                .add("number", "212 555-1234"))
            .add(U.objectBuilder()
                .add("type", "fax")
                .add("number", "646 555-4567")))
        .build();
    // {firstName=John, lastName=Smith, age=25, address=[{streetAddress=21 2nd Street,
    // city=New York, state=NY, postalCode=10021}], phoneNumber=[{type=home, number=212 555-1234},
    // {type=fax, number=646 555-4567}]}

Angularjs - simple form submit

I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().

If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

How to get the device's IMEI/ESN programmatically in android?

The method getDeviceId() of TelephonyManager returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones. Return null if device ID is not available.

Java Code

package com.AndroidTelephonyManager;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class AndroidTelephonyManager extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView textDeviceID = (TextView)findViewById(R.id.deviceid);

    //retrieve a reference to an instance of TelephonyManager
    TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

    textDeviceID.setText(getDeviceID(telephonyManager));

}

String getDeviceID(TelephonyManager phonyManager){

 String id = phonyManager.getDeviceId();
 if (id == null){
  id = "not available";
 }

 int phoneType = phonyManager.getPhoneType();
 switch(phoneType){
 case TelephonyManager.PHONE_TYPE_NONE:
  return "NONE: " + id;

 case TelephonyManager.PHONE_TYPE_GSM:
  return "GSM: IMEI=" + id;

 case TelephonyManager.PHONE_TYPE_CDMA:
  return "CDMA: MEID/ESN=" + id;

 /*
  *  for API Level 11 or above
  *  case TelephonyManager.PHONE_TYPE_SIP:
  *   return "SIP";
  */

 default:
  return "UNKNOWN: ID=" + id;
 }

}
}

XML

<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/hello">
<textview android:id="@+id/deviceid" android:layout_height="wrap_content" android:layout_width="fill_parent">
</textview></textview></linearlayout> 

Permission Required READ_PHONE_STATE in manifest file.

How to solve maven 2.6 resource plugin dependency?

This fixed the same issue for me: My eclipse is installed in /usr/local/bin/eclipse

1) Changed permission for eclipse from root to owner: sudo chown -R $USER eclipse

2) Right click on project/Maven right click on Update Maven select Force update maven project

How to convert entire dataframe to numeric while preserving decimals?

> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
     a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
        a         b 
"numeric" "numeric" 

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

Error Code: 2013. Lost connection to MySQL server during query

Go to Workbench Edit ? Preferences ? SQL Editor ? DBMS connections read time out : Up to 3000. The error no longer occurred.

How to allow only numbers in textbox in mvc4 razor

in textbox write this code onkeypress="return isNumberKey(event)" and function for this is just below.

<script type="text/javascript">
function isNumberKey(evt)
{
          var charCode = (evt.which) ? evt.which : event.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
}
</script>

How to install a specific version of package using Composer?

just use php composer.phar require

For example :

php composer.phar require doctrine/mongodb-odm-bundle 3.0

Also available with install.

https://getcomposer.org/doc/03-cli.md#require https://getcomposer.org/doc/03-cli.md#install

Read XML file using javascript

You can do something like this to read your nodes.

Also you can find some explanation in this page http://www.compoc.com/tuts/

<script type="text/javascript">
        var markers = null;
        $(document).ready(function () {
            $.get("File.xml", {}, function (xml){
              $('marker',xml).each(function(i){
                 markers = $(this);
              });
            });
        });
</script>

How to save the output of a console.log(object) to a file?

You can use library l2i (https://github.com/seriyvolk83/logs2indexeddb) to save all you put into console.log and then invoke

l2i.download();

to download a file with logs.

How to convert rdd object to dataframe in spark

Method 1: (Scala)

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext.implicits._
val df_2 = sc.parallelize(Seq((1L, 3.0, "a"), (2L, -1.0, "b"), (3L, 0.0, "c"))).toDF("x", "y", "z")

Method 2: (Scala)

case class temp(val1: String,val3 : Double) 

val rdd = sc.parallelize(Seq(
  Row("foo",  0.5), Row("bar",  0.0)
))
val rows = rdd.map({case Row(val1:String,val3:Double) => temp(val1,val3)}).toDF()
rows.show()

Method 1: (Python)

from pyspark.sql import Row
l = [('Alice',2)]
Person = Row('name','age')
rdd = sc.parallelize(l)
person = rdd.map(lambda r:Person(*r))
df2 = sqlContext.createDataFrame(person)
df2.show()

Method 2: (Python)

from pyspark.sql.types import * 
l = [('Alice',2)]
rdd = sc.parallelize(l)
schema =  StructType([StructField ("name" , StringType(), True) , 
StructField("age" , IntegerType(), True)]) 
df3 = sqlContext.createDataFrame(rdd, schema) 
df3.show()

Extracted the value from the row object and then applied the case class to convert rdd to DF

val temp1 = attrib1.map{case Row ( key: Int ) => s"$key" }
val temp2 = attrib2.map{case Row ( key: Int) => s"$key" }

case class RLT (id: String, attrib_1 : String, attrib_2 : String)
import hiveContext.implicits._

val df = result.map{ s => RLT(s(0),s(1),s(2)) }.toDF

How to count down in for loop?

If you google. "Count down for loop python" you get these, which are pretty accurate.

how to loop down in python list (countdown)
Loop backwards using indices in Python?

I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.

iOS - Ensure execution on main thread

When you're using iOS >= 4

dispatch_async(dispatch_get_main_queue(), ^{
  //Your main thread code goes in here
  NSLog(@"Im on the main thread");       
});

How do you completely remove Ionic and Cordova installation from mac?

You can use following command if you uninstall globally

npm uninstall -g cordova ionic

option g for global

if you want to uninstall from he drive then you can use following command

npm uninstall cordova ionic

Cannot serve WCF services in IIS on Windows 8

Please do the following two steps on IIS 8.0

Add new MIME type & HttpHandler

  1. Extension: .svc, MIME type: application/octet-stream

  2. Request path: *.svc, Type: System.ServiceModel.Activation.HttpHandler, Name: svc-Integrated

How to execute mongo commands through shell scripts?

Put this in a file called test.js:

db.mycollection.findOne()
db.getCollectionNames().forEach(function(collection) {
  print(collection);
});

then run it with mongo myDbName test.js.

how to read certain columns from Excel using Pandas - Python

You can use column indices (letters) like this:

import pandas as pd
import numpy as np
file_loc = "path.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")
print(df)

[Corresponding documentation][1]:

usecolsint, str, list-like, or callable default None

  • If None, then parse all columns.
  • If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.
  • If list of int, then indicates list of column numbers to be parsed.
  • If list of string, then indicates list of column names to be parsed.

    New in version 0.24.0.

  • If callable, then evaluate each column name against it and parse the column if the callable returns True.

Returns a subset of the columns according to behavior above.

New in version 0.24.0.

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

How to make shadow on border-bottom?

The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
  -moz-box-shadow: 0 4px 6px -6px #222;_x000D_
  box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

covered in depth here

how to find 2d array size in c++

#include <bits/stdc++.h>
using namespace std;


int main(int argc, char const *argv[])
{
    int arr[6][5] = {
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5},
        {1,2,3,4,5}
    };
    int rows = sizeof(arr)/sizeof(arr[0]);
    int cols = sizeof(arr[0])/sizeof(arr[0][0]);
    cout<<rows<<" "<<cols<<endl;
    return 0;
}

Output: 6 5

CSS media queries for screen sizes

For all smartphones and large screens use this format of media query

/* Smartphones (portrait and landscape) ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */

@media only screen and (min-width : 321px) {
/* Styles */
}



/* Smartphones (portrait) ----------- */

@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}

/**********
iPad 3
**********/

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* Desktops and laptops ----------- */

@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

Passing variable from Form to Module in VBA

Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.

A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId attribute set to True, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show without creating a new instance of the class.

Step away from this, and treat your form as an object instead - expose Property Get members and abstract away the form's controls - the calling code doesn't care about controls anyway:

Option Explicit
Private cancelling As Boolean

Public Property Get UserId() As String
    UserId = txtUserId.Text
End Property

Public Property Get Password() As String
    Password = txtPassword.Text
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = cancelling
End Property

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    cancelling = True
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        cancelling = True
        Cancel = True
        Me.Hide
    End If
End Sub

Now the calling code can do this (assuming the UserForm was named LoginPrompt):

With New LoginPrompt
    .Show vbModal
    If .IsCancelled Then Exit Sub
    DoSomething .UserId, .Password
End With

Where DoSomething would be some procedure that requires the two string parameters:

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
    'work with the parameter values, regardless of where they came from
End Sub

Get the correct week number of a given date

C# to Powershell port from code above from il_guru:

function GetWeekOfYear([datetime] $inputDate)
{
   $day = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetDayOfWeek($inputDate)
   if (($day -ge [System.DayOfWeek]::Monday) -and ($day -le [System.DayOfWeek]::Wednesday))
   {
      $inputDate = $inputDate.AddDays(3)
   }

   # Return the week of our adjusted day
   $weekofYear = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetWeekOfYear($inputDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday)
   return $weekofYear
}

Convert Object to JSON string

You can use the excellent jquery-Json plugin:

http://code.google.com/p/jquery-json/

Makes it easy to convert to and from Json objects.

OrderBy pipe issue

In the current version of Angular2, orderBy and ArraySort pipes are not supported. You need to write/use some custom pipes for this.

Java ArrayList clear() function

Source code of clear shows the reason why the newly added data gets the first position.

 public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
    }

clear() is faster than removeAll() by the way, first one is O(n) while the latter is O(n_2)

To get specific part of a string in c#

To avoid getting expections at run time , do something like this.

There are chances of having empty string sometimes,

string a = "abc,xyz,wer";
string b=string.Empty;

if(!string.IsNullOrEmpty(a ))
{
  b = a.Split(',')[0];
}

Xcode project not showing list of simulators

I still had my iOS Device, but all my simulators were gone.

I tried every suggested solution I could find on stackoverflow.

Eventually, I deleted the Xcode app and downloaded it again from the App Store. After installation, the simulators were back.

How to create id with AUTO_INCREMENT on Oracle?

Assuming you mean a column like the SQL Server identity column?

In Oracle, you use a SEQUENCE to achieve the same functionality. I'll see if I can find a good link and post it here.

Update: looks like you found it yourself. Here is the link anyway: http://www.techonthenet.com/oracle/sequences.php

How can I make a multipart/form-data POST request using Java?

Use this code to upload images or any other files to the server using post in multipart.

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class SimplePostRequestTest {

    public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");

        try {
            FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
            StringBody id = new StringBody("3");
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("upload_image", bin);
            reqEntity.addPart("id", id);
            reqEntity.addPart("image_title", new StringBody("CoolPic"));

            httppost.setEntity(reqEntity);
            System.out.println("Requesting : " + httppost.getRequestLine());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost, responseHandler);
            System.out.println("responseBody : " + responseBody);

        } catch (ClientProtocolException e) {

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

}

it requires below files to upload.

libraries are httpclient-4.1.2.jar, httpcore-4.1.2.jar, httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and commons-logging-1.1.1.jar to be in classpath.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

You may try to put the right database name in connection url in the configuration file. As I had the same error while run the POJO class file and it has been solved by this.

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

in some scenario this error occurs because the Microsoft .NET Framework 4.0 configuration for ASP .NET has been damaged, which can occur if Microsoft Visual Studio 2012 was installed before Visual Studio 2010 or Microsoft SQL Server 2008.

After trying different things i reached the conclusion, repair you .Net installation by running following command. For more information follow the link.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\SetupCache\v4.5.51209\setup.exe /repair /x86 /x64 /ia64 /norestart

https://msdn.microsoft.com/en-us/library/hh168535(v=nav.80).aspx

python list by value not by reference

In terms of performance my favorite answer would be:

b.extend(a)

Check how the related alternatives compare with each other in terms of performance:

In [1]: import timeit

In [2]: timeit.timeit('b.extend(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[2]: 9.623248100280762

In [3]: timeit.timeit('b = a[:]', setup='b=[];a=range(0,10)', number=100000000)
Out[3]: 10.84756088256836

In [4]: timeit.timeit('b = list(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[4]: 21.46313500404358

In [5]: timeit.timeit('b = [elem for elem in a]', setup='b=[];a=range(0,10)', number=100000000)
Out[5]: 66.99795293807983

In [6]: timeit.timeit('for elem in a: b.append(elem)', setup='b=[];a=range(0,10)', number=100000000)
Out[6]: 67.9775960445404

In [7]: timeit.timeit('b = deepcopy(a)', setup='from copy import deepcopy; b=[];a=range(0,10)', number=100000000)
Out[7]: 1216.1108016967773

Get remote registry value

For remote registry you have to use .NET with powershell 2.0

$w32reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer1)
$keypath = 'SOFTWARE\Veritas\NetBackup\CurrentVersion'
$netbackup = $w32reg.OpenSubKey($keypath)
$NetbackupVersion1 = $netbackup.GetValue('PackageVersion')

How do I use su to execute the rest of the bash script as that user?

Use a script like the following to execute the rest or part of the script under another user:

#!/bin/sh

id

exec sudo -u transmission /bin/sh - << eof

id

eof

How to select an item from a dropdown list using Selenium WebDriver with java?

WebElement selectgender = driver.findElement(By.id("gender"));
selectgender.sendKeys("Male");

Delete with Join in MySQL

Try like below:

DELETE posts.*,projects.* 
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;

How to remove all options from a dropdown using jQuery / JavaScript

function removeElements(){
  $('#models').html('');
}

Nested attributes unpermitted parameters

Seems there is a change in handling of attribute protection and now you must whitelist params in the controller (instead of attr_accessible in the model) because the former optional gem strong_parameters became part of the Rails Core.

This should look something like this:

class PeopleController < ActionController::Base
  def create
    Person.create(person_params)
  end

private
  def person_params
    params.require(:person).permit(:name, :age)
  end
end

So params.require(:model).permit(:fields) would be used

and for nested attributes something like

params.require(:person).permit(:name, :age, pets_attributes: [:id, :name, :category])

Some more details can be found in the Ruby edge API docs and strong_parameters on github or here

Get the Query Executed in Laravel 3/4

You can also listen for query events using this:

DB::listen(function($sql, $bindings, $time)
{
    var_dump($sql);
});

See the information from the docs here under Listening For Query Events

Datatable select with multiple conditions

Dim dr As DataRow()


dr = dt.Select("A="& a & "and B="& b & "and C=" & c,"A",DataViewRowState.CurrentRows)

Where A,B,C are the column names where second parameter is for sort expression

How to use pagination on HTML tables?

There's a easy way to paginate a table using breedjs (jQuery plugin), see the example:

HTML

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Gender</th>
      <th>Age</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people" b-paginate="5">
      <td>{{person.name}}</td>
      <td>{{person.gender}}</td>
      <td>{{person.age}}</td>
      <td>{{person.email}}</td>
    </tr>
  </tbody>
</table>
<ul></ul>

JS

var data={ people: [ {...}, {...}, ...] };

$(function() {
  breed.run({
    scope: 'people',
    input: data,
    runEnd: function(){ //This runEnd is just to mount the page buttons
        for(i=1 ; i<=breed.getPageCount('people') ; i++){
        $('ul').append(
            $('<li>',{
            html: i,
            onclick: "breed.paginate({scope: 'people', page: " + i + "});"
          })
        );
      }
    }
  });
});

Every time you want to change pages, just call:

breed.paginate({scope: 'people', page: pageNumber);

More info.

Working example.

Set width to match constraints in ConstraintLayout

For making your view as match_parent is not possible directly, but we can do it in a little different way, but don't forget to use Left and Right attribute with Start and End, coz if you use RTL support, it will be needed.

    <Button
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>

Difference between <input type='submit' /> and <button type='submit'>text</button>

Not sure where you get your legends from but:

Submit button with <button>

As with:

<button type="submit">(html content)</button>

IE6 will submit all text for this button between the tags, other browsers will only submit the value. Using <button> gives you more layout freedom over the design of the button. In all its intents and purposes, it seemed excellent at first, but various browser quirks make it hard to use at times.

In your example, IE6 will send text to the server, while most other browsers will send nothing. To make it cross-browser compatible, use <button type="submit" value="text">text</button>. Better yet: don't use the value, because if you add HTML it becomes rather tricky what is received on server side. Instead, if you must send an extra value, use a hidden field.

Button with <input>

As with:

<input type="button" />

By default, this does next to nothing. It will not even submit your form. You can only place text on the button and give it a size and a border by means of CSS. Its original (and current) intent was to execute a script without the need to submit the form to the server.

Normal submit button with <input>

As with:

<input type="submit" />

Like the former, but actually submits the surrounding form.

Image submit button with <input>

As with:

<input type="image" />

Like the former (submit), it will also submit a form, but you can use any image. This used to be the preferred way to use images as buttons when a form needed submitting. For more control, <button> is now used. This can also be used for server side image maps but that's a rarity these days. When you use the usemap-attribute and (with or without that attribute), the browser will send the mouse-pointer X/Y coordinates to the server (more precisely, the mouse-pointer location inside the button of the moment you click it). If you just ignore these extras, it is nothing more than a submit button disguised as an image.

There are some subtle differences between browsers, but all will submit the value-attribute, except for the <button> tag as explained above.

How to send a model in jQuery $.ajax() post request to MVC controller method

If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

In our app, we do this with an extension method:

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

On the view, we use it to render the model:

<script type="javascript">
  var model = <%= Model.ToJson() %>
</script>

You can then pass the model variable into your $.ajax call.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim directly as below:

UPDATE *tablename*
   SET *columnname* = trim(*columnname*);

Callback functions in C++

There is also the C way of doing callbacks: function pointers

//Define a type for the callback signature,
//it is not necessary, but makes life easier

//Function pointer called CallbackType that takes a float
//and returns an int
typedef int (*CallbackType)(float);  


void DoWork(CallbackType callback)
{
  float variable = 0.0f;

  //Do calculations

  //Call the callback with the variable, and retrieve the
  //result
  int result = callback(variable);

  //Do something with the result
}

int SomeCallback(float variable)
{
  int result;

  //Interpret variable

  return result;
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWork(&SomeCallback);
}

Now if you want to pass in class methods as callbacks, the declarations to those function pointers have more complex declarations, example:

//Declaration:
typedef int (ClassName::*CallbackType)(float);

//This method performs work using an object instance
void DoWorkObject(CallbackType callback)
{
  //Class instance to invoke it through
  ClassName objectInstance;

  //Invocation
  int result = (objectInstance.*callback)(1.0f);
}

//This method performs work using an object pointer
void DoWorkPointer(CallbackType callback)
{
  //Class pointer to invoke it through
  ClassName * pointerInstance;

  //Invocation
  int result = (pointerInstance->*callback)(1.0f);
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWorkObject(&ClassName::Method);
  DoWorkPointer(&ClassName::Method);
}

Facebook API error 191

in the facebook App Page, goto the basic tab. find "Website with Facebook Login" Option.

you will find Site URL: input there put the full URL ( for example http://Mywebsite.com/MyLogin.aspx ). this is the URL you can use with the call like If the APP ID is 123456789

https://graph.facebook.com/oauth/authorize?client_id=123456789&redirect_uri=http://Mywebsite/MyLogin.aspx&scope=publish_actions

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

Inherit CSS class

i think you can use more than one class in a tag

for example:

<div class="whatever base"></div>
<div class="whatever2 base"></div>

so when you want to chage all div's color you can just change the .base

...i dont know how to inherit in CSS

How to check if a URL exists or returns 404 with Java?

this worked for me:

URL u = new URL ( "http://www.example.com/");
HttpURLConnection huc =  ( HttpURLConnection )  u.openConnection (); 
huc.setRequestMethod ("GET");  //OR  huc.setRequestMethod ("HEAD"); 
huc.connect () ; 
int code = huc.getResponseCode() ;
System.out.println(code);

thanks for the suggestions above.

How do I download the Android SDK without downloading Android Studio?

To download the SDK over command line, the link has changed slightly than previously mentioned:

wget --quiet --output-document=/tmp/sdk-tools-linux.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}.zip

Latest version listed on the downloads page.

Copy Notepad++ text with formatting?

Horrible to look for this failure:

Copy .dll to here:

\Program Files\Notepad++\plugins --> put it here

Restart the notepad++

and now you are able to use the copy commands!!!

How to make a input field readonly with JavaScript?

Try This :

document.getElementById(<element_ID>).readOnly=true;