Programs & Examples On #Flash video

Questions related to creation, transmission, reception and playback of flash video using Adobe Flash technologies, including player.

How to run html file on localhost?

You can try installing one of the following localhost softwares:

  1. xampp
  2. wamp
  3. ammps server
  4. laragon

There are many more such softwares but the best among them are the ones mentioned above. they also allow domain names (for example: example.com)

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Actually, You are blocked by SSMS not the SQL Server.

So the solution are either change setting of SSMS or use a SQL query.

Getting value of HTML text input

Depends on where you want to use the email. If it's on the client side, without sending it to a PHP script, JQuery (or javascript) can do the trick.

I've created a fiddle to explain the same - http://jsfiddle.net/qHcpR/

It has an alert which goes off on load and when you click the textbox itself.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

You either need to import the project as a Gradle project from within Idea. When you add a dependency you need to open the Gradle window and perform a refresh.

Alternatively generate the project files from gradle with this:

build.gradle:

apply plugin: 'idea'

And then run:

$ gradle idea

If you modify the dependencies you will need to rerun the above again.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

How can I search (case-insensitive) in a column using LIKE wildcard?

This is the example of a simple LIKE query:

SELECT * FROM <table> WHERE <key> LIKE '%<searchpattern>%'

Now, case-insensitive using LOWER() func:

SELECT * FROM <table> WHERE LOWER(<key>) LIKE LOWER('%<searchpattern>%')

Extracting Ajax return data in jQuery

You may also use the jQuery context parameter. Link to docs

Selector Context

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function

Therefore you could also have:

success: function(data){
    var oneval = $('#one',data).text();
    var subval = $('#sub',data).text();
}

How to remove a variable from a PHP session array

if (isset($_POST['remove'])) {
    $key=array_search($_GET['name'],$_SESSION['name']);
    if($key!==false)
    unset($_SESSION['name'][$key]);
    $_SESSION["name"] = array_values($_SESSION["name"]);
} 

Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.

Lumen: get URL parameter in a Blade view

Laravel 5.6:

{{ Request::query('parameter') }}

How to deal with SQL column names that look like SQL keywords?

If it had been in PostgreSQL, use double quotes around the name, like:

select "from" from "table";

Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.

Printing Python version in output

Try

python --version 

or

python -V

This will return a current python version in terminal.

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

A simple way of keeping the values of fields in different fragments in an activity

Create the Instances of fragments and add instead of replace and remove

    FragA  fa= new FragA();
    FragB  fb= new FragB();
    FragC  fc= new FragB();
    fragmentManager = getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.fragmnt_container, fa);
    fragmentTransaction.add(R.id.fragmnt_container, fb);
    fragmentTransaction.add(R.id.fragmnt_container, fc);
    fragmentTransaction.show(fa);
    fragmentTransaction.hide(fb);
    fragmentTransaction.hide(fc);
    fragmentTransaction.commit();

Then just show and hide the fragments instead of adding and removing those again

    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.hide(fa);
    fragmentTransaction.show(fb);
    fragmentTransaction.hide(fc);
    fragmentTransaction.commit()

;

How to change the MySQL root account password on CentOS7?

For me work like this: 1. Stop mysql: systemctl stop mysqld

  1. Set the mySQL environment option systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

  2. Start mysql usig the options you just set systemctl start mysqld

  3. Login as root mysql -u root

  4. After login I use FLUSH PRIVILEGES; tell the server to reload the grant tables so that account-management statements work. If i don't do that i receive this error trying to update the password: "Can't find any matching row in the user table"

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

How to change fonts in matplotlib (python)?

I prefer to employ:

from matplotlib import rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('font',**{'family':'serif','serif':['Times']})
rc('text', usetex=True)

Remove empty strings from a list of strings

Instead of if x, I would use if X != '' in order to just eliminate empty strings. Like this:

str_list = [x for x in str_list if x != '']

This will preserve None data type within your list. Also, in case your list has integers and 0 is one among them, it will also be preserved.

For example,

str_list = [None, '', 0, "Hi", '', "Hello"]
[x for x in str_list if x != '']
[None, 0, "Hi", "Hello"]

How to get the index with the key in Python dictionary?

No, there is no straightforward way because Python dictionaries do not have a set ordering.

From the documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

In other words, the 'index' of b depends entirely on what was inserted into and deleted from the mapping before:

>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}

As of Python 2.7, you could use the collections.OrderedDict() type instead, if insertion order is important to your application.

Authentication plugin 'caching_sha2_password' cannot be loaded

I found that

ALTER USER 'username'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'password';

didn't work by itself. I also needed to set

[mysqld]
    default_authentication_plugin=mysql_native_password

in /etc/mysql/mysql.conf.d/mysqld.cnf on Ubuntu 18.04 running PHP 7.0

pandas three-way joining multiple dataframes on columns

Assumed imports:

import pandas as pd

John Galt's answer is basically a reduce operation. If I have more than a handful of dataframes, I'd put them in a list like this (generated via list comprehensions or loops or whatnot):

dfs = [df0, df1, df2, dfN]

Assuming they have some common column, like name in your example, I'd do the following:

df_final = reduce(lambda left,right: pd.merge(left,right,on='name'), dfs)

That way, your code should work with whatever number of dataframes you want to merge.

Edit August 1, 2016: For those using Python 3: reduce has been moved into functools. So to use this function, you'll first need to import that module:

from functools import reduce

Dependency Injection vs Factory Pattern

I had the same question as soon as I read about DI and ended up at this post. So finally this is what I understood but please correct me if am wrong.

"Long ago there were little kingdoms with their own governing bodies controlling and taking decisions based on their own written rules. Later on formed a big government eliminating all these little governing bodies which has one set of rules(constitution) and are implemented through courts"

The little kingdoms' governing bodies are "Factories"

The big government is the "Dependency Injector".

Regex to get the words after matching string

Here's a quick Perl script to get what you need. It needs some whitespace chomping.

#!/bin/perl

$sample = <<END;
Subject:
  Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
  Account Name:       ChamaraKer
  Account Domain:     JIC
  Logon ID:       0x1fffb

Object:
  Object Server:  Security
  Object Type:    File
  Object Name:    D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
  Handle ID:  0x11dc
END

my @sample_lines = split /\n/, $sample;
my $path;

foreach my $line (@sample_lines) {
  ($path) = $line =~ m/Object Name:([^s]+)/g;
  if($path) {
    print $path . "\n";
  }
}

Remove characters from NSString?

You can try this

- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
    while ([str rangeOfString:@"  "].location != NSNotFound) {
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return str;
}

Hope this will help you out.

Mongodb service won't start

I can't upvote/comment yet, but +1 for manually removing the lock file haha.

My C9 workspace crashed on me and triggered an unexpected shutdown. The API advises: https://docs.mongodb.com/manual/tutorial/recover-data-following-unexpected-shutdown/

.. but removing data/mongo.lock worked for me :).

Also, just in case you're getting a connection refusal (which happened to me), running the repair command before removing the lock file could solve your problem (it did mine).

sudo -u mongodb mongod --repair --dbpath /var/lib/mongodb/

What is the difference between a process and a thread?

I've perused almost all answers there, alas, as an undergraduate student taking OS course currently I can't comprehend thoroughly the two concepts. I mean most of guys read from some OS books the differences i.e. threads are able to access to global variables in the transaction unit since they make use of their process' address space. Yet, the newly question arises why there are processes, cognizantly we know already threads are more lightweight vis-à-vis processes. Let's glance at the following example by making use of the image excerpted from one of the prior answers,

We have 3 threads working at once on a word document e.g. Libre Office. The first does spellchecking by underlining if the word is misspelt. The second takes and prints letters from keyboard. And the last does save document in every short times not to lose the document worked at if something goes wrong. In this case, the 3 threads cannot be 3 processes since they share a common memory which is the address space of their process and thus all have access to the document being edited. So, the road is the word document along with two bulldozers which are the threads though one of them is lack in the image.

enter image description here

How can I install Visual Studio Code extensions offline?

All these suggestions are great, but kind of painful to follow because executing the code to construct the URL or constructing that crazy URL by hand is kind of annoying...

So, I threw together a quick web app to make things easier. Just paste the URL of the extension you want and out comes out the download of your extension already properly named: publisher-extension-version.vsix.

Hope someone finds it helpful: http://vscode-offline.herokuapp.com/

Spring RequestMapping for controllers that produce and consume JSON

You shouldn't need to configure the consumes or produces attribute at all. Spring will automatically serve JSON based on the following factors.

  • The accepts header of the request is application/json
  • @ResponseBody annotated method
  • Jackson library on classpath

You should also follow Wim's suggestion and define your controller with the @RestController annotation. This will save you from annotating each request method with @ResponseBody

Another benefit of this approach would be if a client wants XML instead of JSON, they would get it. They would just need to specify xml in the accepts header.

How to combine results of two queries into a single dataset

The problem is that unless your tables are related you can't determine how to join them, so you'd have to arbitrarily join them, resulting in a cartesian product:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
cross join Table2

If you had, for example, the following data:

col1  col2
a     1
b     2

col3  col4
y     98
z     99

You would end up with the following:

col1  col2  col3  col4
a     1     y     98
a     1     z     99
b     2     y     98
b     2     z     99

Is this what you're looking for? If not, and you have some means of relating the tables, then you'd need to include that in joining the two tables together, e.g.:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
inner join Table2
on Table1.JoiningField = Table2.JoiningField

That would pull things together for you into however the data is related, giving you your result.

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

In case a (transitive) dependency still uses the jre variant of the Kotlin library, you can force the use of the jdk variant with the help of a resolution strategy:

configurations.all {
    resolutionStrategy {
        eachDependency { DependencyResolveDetails details ->
            details.requested.with {
                if (group == "org.jetbrains.kotlin" && name.startsWith("kotlin-stdlib-jre")) {
                    details.useTarget(group: group, name: name.replace("jre", "jdk"), version: version)
                    details.because("Force use of 'kotlin-stdlib-jdk' in favor of deprecated 'kotlin-stdlib-jre'.")
                }
            }
        }
    }
}

trying to animate a constraint in swift

SWIFT 4.x :

self.mConstraint.constant = 100.0
UIView.animate(withDuration: 0.3) {
        self.view.layoutIfNeeded()
}

Example with completion:

self.mConstraint.constant = 100
UIView.animate(withDuration: 0.3, animations: {
        self.view.layoutIfNeeded()
    }, completion: {res in
        //Do something
})

How should I log while using multiprocessing in Python?

Below is a class that can be used in Windows environment, requires ActivePython. You can also inherit for other logging handlers (StreamHandler etc.)

class SyncronizedFileHandler(logging.FileHandler):
    MUTEX_NAME = 'logging_mutex'

    def __init__(self , *args , **kwargs):

        self.mutex = win32event.CreateMutex(None , False , self.MUTEX_NAME)
        return super(SyncronizedFileHandler , self ).__init__(*args , **kwargs)

    def emit(self, *args , **kwargs):
        try:
            win32event.WaitForSingleObject(self.mutex , win32event.INFINITE)
            ret = super(SyncronizedFileHandler , self ).emit(*args , **kwargs)
        finally:
            win32event.ReleaseMutex(self.mutex)
        return ret

And here is an example that demonstrates usage:

import logging
import random , time , os , sys , datetime
from string import letters
import win32api , win32event
from multiprocessing import Pool

def f(i):
    time.sleep(random.randint(0,10) * 0.1)
    ch = random.choice(letters)
    logging.info( ch * 30)


def init_logging():
    '''
    initilize the loggers
    '''
    formatter = logging.Formatter("%(levelname)s - %(process)d - %(asctime)s - %(filename)s - %(lineno)d - %(message)s")
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    file_handler = SyncronizedFileHandler(sys.argv[1])
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

#must be called in the parent and in every worker process
init_logging() 

if __name__ == '__main__':
    #multiprocessing stuff
    pool = Pool(processes=10)
    imap_result = pool.imap(f , range(30))
    for i , _ in enumerate(imap_result):
        pass

Call a url from javascript

If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.

You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.

<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
                                             // i'm just showing an example.
echo $contents;
?>

If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.

Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.

How to use log levels in java

the different log levels are helpful for tools, whose can anaylse you log files. Normally a logfile contains lots of information. To avoid an information overload (or here an stackoverflow^^) you can use the log levels for grouping the information.

How to calculate combination and permutation in R?

The Combinations package is not part of the standard CRAN set of packages, but is rather part of a different repository, omegahat. To install it you need to use

install.packages("Combinations", repos = "http://www.omegahat.org/R")

See the documentation at http://www.omegahat.org/Combinations/

How to fix "could not find a base address that matches schema http"... in WCF

The solution is to define a custom binding inside your Web.Config file and set the security mode to "Transport". Then you just need to use the bindingConfiguration property inside your endpoint definition to point to your custom binding.

See here: Scott's Blog: WCF Bindings Needed For HTTPS

nodejs mongodb object id to string

If you're using Mongoose, the only way to be sure to have the id as an hex String seems to be:

object._id ? object._id.toHexString():object.toHexString();

This is because object._id exists only if the object is populated, if not the object is an ObjectId

how to remove "," from a string in javascript

If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.

Here the script that can remove up to 12 commas:

function uncomma(x) {
  var string1 = x;
  for (y = 0; y < 12; y++) {
    string1 = string1.replace(/\,/g, '');
  }
  return string1;
}

Modify that for loop if you need bigger numbers.

How to provide a mysql database connection in single file in nodejs

var mysql = require('mysql');

var pool  = mysql.createPool({
    host     : 'yourip',
    port    : 'yourport',
    user     : 'dbusername',
    password : 'dbpwd',
    database : 'database schema name',
    dateStrings: true,
    multipleStatements: true
});


// TODO - if any pool issues need to try this link for connection management
// https://stackoverflow.com/questions/18496540/node-js-mysql-connection-pooling

module.exports = function(qry, qrytype, msg, callback) {

if(qrytype != 'S') {
    console.log(qry);
}

pool.getConnection(function(err, connection) {
    if(err) {
        if(connection)
            connection.release();
        throw err;
    } 

    // Use the connection
    connection.query(qry, function (err, results, fields) {
        connection.release();

        if(err) {
            callback('E#connection.query-Error occurred.#'+ err.sqlMessage);    
            return;         
        }

        if(qrytype==='S') {
            //for Select statement
            // setTimeout(function() {
                callback(results);      
            // }, 500);
        } else if(qrytype==='N'){
            let resarr = results[results.length-1];
            let newid= '';
            if(resarr.length)               
                newid = resarr[0]['@eid'];
            callback(msg + newid);
        } else if(qrytype==='U'){
            //let ret = 'I#' + entity + ' updated#Updated rows count: ' + results[1].changedRows;
            callback(msg);                      
        } else if(qrytype==='D'){
            //let resarr = results[1].affectedRows;
            callback(msg);
        }
    });

    connection.on('error', function (err) {
        connection.release();
        callback('E#connection.on-Error occurred.#'+ err.sqlMessage);   
        return;         
    });
});

}

Tomcat in Intellij Idea Community Edition

Tomcat (Headless) can be integrated with IntelliJ Idea - Community edition.

Step-by-step instructions are as below:

  1. Add tomcatX-maven-plugin to pom.xml

    <build>
        <plugins>
            <plugin>
                 <groupId>org.apache.tomcat.maven</groupId>
                 <artifactId>tomcat7-maven-plugin</artifactId>
                 <version>2.2</version>
                 <configuration>
                     <path>SampleProject</path>
                 </configuration>
            </plugin>
        </plugins>
    </build>
    
  2. Add new run configuration as below:

    Run >> Edit Configurations >> + >> Maven
    
    Parameters tab ...
    Name :: Tomcat
    Working Directory :: Project Root Directory
    Command Line :: tomcat7:run
    
    Runner tab ...
    VM Options :: <user needed options>
    JRE :: <project needed>
    
  3. Invoke Tomcat in Run/Debug mode directly from IntelliJ Run >> Run/Debug menu

NOTE: Though this is considered a hacking of using using Tomcat integration features of IntelliJ - Enterprise version features, but I would consider this a programmatic way integrating tomcat to the IntelliJ Idea - community edition.

Copy all the lines to clipboard

You should yank the text to the * or + registers:

gg"*yG

Explanation:

  • gg to get the cursor to the first character of the file
  • "*y to start a yank command to the register * from the first line, until...
  • G to go the end of the file

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

It looks like you are passing an NSString parameter where you should be passing an NSData parameter:

NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&jsonError];

How to run a stored procedure in oracle sql developer?

Try to execute the procedure like this,

var c refcursor;
execute pkg_name.get_user('14232', '15', 'TDWL', 'SA', 1, :c);
print c;

Blur or dim background when Android PopupWindow active

I've found a solution for this

Create a custom transparent dialog and inside that dialog open the popup window:

dialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar);
emptyDialog = LayoutInflater.from(context).inflate(R.layout.empty, null);

/* blur background*/
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();  
lp.dimAmount=0.0f;  
dialog.getWindow().setAttributes(lp);  
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); 
dialog.setContentView(emptyDialog);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnShowListener(new OnShowListener()
{
    @Override
    public void onShow(DialogInterface dialogIx)
    {
        mQuickAction.show(emptyDialog); //open the PopupWindow here
    }
});
dialog.show();

xml for the dialog(R.layout.empty):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="match_parent" android:layout_width="match_parent"
     style="@android:style/Theme.Translucent.NoTitleBar" />

now you want to dismiss the dialog when Popup window dismisses. so

mQuickAction.setOnDismissListener(new OnDismissListener()
{
    @Override
    public void onDismiss()
    {
        if(dialog!=null)
        {
            dialog.dismiss(); // dismiss the empty dialog when the PopupWindow closes
            dialog = null;
        }
    }
});

Note: I've used NewQuickAction plugin for creating PopupWindow here. It can also be done on native Popup Windows

Print Pdf in C#

I advice you to try 2Printer command line tool from: http://www.doc2prn.com/

Command line example to print all PDF files from folder "C:\Input" is below. You can simple call it from your C# code.

2Printer.exe -s "C:\Input*.PDF" -prn "Canon MP610 series Printer"

Android Viewpager as Image Slide Gallery

In Jake's ViewPageIndicator he has implemented View pager to display a String array (i.e. ["this","is","a","text"]) which you pass from YourAdapter.java (that extends FragmentPagerAdapter) to the YourFragment.java which returns a View to the viewpager.

In order to display something different, you simply have to change the context type your passing. In this case you want to pass images instead of text, as shown in the sample below:

This is how you setup your Viewpager:

public class PlaceDetailsFragment extends SherlockFragment {
    PlaceSlidesFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;

    public static final String TAG = "detailsFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_place_details,
                container, false);

        mAdapter = new PlaceSlidesFragmentAdapter(getActivity()
                .getSupportFragmentManager());

        mPager = (ViewPager) view.findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);
        ((CirclePageIndicator) mIndicator).setSnap(true);

        mIndicator
                .setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        Toast.makeText(PlaceDetailsFragment.this.getActivity(),
                                "Changed to page " + position,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onPageScrolled(int position,
                            float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                    }
                });
        return view;
    }

}

your_layout.xml

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



    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <com.viewpagerindicator.CirclePageIndicator
        android:id="@+id/indicator"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip" />

</LinearLayout>

YourAdapter.java

public class PlaceSlidesFragmentAdapter extends FragmentPagerAdapter implements
        IconPagerAdapter {

    private int[] Images = new int[] { R.drawable.photo1, R.drawable.photo2,
            R.drawable.photo3, R.drawable.photo4

    };

    protected static final int[] ICONS = new int[] { R.drawable.marker,
            R.drawable.marker, R.drawable.marker, R.drawable.marker };

    private int mCount = Images.length;

    public PlaceSlidesFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return new PlaceSlideFragment(Images[position]);
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public int getIconResId(int index) {
        return ICONS[index % ICONS.length];
    }

    public void setCount(int count) {
        if (count > 0 && count <= 10) {
            mCount = count;
            notifyDataSetChanged();
        }
    }
}

YourFragment.java

// you need to return image instaed of text from here.//

public final class PlaceSlideFragment extends Fragment {
    int imageResourceId;

    public PlaceSlideFragment(int i) {
        imageResourceId = i;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        ImageView image = new ImageView(getActivity());
        image.setImageResource(imageResourceId);

        LinearLayout layout = new LinearLayout(getActivity());
        layout.setLayoutParams(new LayoutParams());

        layout.setGravity(Gravity.CENTER);
        layout.addView(image);

        return layout;
    }
}

You should get a View pager like this from the above code. enter image description here

How to install PHP intl extension in Ubuntu 14.04

For php5 on Ubuntu 14.04

sudo apt-get install php5-intl

For php7 on Ubuntu 16.04

sudo apt-get install php7.0-intl

For php7.2 on Ubuntu 18.04

sudo apt-get install php7.2-intl

Anyway restart your apache after

sudo service apache2 restart

IMPORTANT NOTE: Keep in mind that your php in your terminal/command line has NOTHING todo with the php used by the apache webserver!

If the extension is already installed you should try to enable it. Either in the php.ini file or from command line.

Syntax:

php:

phpenmod [mod name]

apache:

a2enmod [mod name]

Mod of negative number is melting my brain

All of the answers here work great if your divisor is positive, but it's not quite complete. Here is my implementation which always returns on a range of [0, b), such that the sign of the output is the same as the sign of the divisor, allowing for negative divisors as the endpoint for the output range.

PosMod(5, 3) returns 2
PosMod(-5, 3) returns 1
PosMod(5, -3) returns -1
PosMod(-5, -3) returns -2

    /// <summary>
    /// Performs a canonical Modulus operation, where the output is on the range [0, b).
    /// </summary>
    public static real_t PosMod(real_t a, real_t b)
    {
        real_t c = a % b;
        if ((c < 0 && b > 0) || (c > 0 && b < 0)) 
        {
            c += b;
        }
        return c;
    }

(where real_t can be any number type)

How do I compile jrxml to get jasper?

Using Version 5.1.0:

Just click preview and it will create a YourReportName.jasper for you in the same working directory.

jQuery/JavaScript: accessing contents of an iframe

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

Alternative to iFrames with HTML5

If you want to do this and control the server from which the base page or content is being served, you can use Cross Origin Resource Sharing (http://www.w3.org/TR/access-control/) to allow client-side JavaScript to load data into a <div> via XMLHttpRequest():

// I safely ignore IE 6 and 5 (!) users
// because I do not wish to proliferate
// broken software that will hurt other
// users of the internet, which is what
// you're doing when you write anything
// for old version of IE (5/6)
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById('displayDiv').innerHTML = xhr.responseText;
  }
};
xhr.open('GET', 'http://api.google.com/thing?request=data', true);
xhr.send();

Now for the lynchpin of this whole operation, you need to write code for your server that will give clients the Access-Control-Allow-Origin header, specifying which domains you want the client-side code to be able to access via XMLHttpRequest(). The following is an example of PHP code you can include at the top of your page in order to send these headers to clients:

<?php
  header('Access-Control-Allow-Origin: http://api.google.com');
  header('Access-Control-Allow-Origin: http://some.example.com');
?>

HTTP Error 503. The service is unavailable. App pool stops on accessing website

Will this answer Help you?
If you are receiving the following message in the EventViewer

The Module DLL aspnetcorev2.dll failed to load. The data is the error.

Then yes this will solve your problem


To check your event Viewer

  1. press Win+R and type: eventvwr, then press ENTER.
  2. On the left side of Windows Event Viewer click on Windows Logs -> Application.
  3. Now you need to find some ERRORS for source IIS-W3SVC-WP in the middle window.

if you receiving the previous message error then solution is :

Install Microsoft Visual C++ 2015 Redistributable 86x AND 64X (both of them)

Source

How to convert a column of DataTable to a List

Try this:

static void Main(string[] args)
{
    var dt = new DataTable
    {
        Columns = { { "Lastname",typeof(string) }, { "Firstname",typeof(string) } }
    };
    dt.Rows.Add("Lennon", "John");
    dt.Rows.Add("McCartney", "Paul");
    dt.Rows.Add("Harrison", "George");
    dt.Rows.Add("Starr", "Ringo");

    List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();

    foreach(string e in s)
        Console.WriteLine(e);

    Console.ReadLine();
}

Number of days between past date and current date in Google spreadsheet

The following seemed to work well for me:

=DATEDIF(B2, Today(), "D")

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

If your code cannot be updated on some reason, just change your switch ... continue to switch ... break, as in previous versions of PHP it was meant to work this way.

How to copy file from HDFS to the local file system

If your source "file" is split up among multiple files (maybe as the result of map-reduce) that live in the same directory tree, you can copy that to a local file with:

hadoop fs -getmerge /hdfs/source/dir_root/ local/destination

How to move an element down a litte bit in html

You can use the top margin-top and adjust the text or you could also use padding-top both would have similar visual effect in your case but actually both behave a bit differently.

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

You could just do something like this:

SELECT *
FROM foo
WHERE (@param = 0 AND MyColumn IS NULL)
OR (@param = 1 AND MyColumn IS NOT NULL)
OR (@param = 2)

Something like that.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

Scroll back to the top of scrollable div

This is the only way it worked for me, with smooth scrolling transition:

  $('html, body').animate({
    scrollTop: $('#containerDiv').offset().top,
  }, 250);

How to save a list as numpy array in python?

you mean something like this ?

from numpy  import array
a = array( your_list )

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

npm notice created a lockfile as package-lock.json. You should commit this file

Yes you should, As it locks the version of each and every package which you are using in your app and when you run npm install it install the exact same version in your node_modules folder. This is important becasue let say you are using bootstrap 3 in your application and if there is no package-lock.json file in your project then npm install will install bootstrap 4 which is the latest and you whole app ui will break due to version mismatch.

Case insensitive comparison NSString

NSMutableArray *arrSearchData;  
NSArray *data=[arrNearByData objectAtIndex:i];
NSString *strValue=[NSString stringWithFormat:@"%@", [data valueForKey:@"restName"]];
NSRange r = [strValue rangeOfString:key options:NSCaseInsensitiveSearch];

if(r.location != NSNotFound)
{
     [arrSearchData addObject:data];
}

Find the location of a character in string

You could use grep as well:

grep('2', strsplit(string, '')[[1]])
#4 24

how to inherit Constructor from super class to sub class

Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?

It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

get name of a variable or parameter

Alternatively,

1) Without touching System.Reflection namespace,

GETNAME(new { myInput });

public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}

2) The below one can be faster though (from my tests)

GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return typeof(T).GetProperties()[0].Name;
}

You can also extend this for properties of objects (may be with extension methods):

new { myClass.MyProperty1 }.GETNAME();

You can cache property values to improve performance further as property names don't change during runtime.

The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine

Display all dataframe columns in a Jupyter Python Notebook

If you want to show all the rows set like bellow

pd.options.display.max_rows = None

If you want to show all columns set like bellow

pd.options.display.max_columns = None

How to make div same height as parent (displayed as table-cell)

You have to set the height for the parents (container and child) explicitly, here is another work-around (if you don't want to set that height explicitly):

.child {
  width: 30px;
  background-color: red;
  display: table-cell;
  vertical-align: top;
  position:relative;
}

.content {
  position:absolute;
  top:0;
  bottom:0;
  width:100%;
  background-color: blue;
}

Fiddle

annotation to make a private method public only for test classes

dp4j has what you need. Essentially all you have to do is add dp4j to your classpath and whenever a method annotated with @Test (JUnit's annotation) calls a method that's private it will work (dp4j will inject the required reflection at compile-time). You may also use dp4j's @TestPrivates annotation to be more explicit.

If you insist on also annotating your private methods you may use Google's @VisibleForTesting annotation.

What is the difference between & and && in Java?

I think my answer can be more understandable:

There are two differences between & and &&.

If they use as logical AND

& and && can be logical AND, when the & or && left and right expression result all is true, the whole operation result can be true.

when & and && as logical AND, there is a difference:

when use && as logical AND, if the left expression result is false, the right expression will not execute.

Take the example :

String str = null;

if(str!=null && !str.equals("")){  // the right expression will not execute

}

If using &:

String str = null;

if(str!=null & !str.equals("")){  // the right expression will execute, and throw the NullPointerException 

}

An other more example:

int x = 0;
int y = 2;
if(x==0 & ++y>2){
    System.out.print(“y=”+y);  // print is: y=3
}

int x = 0;
int y = 2;
if(x==0 && ++y>2){
    System.out.print(“y=”+y);  // print is: y=2
}

& can be used as bit operator

& can be used as Bitwise AND operator, && can not.

The bitwise AND " &" operator produces 1 if and only if both of the bits in its operands are 1. However, if both of the bits are 0 or both of the bits are different then this operator produces 0. To be more precise bitwise AND " &" operator returns 1 if any of the two bits is 1 and it returns 0 if any of the bits is 0. 

From the wiki page:

http://www.roseindia.net/java/master-java/java-bitwise-and.shtml

How to change value of object which is inside an array using JavaScript or jQuery?

You can create your specific function like the below, then use that everywhere you need.

var each    = (arr, func) => 
                Array.from(
                    (function* (){
                        var i = 0;
                        for(var item of arr)
                            yield func(item, i++);
                    })()
                );

Enjoy..

How to find the statistical mode?

found this on the r mailing list, hope it's helpful. It is also what I was thinking anyways. You'll want to table() the data, sort and then pick the first name. It's hackish but should work.

names(sort(-table(x)))[1]

LIKE vs CONTAINS on SQL Server

I think that CONTAINS took longer and used Merge because you had a dash("-") in your query adventure-works.com.

The dash is a break word so the CONTAINS searched the full-text index for adventure and than it searched for works.com and merged the results.

Java Web Service client basic authentication

Some context additional about basic authentication, it consists in a header which contains the key/value pair:

Authorization: Basic Z2VybWFuOmdlcm1hbg==

where "Authorization" is the headers key, and the headers value has a string ( "Basic" word plus blank space) concatenated to "Z2VybWFuOmdlcm1hbg==", which are the user and password in base 64 joint by double dot

String name = "username";
String password = "secret";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
...
objectXXX.header("Authorization", "Basic " + authStringEnc);

In Maven how to exclude resources from the generated jar?

To exclude any file from a jar / target directory you can use the <excludes> tag in your pom.xml file.

In the next example, all files with .properties extension will not be included:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>*.properties</exclude>
            </excludes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

Why compile Python code?

As already mentioned, you can get a performance increase from having your python code compiled into bytecode. This is usually handled by python itself, for imported scripts only.

Another reason you might want to compile your python code, could be to protect your intellectual property from being copied and/or modified.

You can read more about this in the Python documentation.

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

Dynamically display a CSV file as an HTML table on a web page

Does it work if you escape the quoted commas with \ ?

Name, Age, Sex

"Cantor\, Georg", 163,M

Most delimited formats require that their delimiter be escaped in order to properly parse.


A rough Java example:

import java.util.Iterator;

public class CsvTest {

    public static void main(String[] args) {
        String[] lines = { "Name, Age, Sex", "\"Cantor, Georg\", 163, M" };

        StringBuilder result = new StringBuilder();

        for (String head : iterator(lines[0])) {
            result.append(String.format("<tr>%s</tr>\n", head));
        }

        for (int i=1; i < lines.length; i++) {
            for (String row : iterator(lines[i])) {
                result.append(String.format("<td>%s</td>\n", row));
            }
        }

        System.out.println(String.format("<table>\n%s</table>", result.toString()));
    }

    public static Iterable<String> iterator(final String line) {
        return new Iterable<String>() {
            public Iterator<String> iterator() {
                return new Iterator<String>() {
                    private int position = 0;

                    public boolean hasNext() {
                        return position < line.length();
                    }

                    public String next() {
                        boolean inquote = false;
                        StringBuilder buffer = new StringBuilder();
                        for (; position < line.length(); position++) {
                            char c = line.charAt(position);
                            if (c == '"') {
                                inquote = !inquote;
                            }
                            if (c == ',' && !inquote) {
                                position++;
                                break;
                            } else {
                                buffer.append(c);
                            }
                        }
                        return buffer.toString().trim();
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
}

JSON forEach get Key and Value

Use forEach in combo with Object.entries().

_x000D_
_x000D_
const WALLPAPERS = [{
  WALLPAPER_KEY: 'wallpaper.image',
  WALLPAPER_VALID_KEY: 'wallpaper.image.valid',
}, {
  WALLPAPER_KEY: 'lockscreen.image',
  WALLPAPER_VALID_KEY: 'lockscreen.image.valid',
}];

WALLPAPERS.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    console.log(`${key} - ${value}`);
  }
});
_x000D_
_x000D_
_x000D_

javascript filter array multiple conditions

const data = [{
    realName: 'Sean Bean',
    characterName: 'Eddard “Ned” Stark'
}, {
    realName: 'Kit Harington',
    characterName: 'Jon Snow'
}, {
    realName: 'Peter Dinklage',
    characterName: 'Tyrion Lannister'
}, {
    realName: 'Lena Headey',
    characterName: 'Cersei Lannister'
}, {
    realName: 'Michelle Fairley',
    characterName: 'Catelyn Stark'
}, {
    realName: 'Nikolaj Coster-Waldau',
    characterName: 'Jaime Lannister'
}, {
    realName: 'Maisie Williams',
    characterName: 'Arya Stark'
}];

const filterKeys = ['realName', 'characterName'];


const multiFilter = (data = [], filterKeys = [], value = '') => data.filter((item) => filterKeys.some(key => item[key].toString().toLowerCase().includes(value.toLowerCase()) && item[key]));


let filteredData = multiFilter(data, filterKeys, 'stark');

console.info(filteredData);
/* [{
  "realName": "Sean Bean",
  "characterName": "Eddard “Ned” Stark"
}, {
  "realName": "Michelle Fairley",
  "characterName": "Catelyn Stark"
}, {
  "realName": "Maisie Williams",
  "characterName": "Arya Stark"
}]
 */

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

How can I make a time delay in Python?

asyncio.sleep

Notice in recent Python versions (Python 3.4 or higher) you can use asyncio.sleep. It's related to asynchronous programming and asyncio. Check out next example:

import asyncio
from datetime import datetime

@asyncio.coroutine
def countdown(iteration_name, countdown_sec):
    """
    Just count for some countdown_sec seconds and do nothing else
    """
    while countdown_sec > 0:
       print(f'{iteration_name} iterates: {countdown_sec} seconds')
       yield from asyncio.sleep(1)
       countdown_sec -= 1

loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(countdown('First Count', 2)),
         asyncio.ensure_future(countdown('Second Count', 3))]

start_time = datetime.utcnow()

# Run both methods. How much time will both run...?
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

print(f'total running time: {datetime.utcnow() - start_time}')

We may think it will "sleep" for 2 seconds for first method and then 3 seconds in the second method, a total of 5 seconds running time of this code. But it will print:

total_running_time: 0:00:03.01286

It is recommended to read asyncio official documentation for more details.

How to read a file byte by byte in Python and how to print a bytelist as a binary?

The code you've shown will read 8 bytes. You could use

with open(filename, 'rb') as f:
   while 1:
      byte_s = f.read(1)
      if not byte_s:
         break
      byte = byte_s[0]
      ...

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

What is the proper way to display the full InnerException?

I usually do like this to remove most of the noise:

void LogException(Exception error) {
    Exception realerror = error;
    while (realerror.InnerException != null)
        realerror = realerror.InnerException;

    Console.WriteLine(realerror.ToString())
}    

Edit: I forgot about this answer and is surprised no one pointed out that you can just do

void LogException(Exception error) {
    Console.WriteLine(error.GetBaseException().ToString())
}    

Simple calculations for working with lat/lon and km distance?

Interesting that I didn't see a mention of UTM coordinates.

https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

At least if you want to add km to the same zone, it should be straightforward (in Python : https://pypi.org/project/utm/ )

utm.from_latlon and utm.to_latlon.

How to add a margin to a table row <tr>

add a div to the cells that you would like to add some extra spacing:

<tr class="highlight">
 <td><div>Value1</div></td>
 <td><div>Value2</div></td>
</tr>
tr.highlight td div {
margin-top: 10px;
}

Sql Server equivalent of a COUNTIF aggregate function

Why not like this?

SELECT count(1)
FROM AD_CurrentView
WHERE myColumn=1

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

How to decrypt a password from SQL server?

You cannot decrypt this password again but there is another method named "pwdcompare". Here is a example how to use it with SQL syntax:

USE TEMPDB
GO
declare @hash varbinary (255)
CREATE TABLE tempdb..h (id_num int, hash varbinary (255))
SET @hash = pwdencrypt('123') -- encryption
INSERT INTO tempdb..h (id_num,hash) VALUES (1,@hash)
SET @hash = pwdencrypt('123')
INSERT INTO tempdb..h (id_num,hash) VALUES (2,@hash)
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 2
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
INSERT INTO tempdb..h (id_num,hash) 
VALUES (3,CONVERT(varbinary (255),
0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8))
SELECT TOP 1 @hash = hash FROM tempdb..h WHERE id_num = 3
SELECT pwdcompare ('123', @hash) AS [Success of check] -- Comparison
SELECT * FROM tempdb..h
DROP TABLE tempdb..h
GO

Intercept and override HTTP requests from WebView

You don't mention the API version, but since API 11 there's the method WebViewClient.shouldInterceptRequest

Maybe this could help?

Turning a Comma Separated string into individual rows

Finally, the wait is over with SQL Server 2016. They have introduced the Split string function, STRING_SPLIT:

select OtherID, cs.Value --SplitData
from yourtable
cross apply STRING_SPLIT (Data, ',') cs

All the other methods to split string like XML, Tally table, while loop, etc.. have been blown away by this STRING_SPLIT function.

Here is an excellent article with performance comparison: Performance Surprises and Assumptions: STRING_SPLIT.

For older versions, using tally table here is one split string function(best possible approach)

CREATE FUNCTION [dbo].[DelimitedSplit8K]
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
     -- enough to cover NVARCHAR(4000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;

Referred from Tally OH! An Improved SQL 8K “CSV Splitter” Function

Generate a random number in a certain range in MATLAB

Best solution is randint , but this function produce integer numbers.

You can use rand with rounding function

  r = round(a + (b-a).*rand(m,n));

This produces Real random number between a and b , size of output matrix is m*n

jquery 3.0 url.indexOf error

Better approach may be a polyfill like this

jQuery.fn.load = function(callback){ $(window).on("load", callback) };

With this you can leave the legacy code untouched. If you use webpack be sure to use script-loader.

Safest way to run BAT file from Powershell script

cmd.exe /c '\my-app\my-file.bat'

How to remove provisioning profiles from Xcode

In xcode 6, provisioning profiles are stored under Xcode > Preferences > accounts. Press "View details". On selecting your profile, you will get option to revoke it under settings(gear) icon below.

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

Required attribute on multiple checkboxes with the same name?

var verifyPaymentType = function () {
   //coloque os checkbox dentro de uma div com a class checkbox
  var inputs =  window.jQuery('.checkbox').find('input');
  var first = inputs.first()[0];

  inputs.on('change', function () {
    this.setCustomValidity('');
  });

  first.setCustomValidity( window.jQuery('.checkbox').find('input:checked').length === 0 ? 'Choose one' : '');
}

window.jQuery('#submit').click(verifyPaymentType);

}

Breaking a list into multiple columns in Latex

Using the multicol package and embedding your list in a multicols environment does what you want:

\documentclass{article}
\usepackage{multicol}

\begin{document}
\begin{multicols}{2}
\begin{enumerate}
    \item a
    \item b
    \item c
    \item d
    \item e
    \item f
\end{enumerate}
\end{multicols}
\end{document}

Scale an equation to fit exact page width

The graphicx package provides the command \resizebox{width}{height}{object}:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
 A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}

Select row with most recent date per user

Already solved, but just for the record, another approach would be to create two views...

CREATE TABLE lms_attendance
(id int, user int, time int, io varchar(3));

CREATE VIEW latest_all AS
SELECT la.user, max(la.time) time
FROM lms_attendance la 
GROUP BY la.user;

CREATE VIEW latest_io AS
SELECT la.* 
FROM lms_attendance la
JOIN latest_all lall 
    ON lall.user = la.user
    AND lall.time = la.time;

INSERT INTO lms_attendance 
VALUES
(1, 9, 1370931202, 'out'),
(2, 9, 1370931664, 'out'),
(3, 6, 1370932128, 'out'),
(4, 12, 1370932128, 'out'),
(5, 12, 1370933037, 'in');

SELECT * FROM latest_io;

Click here to see it in action at SQL Fiddle

Returning http 200 OK with error within response body

HTTP Is the Protocol handling the transmission of data over the internet.

If that transmission breaks for whatever reason the HTTP error codes tell you why it can't be sent to you.

The data being transmitted is not handled by HTTP Error codes. Only the method of transmission.

HTTP can't say 'Ok, this answer is gobbledigook, but here it is'. it just says 200 OK.

i.e : I've completed my job of getting it to you, the rest is up to you.

I know this has been answered already but I put it in words I can understand. sorry for any repetition.

How can I merge the columns from two tables into one output?

I guess that what you want to do is an UNION of both tables.

If both tables have the same columns then you can just do

SELECT category_id, col1, col2, col3
  FROM items_a
UNION 
SELECT category_id, col1, col2, col3 
  FROM items_b

Else, you might have to do something like

SELECT category_id, col1, col2, col3
  FROM items_a 
UNION 
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
  FROM items_b

Keeping ASP.NET Session Open / Alive

I use JQuery to perform a simple AJAX call to a dummy HTTP Handler that does nothing but keeping my Session alive:

function setHeartbeat() {
    setTimeout("heartbeat()", 5*60*1000); // every 5 min
}

function heartbeat() {
    $.get(
        "/SessionHeartbeat.ashx",
        null,
        function(data) {
            //$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)
            setHeartbeat();
        },
        "json"
    );
}

Session handler can be as simple as:

public class SessionHeartbeatHttpHandler : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable { get { return false; } }

    public void ProcessRequest(HttpContext context)
    {
        context.Session["Heartbeat"] = DateTime.Now;
    }
}

The key is to add IRequiresSessionState, otherwise Session won't be available (= null). The handler can of course also return a JSON serialized object if some data should be returned to the calling JavaScript.

Made available through web.config:

<httpHandlers>
    <add verb="GET,HEAD" path="SessionHeartbeat.ashx" validate="false" type="SessionHeartbeatHttpHandler"/>
</httpHandlers>

added from balexandre on August 14th, 2012

I liked so much of this example, that I want to improve with the HTML/CSS and the beat part

change this

//$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)

into

beatHeart(2); // just a little "red flash" in the corner :)

and add

// beat the heart 
// 'times' (int): nr of times to beat
function beatHeart(times) {
    var interval = setInterval(function () {
        $(".heartbeat").fadeIn(500, function () {
            $(".heartbeat").fadeOut(500);
        });
    }, 1000); // beat every second

    // after n times, let's clear the interval (adding 100ms of safe gap)
    setTimeout(function () { clearInterval(interval); }, (1000 * times) + 100);
}

HTML and CSS

<div class="heartbeat">&hearts;</div>

/* HEARBEAT */
.heartbeat {
    position: absolute;
    display: none;
    margin: 5px;
    color: red;
    right: 0;
    top: 0;
}

here is a live example for only the beating part: http://jsbin.com/ibagob/1/

Force "git push" to overwrite remote files

Simple steps by using tortoisegit

GIT giving local files commit and pushing into git repository.

Steps :

1) stash changes stash name

2) pull

3) stash pop

4) commit 1 or more files and give commit changes description set author and Date

5) push

Representing null in JSON

There is only one way to represent null; that is with null.

console.log(null === null);   // true
console.log(null === true);   // false
console.log(null === false);  // false
console.log(null === 'null'); // false
console.log(null === "null"); // false
console.log(null === "");     // false
console.log(null === []);     // false
console.log(null === 0);      // false

That is to say; if any of the clients that consume your JSON representation use the === operator; it could be a problem for them.

no value

If you want to convey that you have an object whose attribute myCount has no value:

{ "myCount": null }

no attribute / missing attribute

What if you to convey that you have an object with no attributes:

{}

Client code will try to access myCount and get undefined; it's not there.

empty collection

What if you to convey that you have an object with an attribute myCount that is an empty list:

{ "myCount": [] }

Remove quotes from String in Python

You can replace "quote" characters with an empty string, like this:

>>> a = '"sajdkasjdsak" "asdasdasds"' 
>>> a
'"sajdkasjdsak" "asdasdasds"'
>>> a = a.replace('"', '')
>>> a
'sajdkasjdsak asdasdasds'

In your case, you can do the same for out variable.

android adb turn on wifi via adb

I was in the same situation on a Samsung Mini II. I got around it eventually by holding down the power button until the "power off" menu appeared. From this menu it was possible to enable the network data connection.

Then signing in to my google account using @googlemail.com (rather than @gmail.com) seemed to do the trick. Though the change of address may just have given the phone time to warm up the 3g connection rather than making any real difference.

Changing the row height of a datagridview

You need to set the Height property of the RowTemplate:

var dgv = new DataGridView();
dgv.RowTemplate.Height = 30;

Setting a checkbox as checked with Vue.js

In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

Understanding string reversal via slicing

I think the following makes a bit more sense for print strings in reverse, but maybe that's just me:

for char in reversed( myString ):  
  print( char, end = "" )

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

To pass a pointer to an int it should be void Fun(int* pointer).

Passing a reference to an int would look like this...

void Fun(int& ref) {
   ref = 10;
}

int main() {
   int test = 5;
   cout << test << endl;  // prints 5

   Fun(test);
   cout << test << endl;  // prints 10 because Fun modified the value

   return 1;
}

How can I add shadow to the widget in flutter?

Before you start reinventing the wheel with one of these answers, check out the Material Card widget. It also allows you to define a global style via the app theme directly:

example

How do I pull my project from github?

Git clone is the command you're looking for:

git clone [email protected]:username/repo.git

Update: And this is the official guide: https://help.github.com/articles/fork-a-repo

Take a look at: https://help.github.com/

It has really useful content

Programmatically Creating UILabel

here is how to create UILabel Programmatically..

1) Write this in .h file of your project.

UILabel *label;

2) Write this in .m file of your project.

label=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];//Set frame of label in your viewcontroller.
[label setBackgroundColor:[UIColor lightGrayColor]];//Set background color of label.
[label setText:@"Label"];//Set text in label.
[label setTextColor:[UIColor blackColor]];//Set text color in label.
[label setTextAlignment:NSTextAlignmentCenter];//Set text alignment in label.
[label setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];//Set line adjustment.
[label setLineBreakMode:NSLineBreakByCharWrapping];//Set linebreaking mode..
[label setNumberOfLines:1];//Set number of lines in label.
[label.layer setCornerRadius:25.0];//Set corner radius of label to change the shape.
[label.layer setBorderWidth:2.0f];//Set border width of label.
[label setClipsToBounds:YES];//Set its to YES for Corner radius to work.
[label.layer setBorderColor:[UIColor blackColor].CGColor];//Set Border color.
[self.view addSubview:label];//Add it to the view of your choice. 

How to replace � in a string

for detail

import java.io.UnsupportedEncodingException;

/**
 * File: BOM.java
 * 
 * check if the bom character is present in the given string print the string
 * after skipping the utf-8 bom characters print the string as utf-8 string on a
 * utf-8 console
 */

public class BOM
{
    private final static String BOM_STRING = "Hello World";
    private final static String ISO_ENCODING = "ISO-8859-1";
    private final static String UTF8_ENCODING = "UTF-8";
    private final static int UTF8_BOM_LENGTH = 3;

    public static void main(String[] args) throws UnsupportedEncodingException {
        final byte[] bytes = BOM_STRING.getBytes(ISO_ENCODING);
        if (isUTF8(bytes)) {
            printSkippedBomString(bytes);
            printUTF8String(bytes);
        }
    }

    private static void printSkippedBomString(final byte[] bytes) throws UnsupportedEncodingException {
        int length = bytes.length - UTF8_BOM_LENGTH;
        byte[] barray = new byte[length];
        System.arraycopy(bytes, UTF8_BOM_LENGTH, barray, 0, barray.length);
        System.out.println(new String(barray, ISO_ENCODING));
    }

    private static void printUTF8String(final byte[] bytes) throws UnsupportedEncodingException {
        System.out.println(new String(bytes, UTF8_ENCODING));
    }

    private static boolean isUTF8(byte[] bytes) {
        if ((bytes[0] & 0xFF) == 0xEF && 
            (bytes[1] & 0xFF) == 0xBB && 
            (bytes[2] & 0xFF) == 0xBF) {
            return true;
        }
        return false;
    }
}

Relay access denied on sending mail, Other domain outside of network

If it is giving you relay access denied when you are trying to send an email from outside your network to a domain that your server is not authoritative for then it means your receive connector does not grant you the permissions for sending/relaying. Most likely what you need to do is to authenticate to the server to be granted the permissions for relaying but that does depend upon the configuration of your receive connector. In Exchange 2007/2010/2013 you would need to enable ExchangeUsers permission group as well as an authentication mechanism such as Basic authentication.

Once you're sure your receive connector is configured make sure your email client is configured for authentication as well for the SMTP server. It depends upon your server setup but normally for Exchange you would configure the username by itself, no need for the domain to appended or prefixed to it.

To test things out with authentication via telnet you can go over my post here for directions: https://jefferyland.wordpress.com/2013/05/28/essential-exchange-troubleshooting-send-email-via-telnet/

Gradle DSL method not found: 'runProguard'

enter image description hereIf you are using version 0.14.0 or higher of the gradle plugin, you should replace "runProguard" with "minifyEnabled" in your build.gradle files.

runProguard was renamed to minifyEnabled in version 0.14.0. For more info, See Android Build System

Markdown `native` text alignment

For Markdown Extra you can use custom attributes:

# Example text {style=text-align:center}

This works for headers and blockquotes, but not for paragraphs, inline elements and code blocks.

A shorter version (but not supported in HTML 5):

# Example text {align=center}

Dynamically adding HTML form field using jQuery

You can add any type of HTML with methods like append and appendTo (among others):

jQuery manipulation methods

Example:

$('form#someform').append('<input type="text" name="something" id="something" />');

Font size relative to the user's screen resolution?

You might try this tool: http://fittextjs.com/

I haven't used this second tool, but it seems similar: https://github.com/zachleat/BigText

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

Mysql database sync between two databases

Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.

"inconsistent use of tabs and spaces in indentation"

With the IDLE editor you can use this:

  • Menu Edit ? Select All
  • Menu Format ? Untabify Region
  • Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
  • Hit select, and it fixes the entire document.

How to delete last item in list?

You need:

record = record[:-1]

before the for loop.

This will set record to the current record list but without the last item. You may, depending on your needs, want to ensure the list isn't empty before doing this.

How do I use .woff fonts for my website?

You need to declare @font-face like this in your stylesheet

@font-face {
  font-family: 'Awesome-Font';
  font-style: normal;
  font-weight: 400;
  src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}

Now if you want to apply this font to a paragraph simply use it like this..

p {
font-family: 'Awesome-Font', Arial;
}

More Reference

What's a decent SFTP command-line client for windows?

WinSCP can be called from batch file:

"C:\Program Files\WinSCP\WinSCP.exe" /console

Example commands:

option batch on 
option confirm off  
option transfer binary 
open sftp://username@hostname:port -hostkey="ssh-rsa " 

SQL Error: ORA-00913: too many values

If you are having 112 columns in one single table and you would like to insert data from source table, you could do as

create table employees as select * from source_employees where employee_id=100;

Or from sqlplus do as

copy from source_schema/password insert employees using select * from 
source_employees where employee_id=100;

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

If you defined your cell through the Interface Builder, by placing a cell inside your UICollectionView, or UITableView :

Make sure you binded the cell with an actual class you created, and very important, that you checked "Inherit module from target"

How to check for an empty struct?

Just a quick addition, because I tackled the same issue today:

With Go 1.13 it is possible to use the new isZero() method:

if reflect.ValueOf(session).IsZero() {
     // do stuff...
}

I didn't test this regarding performance, but I guess that this should be faster, than comparing via reflect.DeepEqual().

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

Sorting a list using Lambda/Linq to objects

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;

public static class EnumerableHelper
{

    static MethodInfo orderBy = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName)
    {
        var pi = typeof(TSource).GetProperty(propertyName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        var sourceParam = Expression.Parameter(typeof(IEnumerable<TSource>), "source");
        return 
            Expression.Lambda<Func<IEnumerable<TSource>, IOrderedEnumerable<TSource>>>
            (
                Expression.Call
                (
                    orderBy.MakeGenericMethod(typeof(TSource), pi.PropertyType), 
                    sourceParam, 
                    Expression.Lambda
                    (
                        typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), 
                        Expression.Property(selectorParam, pi), 
                        selectorParam
                    )
                ), 
                sourceParam
            )
            .Compile()(source);
    }

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName, bool ascending)
    {
        return ascending ? source.OrderBy(propertyName) : source.OrderBy(propertyName).Reverse();
    }

}

Another one, this time for any IQueryable:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class IQueryableHelper
{

    static MethodInfo orderBy = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();
    static MethodInfo orderByDescending = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderByDescending" && x.GetParameters().Length == 2).First();

    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, params string[] sortDescriptors)
    {
        return sortDescriptors.Length > 0 ? source.OrderBy(sortDescriptors, 0) : source;
    }

    static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string[] sortDescriptors, int index)
    {
        if (index < sortDescriptors.Length - 1) source = source.OrderBy(sortDescriptors, index + 1);
        string[] splitted = sortDescriptors[index].Split(' ');
        var pi = typeof(TSource).GetProperty(splitted[0], BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.IgnoreCase);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        return source.Provider.CreateQuery<TSource>(Expression.Call((splitted.Length > 1 && string.Compare(splitted[1], "desc", StringComparison.Ordinal) == 0 ? orderByDescending : orderBy).MakeGenericMethod(typeof(TSource), pi.PropertyType), source.Expression, Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), Expression.Property(selectorParam, pi), selectorParam)));
    }

}

You can pass multiple sort criteria, like this:

var q = dc.Felhasznalos.OrderBy(new string[] { "Email", "FelhasznaloID desc" });

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

Get all LI elements in array

If you want all the li tags in an array even when they are in different ul tags then you can simply do

var lis = document.getElementByTagName('li'); 

and if you want to get particular div tag li's then:

var lis = document.getElementById('divID').getElementByTagName('li'); 

else if you want to search a ul first and then its li tags then you can do:

var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
    var lis=uls[i].getElementsByTagName('li');
    for(var j=0;j<lis.length;j++){
        console.log(lis[j].innerHTML);
    }
}

How to set index.html as root file in Nginx?

For me, the try_files directive in the (currently most voted) answer https://stackoverflow.com/a/11957896/608359 led to rewrite cycles,

*173 rewrite or internal redirection cycle while internally redirecting

I had better luck with the index directive. Note that I used a forward slash before the name, which might or might not be what you want.

server {
  listen 443 ssl;
  server_name example.com;

  root /home/dclo/example;
  index /index.html;
  error_page 404 /index.html;

  # ... ssl configuration
}

In this case, I wanted all paths to lead to /index.html, including when returning a 404.

How to access the contents of a vector from a pointer to the vector in C++?

There are many solutions, here's a few I've come up with:

int main(int nArgs, char ** vArgs)
{
    vector<int> *v = new vector<int>(10);
    v->at(2); //Retrieve using pointer to member
    v->operator[](2); //Retrieve using pointer to operator member
    v->size(); //Retrieve size
    vector<int> &vr = *v; //Create a reference
    vr[2]; //Normal access through reference
    delete &vr; //Delete the reference. You could do the same with
                //a pointer (but not both!)
}

How to get the indices list of all NaN value in numpy array?

Since x!=x returns the same boolean array with np.isnan(x) (because np.nan!=np.nan would return True), you could also write:

np.argwhere(x!=x)

However, I still recommend writing np.argwhere(np.isnan(x)) since it is more readable. I just try to provide another way to write the code in this answer.

How to enable cURL in PHP / XAMPP

If you're are using MAMP, cURL is enabled by default.

Escaping quotation marks in PHP

$text1= "From time to \"time\"";

or

$text1= 'From time to "time"';

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)

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

And just to give you yet another option, you can use NOT ISNULL(archived) as your WHERE filter.

JavaScript code to stop form submission

Lets say you have a form similar to this

<form action="membersDeleteAllData.html" method="post">
    <button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>

Here is the javascript for the confirmAction function

<script type="text/javascript">
    function confirmAction(e)
    {
        var confirmation = confirm("Are you sure about this ?") ;

        if (!confirmation)
        {
            e.preventDefault() ;
            returnToPreviousPage();
        }

        return confirmation ;
    }
</script>

This one works on Firefox, Chrome, Internet Explorer(edge), Safari, etc.

If that is not the case let me know

Return char[]/string from a function

char* charP = createStr();

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

Get current NSDate in timestamp format

Can also use

@(time(nil)).stringValue);

for timestamp in seconds.

How to display a list of images in a ListView in Android?

File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >  

<ImageView android:id="@+id/R.id.list_item_image"
  android:layout_width="100dip"
  android:layout_height="wrap_content" />  
</LinearLayout>

NumPy array initialization (fill with identical values)

I believe fill is the fastest way to do this.

a = np.empty(10)
a.fill(7)

You should also always avoid iterating like you are doing in your example. A simple a[:] = v will accomplish what your iteration does using numpy broadcasting.

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

If you keep on allocating & keeping references to object, you will fill up any amount of memory you have.

One option is to do a transparent file close & open when they switch tabs (you only keep a pointer to the file, and when the user switches tab, you close & clean all the objects... it'll make the file change slower... but...), and maybe keep only 3 or 4 files on memory.

Other thing you should do is, when the user opens a file, load it, and intercept any OutOfMemoryError, then (as it is not possible to open the file) close that file, clean its objects and warn the user that he should close unused files.

Your idea of dynamically extending virtual memory doesn't solve the issue, for the machine is limited on resources, so you should be carefull & handle memory issues (or at least, be carefull with them).

A couple of hints i've seen with memory leaks is:

--> Keep on mind that if you put something into a collection and afterwards forget about it, you still have a strong reference to it, so nullify the collection, clean it or do something with it... if not you will find a memory leak difficult to find.

--> Maybe, using collections with weak references (weakhashmap...) can help with memory issues, but you must be carefull with it, for you might find that the object you look for has been collected.

--> Another idea i've found is to develope a persistent collection that stored on database objects least used and transparently loaded. This would probably be the best approach...

How to get a variable type in Typescript?

Type guards in typescript

To determine the type of a variable after a conditional statement you can use type guards. A type guard in typescript is the following:

An expression which allows you to narrow down the type of something within a conditional block.

In other words it is an expression within a conditional block from where the typescript compiler has enough information to narrow down the type. The type will be more specific within the block of the type guard because the compiler has inferred more information about the type.

Example

declare let abc: number | string;

// typeof abc === 'string' is a type guard
if (typeof abc === 'string') {
    // abc: string
    console.log('abc is a string here')
} else {
    // abc: number, only option because the previous type guard removed the option of string
    console.log('abc is a number here')
}

Besides the typeof operator there are built in type guards like instanceof, in and even your own type guards.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You need to define a class for the bullets you want to hide. For examples

.no-bullets {
    list-style-type: none;
}

Then apply it to the list you want hidden bullets:

<ul class="no-bullets">

All other lists (without a specific class) will show the bulltets as usual.

How to get JQuery.trigger('click'); to initiate a mouse click

Try this that works for me:

$('#bar').mousedown();

Best practices with STDIN in Ruby?

I am not quite sure what you need, but I would use something like this:

#!/usr/bin/env ruby

until ARGV.empty? do
  puts "From arguments: #{ARGV.shift}"
end

while a = gets
  puts "From stdin: #{a}"
end

Note that because ARGV array is empty before first gets, Ruby won't try to interpret argument as text file from which to read (behaviour inherited from Perl).

If stdin is empty or there is no arguments, nothing is printed.

Few test cases:

$ cat input.txt | ./myprog.rb
From stdin: line 1
From stdin: line 2

$ ./myprog.rb arg1 arg2 arg3
From arguments: arg1
From arguments: arg2
From arguments: arg3
hi!
From stdin: hi!

Downloading an entire S3 bucket?

If you use Firefox with S3Fox, that DOES let you select all files (shift-select first and last) and rightclick and download all... I've done it with 500+ files w/o problem

How to locate the Path of the current project directory in Java (IDE)?

This is a code snippet to retrieve the path of the current running web application project in java.

public String getPath() throws UnsupportedEncodingException {

    String path = this.getClass().getClassLoader().getResource("").getPath();
    String fullPath = URLDecoder.decode(path, "UTF-8");
    String pathArr[] = fullPath.split("/WEB-INF/classes/");
    System.out.println(fullPath);
    System.out.println(pathArr[0]);
    fullPath = pathArr[0];

    return fullPath;

}

Source: https://dzone.com/articles/get-current-web-application

Difference between string and StringBuilder in C#

From the StringBuilder Class documentation:

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Access images inside public folder in laravel

I have created an Asset helper of my own.

First I defined the asset types and path in app/config/assets.php:

return array(

    /*
    |--------------------------------------------------------------------------
    | Assets paths
    |--------------------------------------------------------------------------
    |
    | Location of all application assets, relative to the public folder,
    | may be used together with absolute paths or with URLs.
    |
    */

    'images' => '/storage/images',
    'css' => '/assets/css',
    'img' => '/assets/img',
    'js' => '/assets/js'
);

Then the actual Asset class:

class Asset
{
    private static function getUrl($type, $file)
    {
        return URL::to(Config::get('assets.' . $type) . '/' . $file);
    }

    public static function css($file)
    {
        return self::getUrl('css', $file);
    }

    public static function img($file)
    {
        return self::getUrl('img', $file);
    }

    public static function js($file)
    {
        return self::getUrl('js', $file);
    }

}

So in my view I can do this to show an image:

{{ HTML::image(Asset::img('logo.png'), "My logo")) }}

Or like this to implement a Java script:

{{ HTML::script(Asset::js('my_script.js')) }}

Insert auto increment primary key to existing table

For those like myself getting a Multiple primary key defined error try:

ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST NOT NULL;

On MySQL v5.5.31 this set the id column as the primary key for me and populated each row with an incrementing value.

What is LDAP used for?

Well, there are LDAP servers and the LDAP protocol. Combined, it's a data store, or a database. It's not relational, but it's just a place to store data, and it's optimized to be efficient at reads more than writes. It doesn't support transactions.

Now, it happens to be very popular for storing credentials, but that's by no means its only purpose, and not its original purpose.

How to compare variables to undefined, if I don’t know whether they exist?

!undefined is true in javascript, so if you want to know whether your variable or object is undefined and want to take actions, you could do something like this:

if(<object or variable>) {
     //take actions if object is not undefined
} else {
     //take actions if object is undefined
}

How do I turn a String into a InputStreamReader in java?

Are you trying to get a) Reader functionality out of InputStreamReader, or b) InputStream functionality out of InputStreamReader? You won't get b). InputStreamReader is not an InputStream.

The purpose of InputStreamReader is to take an InputStream - a source of bytes - and decode the bytes to chars in the form of a Reader. You already have your data as chars (your original String). Encoding your String into bytes and decoding the bytes back to chars would be a redundant operation.

If you are trying to get a Reader out of your source, use StringReader.

If you are trying to get an InputStream (which only gives you bytes), use apache commons IOUtils.toInputStream(..) as suggested by other answers here.

How to use localization in C#

Great answer by F.Mörk. But if you want to update translation, or add new languages once the application is released, you're stuck, because you always have to recompile it to generate the resources.dll.

Here is a solution to manually compile a resource dll. It uses the resgen.exe and al.exe tools (installed with the sdk).

Say you have a Strings.fr.resx resource file, you can compile a resources dll with the following batch:

resgen.exe /compile Strings.fr.resx,WpfRibbonApplication1.Strings.fr.resources 
Al.exe /t:lib /embed:WpfRibbonApplication1.Strings.fr.resources /culture:"fr" /out:"WpfRibbonApplication1.resources.dll"
del WpfRibbonApplication1.Strings.fr.resources
pause

Be sure to keep the original namespace in the file names (here "WpfRibbonApplication1")

TypeScript typed array usage

You could try either of these. They are not giving me errors.

It is also the suggested method from typescript for array declaration.

By using the Array<Thing> it is making use of the generics in typescript. It is similar to asking for a List<T> in c# code.

// Declare with default value
private _possessions: Array<Thing> = new Array<Thing>();
// or
private _possessions: Array<Thing> = [];
// or -> prefered by ts-lint
private _possessions: Thing[] = [];

or

// declare
private _possessions: Array<Thing>;
// or -> preferd by ts-lint
private _possessions: Thing[];

constructor(){
    //assign
    this._possessions = new Array<Thing>();
    //or
    this._possessions = [];
}

Forcing anti-aliasing using css: Is this a myth?

I disagree with Chad Birch. We can force anti-aliasing, at least in Chrome using a simple css trick with the -webkit-text-stroke property:-

-webkit-text-stroke: 1px transparent;

'DataFrame' object has no attribute 'sort'

sort() was deprecated for DataFrames in favor of either:

sort() was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values() and sort_index(). It was removed from Pandas with release 0.20 (2017-05-05).

datetime dtypes in pandas read_csv

There is a parse_dates parameter for read_csv which allows you to define the names of the columns you want treated as dates or datetimes:

date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Jquery Setting Value of Input Field

change your jquery loading setting to onload in jsfiddle . . .it works . . .

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Make sure you open the .xcworkspace file not the project file from xCode Project menu when working with pods. That should solve the issue with linking.

Hash function that produces short hashes?

I needed something along the lines of a simple string reduction function recently. Basically, the code looked something like this (C/C++ code ahead):

size_t ReduceString(char *Dest, size_t DestSize, const char *Src, size_t SrcSize, bool Normalize)
{
    size_t x, x2 = 0, z = 0;

    memset(Dest, 0, DestSize);

    for (x = 0; x < SrcSize; x++)
    {
        Dest[x2] = (char)(((unsigned int)(unsigned char)Dest[x2]) * 37 + ((unsigned int)(unsigned char)Src[x]));
        x2++;

        if (x2 == DestSize - 1)
        {
            x2 = 0;
            z++;
        }
    }

    // Normalize the alphabet if it looped.
    if (z && Normalize)
    {
        unsigned char TempChr;
        y = (z > 1 ? DestSize - 1 : x2);
        for (x = 1; x < y; x++)
        {
            TempChr = ((unsigned char)Dest[x]) & 0x3F;

            if (TempChr < 10)  TempChr += '0';
            else if (TempChr < 36)  TempChr = TempChr - 10 + 'A';
            else if (TempChr < 62)  TempChr = TempChr - 36 + 'a';
            else if (TempChr == 62)  TempChr = '_';
            else  TempChr = '-';

            Dest[x] = (char)TempChr;
        }
    }

    return (SrcSize < DestSize ? SrcSize : DestSize);
}

It probably has more collisions than might be desired but it isn't intended for use as a cryptographic hash function. You might try various multipliers (i.e. change the 37 to another prime number) if you get too many collisions. One of the interesting features of this snippet is that when Src is shorter than Dest, Dest ends up with the input string as-is (0 * 37 + value = value). If you want something "readable" at the end of the process, Normalize will adjust the transformed bytes at the cost of increasing collisions.

Source:

https://github.com/cubiclesoft/cross-platform-cpp/blob/master/sync/sync_util.cpp

How to Bootstrap navbar static to fixed on scroll?

Or you can change position of specific div using class name

$(document).scroll(function(e){
    var scrollTop = $(document).scrollTop();
    if(scrollTop > 0){
        //console.log(scrollTop);
        $('.header').css("position","fixed");
    } else {
         $('.header').css("position","relative");
    }
});

jQuery UI DatePicker to show month year only

Is it just me or is this not working as it should in IE(8)? The date changes when clicking done, but the datepicker opens up again, until you actually click somewhere in the page to loose focus on the input field...

I'm looking in to solving this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
    $('.date-picker').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
    });
});
</script>
<style>
.ui-datepicker-calendar {
    display: none;
    }
</style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

How can I print using JQuery

There is a jquery print area. I've been using it for some time now.

$(".printMe").click(function(){
   $("#outprint").printArea({ mode: 'popup', popClose: true });
});

Get method arguments using Spring AOP?

you can get method parameter and its value and if annotated with a annotation with following code:

Map<String, Object> annotatedParameterValue = getAnnotatedParameterValue(MethodSignature.class.cast(jp.getSignature()).getMethod(), jp.getArgs()); ....

private Map<String, Object> getAnnotatedParameterValue(Method method, Object[] args) {
        Map<String, Object> annotatedParameters = new HashMap<>();
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        Parameter[] parameters = method.getParameters();

        int i = 0;
        for (Annotation[] annotations : parameterAnnotations) {
            Object arg = args[i];
            String name = parameters[i++].getDeclaringExecutable().getName();
            for (Annotation annotation : annotations) {
                if (annotation instanceof AuditExpose) {
                    annotatedParameters.put(name, arg);
                }
            }
        }
        return annotatedParameters;
    }

Proper way to exit command line program?

Take a look at Job Control on UNIX systems

If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs and kill -9 %<job #> to kill it. The '-9' is a type of signal. You can man kill to see a list of signals.

How can you debug a CORS request with cURL?

Here's how you can debug CORS requests using curl.

Sending a regular CORS request using cUrl:

curl -H "Origin: http://example.com" --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

The -H "Origin: http://example.com" flag is the third party domain making the request. Substitute in whatever your domain is.

The --verbose flag prints out the entire response so you can see the request and response headers.

The url I'm using above is a sample request to a Google API that supports CORS, but you can substitute in whatever url you are testing.

The response should include the Access-Control-Allow-Origin header.

Sending a preflight request using cUrl:

curl -H "Origin: http://example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS --verbose \
  https://www.googleapis.com/discovery/v1/apis?fields=

This looks similar to the regular CORS request with a few additions:

The -H flags send additional preflight request headers to the server

The -X OPTIONS flag indicates that this is an HTTP OPTIONS request.

If the preflight request is successful, the response should include the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers response headers. If the preflight request was not successful, these headers shouldn't appear, or the HTTP response won't be 200.

You can also specify additional headers, such as User-Agent, by using the -H flag.

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

jeues answer helped me nothing :-( after hours I finally found the solution for my system and I think this will help other people too. I had to set the LD_LIBRARY_PATH like this:

   export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/

after that everything worked very well, even without any "-extension RANDR" switch.

Carriage Return\Line feed in Java

Don't know who looks at your file, but if you open it in wordpad instead of notepad, the linebreaks will show correct. In case you're using a special file extension, associate it with wordpad and you're done with it. Or use any other more advanced text editor.

Difference between pre-increment and post-increment in a loop?

One (++i) is preincrement, one (i++) is postincrement. The difference is in what value is immediately returned from the expression.

// Psuedocode
int i = 0;
print i++; // Prints 0
print i; // Prints 1
int j = 0;
print ++j; // Prints 1
print j; // Prints 1

Edit: Woops, entirely ignored the loop side of things. There's no actual difference in for loops when it's the 'step' portion (for(...; ...; )), but it can come into play in other cases.

"Can't find Project or Library" for standard VBA functions

I have experienced this exact problem and found, on the users machine, one of the libraries I depended on was marked as "MISSING" in the references dialog. In that case it was some office font library that was available in my version of Office 2007, but not on the client desktop.

The error you get is a complete red herring (as pointed out by divo).

Fortunately I wasn't using anything from the library, so I was able to remove it from the XLA references entirely. I guess, an extension of divo' suggested best practice would be for testing to check the XLA on all the target Office versions (not a bad idea in any case).

get and set in TypeScript

It is very similar to creating common methods, simply put the keyword reserved get or set at the beginning.

class Name{
    private _name: string;

    getMethod(): string{
        return this._name;
    }

    setMethod(value: string){
        this._name = value
    }

    get getMethod1(): string{
        return this._name;
    }

    set setMethod1(value: string){
        this._name = value
    }
}

class HelloWorld {

    public static main(){

        let test = new Name();

        test.setMethod('test.getMethod() --- need ()');
            console.log(test.getMethod());

        test.setMethod1 = 'test.getMethod1 --- no need (), and used = for set ';
            console.log(test.getMethod1);
    }
}
HelloWorld.main();

In this case you can skip return type in get getMethod1() {

    get getMethod1() {
        return this._name;
    }

SVN Repository on Google Drive or DropBox

I made my own subversion repository on my Ubuntu One folder. Then, I imported the files to the repository using svn+ssh and my user account password.

When I want to do a checkout, I just checkout from my Ubuntu One folder. The commit process its analogue.

You must setup Ubutnu One on the devices that you want to grant access, then checkout the project from this folder to a temporary folder to edit it.

In my case, I use a folder in the Ubuntu One file-system, so I have the repository and my develop-folder in Ubuntu One.

How to remove a character at the end of each line in unix

You can use sed:

sed 's/,$//' file > file.nocomma

and to remove whatever last character:

sed 's/.$//' file > file.nolast

number_format() with MySQL

You need this:

CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))

How to display the function, procedure, triggers source code in postgresql?

Here are few examples from PostgreSQL-9.5

Display list:

  1. Functions: \df+
  2. Triggers : \dy+

Display Definition:

postgres=# \sf
function name is required

postgres=# \sf pg_reload_conf()
CREATE OR REPLACE FUNCTION pg_catalog.pg_reload_conf()
 RETURNS boolean
 LANGUAGE internal
 STRICT
AS $function$pg_reload_conf$function$

postgres=# \sf pg_encoding_to_char
CREATE OR REPLACE FUNCTION pg_catalog.pg_encoding_to_char(integer)
 RETURNS name
 LANGUAGE internal
 STABLE STRICT
AS $function$PG_encoding_to_char$function$

Count number of records returned by group by

In PostgreSQL this works for me:

select count(count.counts) 
from 
    (select count(*) as counts 
     from table 
     group by concept) as count;

How to process each output line in a loop?

Often the order of the processing does not matter. GNU Parallel is made for this situation:

grep xyz abc.txt | parallel echo do stuff to {}

If you processing is more like:

grep xyz abc.txt | myprogram_reading_from_stdin

and myprogram is slow then you can run:

grep xyz abc.txt | parallel --pipe myprogram_reading_from_stdin

C++, how to declare a struct in a header file

You've only got a forward declaration for student in the header file; you need to place the struct declaration in the header file, not the .cpp. The method definitions will be in the .cpp (assuming you have any).

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

Assigning multiple styles on an HTML element

The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:

<h2 style="text-align:center; font-family:tahoma">TITLE</h2>

Regex Letters, Numbers, Dashes, and Underscores

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:

([[:alnum:]\-_]+)

But a since you are including the underscore I would simply use:

([\w\-]+)

(works in all variants)

What are the differences between a HashMap and a Hashtable in Java?

My small contribution :

  1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.

  2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.

  3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.

Generate unique random numbers between 1 and 100

For example: To generate 8 unique random numbers and store them to an array, you can simply do this:

_x000D_
_x000D_
var arr = [];_x000D_
while(arr.length < 8){_x000D_
    var r = Math.floor(Math.random() * 100) + 1;_x000D_
    if(arr.indexOf(r) === -1) arr.push(r);_x000D_
}_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Printing one character at a time from a string, using the while loop

Python allows you to use a string as an iterator:

for character in 'string':
    print(character)

I'm guessing it's your job to figure out how to turn that into a while loop.

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

I like to use custom conditions. Here's some code in Python:

def conditions(driver):
    flag = True
    ticker = driver.find_elements_by_id("textbox")
    if not ticker:
        flag = False
    return flag

... click something to load ...
self.wait = WebDriverWait(driver, timeout)
self.wait.until(conditions)

Whenever you need to wait, you can do it explicitly by checking existance of a certain element (such element may vary from page to page). find_elements_by_id returns list - empty or not, you have just to check.

Better way to convert an int to a boolean

int i = 0;
bool b = Convert.ToBoolean(i);