Programs & Examples On #Members

0

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

How can I stream webcam video with C#?

I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.

If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

just open the hive terminal from the hive folder,after editing (bashrc) and (hive-site.xml) files. Steps-- open hive folder where it is installed. now open terminal from folder.

disable Bootstrap's Collapse open/close animation

Bootstrap 2 CSS solution:

.collapse {  transition: height 0.01s; }  

NB: setting transition: none disables the collapse functionnality.


Bootstrap 4 solution:

.collapsing {
  transition: none !important;
}

An Iframe I need to refresh every 30 seconds (but not the whole page)

I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.

UITableview: How to Disable Selection for Some Rows but Not Others

I like Brian Chapados answer above. However, this means that you may have logic duplicated in both cellForRowAtIndexPath and then in willSelectRowAtIndexPath which can easily get out of sync. Instead of duplicating the logic, just check the selectionStyle:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.selectionStyle == UITableViewCellSelectionStyleNone)
        return nil;

    else
        return indexPath;
}

How do I update pip itself from inside my virtual environment?

I tried all of these solutions mentioned above under Debian Jessie. They don't work, because it just takes the latest version compile by the debian package manager which is 1.5.6 which equates to version 6.0.x. Some packages that use pip as prerequisites will not work as a results, such as spaCy (which needs the option --no-cache-dir to function correctly).

So the actual best way to solve these problems is to run get-pip.py downloaded using wget, from the website or using curl as follows:

 wget https://bootstrap.pypa.io/get-pip.py -O ./get-pip.py
 python ./get-pip.py
 python3 ./get-pip.py

This will install the current version which at the time of writing this solution is 9.0.1 which is way beyond what Debian provides.

 $ pip --version
 pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python2.7/dist-packages (python 2.7)
 $ pip3 --version
 pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python3.4/site-packages (python 3.4)

Reading a .txt file using Scanner class in Java

By the way it worth setting up the character encoding as well:

Scanner scanner = new Scanner(new File("C:\\tmp\\edit1.txt"), "UTF-16");

Convert generic list to dataset in C#

There is a bug with Lee's extension code above, you need to add the newly filled row to the table t when iterating throught the items in the list.

public static DataSet ToDataSet<T>(this IList<T> list) {

Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);

//add a column to table for each public property on T
foreach(var propInfo in elementType.GetProperties())
{
    t.Columns.Add(propInfo.Name, propInfo.PropertyType);
}

//go through each property on T and add each value to the table
foreach(T item in list)
{
    DataRow row = t.NewRow();
    foreach(var propInfo in elementType.GetProperties())
    {
            row[propInfo.Name] = propInfo.GetValue(item, null);
    }

    //This line was missing:
    t.Rows.Add(row);
}


return ds;

}

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

Switching the order of block elements with CSS

Hows this for low tech...

put the ad at the top and bottom and use media queries to display:none as appropriate.

If the ad wasn't too big, it wouldn't add too much size to the download, you could even customise where the ad sent you for iPhone/pc.

Using jQuery Fancybox or Lightbox to display a contact form

Have a look at: Greybox

It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.

You will find many information on how to use Greybox and also some great examples. Cheers Kara

How to upper case every first letter of word in a string?

import org.apache.commons.lang.WordUtils;

public class CapitalizeFirstLetterInString {
    public static void main(String[] args) {
        // only the first letter of each word is capitalized.
        String wordStr = WordUtils.capitalize("this is first WORD capital test.");
        //Capitalize method capitalizes only first character of a String
        System.out.println("wordStr= " + wordStr);

        wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
        // This method capitalizes first character of a String and make rest of the characters lowercase
        System.out.println("wordStr = " + wordStr );
    }
}

Output :

This Is First WORD Capital Test.

This Is First Word Capital Test.

Testing two JSON objects for equality ignoring child order in Java

Looking at the answers, I tried JSONAssert but it failed. So I used Jackson with zjsonpatch. I posted details in the SO answer here.

List of IP addresses/hostnames from local network in Python

For OSX (and Linux), a simple solution is to use either os.popen or os.system and run the arp -a command.

For example:

devices = []
for device in os.popen('arp -a'): devices.append(device)

This will give you a list of the devices on your local network.

How to get a complete list of object's methods and attributes?

Only to supplement:

  1. dir() is the most powerful/fundamental tool. (Most recommended)
  2. Solutions other than dir() merely provide their way of dealing the output of dir().

    Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __, but sometimes you may well need the __doc__ doc-string.

  3. __dir__() and dir() returns identical content.
  4. __dict__ and dir() are different. __dict__ returns incomplete content.
  5. IMPORTANT: __dir__() can be sometimes overwritten with a function, value or type, by the author for whatever purpose.

    Here is an example:

    \\...\\torchfun.py in traverse(self, mod, search_attributes)
    445             if prefix in traversed_mod_names:
    446                 continue
    447             names = dir(m)
    448             for name in names:
    449                 obj = getattr(m,name)
    

    TypeError: descriptor __dir__ of 'object' object needs an argument

    The author of PyTorch modified the __dir__() method to something that requires an argument. This modification makes dir() fail.

  6. If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.

Html.EditorFor Set Default Value

This is my working code:

@Html.EditorFor(model => model.PropertyName, new { htmlAttributes = new { @class = "form-control", @Value = "123" } })

my difference with other answers is using Value inside the htmlAttributes array

Redirection of standard and error output appending to the same log file

Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.

$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)

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

I could not get the example working using the resizeMode properties of Image, but because the images will all be square there is a way to do it using the Dimensions of the window along with flexbox.

Set flexDirection: 'row', and flexWrap: 'wrap', then they will all line up as long as they are all the same dimensions.

I set it up here

https://snack.expo.io/HkbZNqjeZ

"use strict";

var React = require("react-native");
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  Dimensions,
  ScrollView
} = React;

var deviceWidth = Dimensions.get("window").width;
var temp = "http://thumbs.dreamstime.com/z/close-up-angry-chihuahua-growling-2-years-old-15126199.jpg";
var SampleApp = React.createClass({
  render: function() {
    var images = [];

    for (var i = 0; i < 10; i++) {
      images.push(
        <TouchableOpacity key={i} activeOpacity={0.75} style={styles.item}>
          <Image style={styles.image} source={{ uri: temp }} />
        </TouchableOpacity>
      );
    }

    return (
      <ScrollView style={{ flex: 1 }}>
        <View style={styles.container}>
          {images}
        </View>
      </ScrollView>
    );
  }
});

What does double question mark (??) operator mean in PHP

$x = $y ?? 'dev'

is short hand for x = y if y is set, otherwise x = 'dev'

There is also

$x = $y =="SOMETHING" ? 10 : 20

meaning if y equals 'SOMETHING' then x = 10, otherwise x = 20

Error: request entity too large

Little old post but I had the same problem

Using express 4.+ my code looks like this and it works great after two days of extensive testing.

var url         = require('url'),
    homePath    = __dirname + '/../',
    apiV1       = require(homePath + 'api/v1/start'),
    bodyParser  = require('body-parser').json({limit:'100mb'});

module.exports = function(app){
    app.get('/', function (req, res) {
        res.render( homePath + 'public/template/index');
    });

    app.get('/api/v1/', function (req, res) {
        var query = url.parse(req.url).query;
        if ( !query ) {
            res.redirect('/');
        }
        apiV1( 'GET', query, function (response) {
            res.json(response);
        });
    });

    app.get('*', function (req,res) {
        res.redirect('/');
    });

    app.post('/api/v1/', bodyParser, function (req, res) {
        if ( !req.body ) {
            res.json({
                status: 'error',
                response: 'No data to parse'
            });
        }
        apiV1( 'POST', req.body, function (response) {
            res.json(response);
        });
    });
};

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

If you want to obtain a stand-alone binary application in Python try to use a tool like py2exe or PyInstaller.

XAMPP - MySQL shutdown unexpectedly

There are a number of things I've tried. This is the 2nd time this has happened to me. On my first time, I've to reinstall my xampp. And on the third day, mysql crashed again. I've tried everything I found on the internet. Like, innodb_flush_method=normal in my.ini file and deleting ibdata1, ib_logfile1, ib_logfile0 files, and others but none of these works. So later I tried to run xampp with admin privilege and install apache and mysql as a service as it was instructed on xampp control panel itself. After starting mysql, I read error-log again and from there I came to know that one of my databases is responsible for this. That database file won't let mysql start. So I deleted everything in the data folder and then in cmd I navigated to C:/xampp/mysql/bin path and ran these commands:

mysqld --initialize

mysql_install_db

and mysql started running again. But my databases and data are lost.

Using async/await with a forEach loop

Currently the Array.forEach prototype property doesn't support async operations, but we can create our own poly-fill to meet our needs.

// Example of asyncForEach Array poly-fill for NodeJs
// file: asyncForEach.js
// Define asynForEach function 
async function asyncForEach(iteratorFunction){
  let indexer = 0
  for(let data of this){
    await iteratorFunction(data, indexer)
    indexer++
  }
}
// Append it as an Array prototype property
Array.prototype.asyncForEach = asyncForEach
module.exports = {Array}

And that's it! You now have an async forEach method available on any arrays that are defined after these to operations.

Let's test it...

// Nodejs style
// file: someOtherFile.js

const readline = require('readline')
Array = require('./asyncForEach').Array
const log = console.log

// Create a stream interface
function createReader(options={prompt: '>'}){
  return readline.createInterface({
    input: process.stdin
    ,output: process.stdout
    ,prompt: options.prompt !== undefined ? options.prompt : '>'
  })
}
// Create a cli stream reader
async function getUserIn(question, options={prompt:'>'}){
  log(question)
  let reader = createReader(options)
  return new Promise((res)=>{
    reader.on('line', (answer)=>{
      process.stdout.cursorTo(0, 0)
      process.stdout.clearScreenDown()
      reader.close()
      res(answer)
    })
  })
}

let questions = [
  `What's your name`
  ,`What's your favorite programming language`
  ,`What's your favorite async function`
]
let responses = {}

async function getResponses(){
// Notice we have to prepend await before calling the async Array function
// in order for it to function as expected
  await questions.asyncForEach(async function(question, index){
    let answer = await getUserIn(question)
    responses[question] = answer
  })
}

async function main(){
  await getResponses()
  log(responses)
}
main()
// Should prompt user for an answer to each question and then 
// log each question and answer as an object to the terminal

We could do the same for some of the other array functions like map...

async function asyncMap(iteratorFunction){
  let newMap = []
  let indexer = 0
  for(let data of this){
    newMap[indexer] = await iteratorFunction(data, indexer, this)
    indexer++
  }
  return newMap
}

Array.prototype.asyncMap = asyncMap

... and so on :)

Some things to note:

  • Your iteratorFunction must be an async function or promise
  • Any arrays created before Array.prototype.<yourAsyncFunc> = <yourAsyncFunc> will not have this feature available

Passing variables through handlebars partial

Handlebars partials take a second parameter which becomes the context for the partial:

{{> person this}}

In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:

{{> person headline='Headline'}}

You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32

Counting Chars in EditText Changed Listener

little few change in your code :

TextView tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        tv.setText(String.valueOf(s.toString().length()));
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
}); 

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

Send email by using codeigniter library via localhost

$insert = $this->db->insert('email_notification', $data);
                $this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");

                //require ("plugins/mailer/PHPMailerAutoload.php");
                $mail = new PHPMailer;
                $mail->SMTPOptions = array(
                    'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true,
                ),
                );

                $message="
                     Your Account Has beed created successfully by Admin:
                    Username: ".$this->input->post('username')." <br><br>
                    Email: ".$this->input->post('sender_email')." <br><br>
                    Regargs<br>
                    <div class='background-color:#666;color:#fff;padding:6px;
                    text-align:center;'>
                         Bookly Admin.
                    </div>
                ";
                $mail->isSMTP(); // Set mailer to use SMTP
                $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
                $mail->SMTPAuth = true; 
                $subject = "Hello  ".$this->input->post('username');
                $mail->SMTDebug=2;
                $email = $this->input->post('sender_email'); //this email is user email
                $from_label = "Account Creation";
                $mail->Username = 'your email'; // SMTP username
                $mail->Password = 'password'; // SMTP password
                $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
                $mail->Port = 465;
                $mail->setFrom($from_label);
                $mail->addAddress($email, 'Bookly Admin');
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message;
                $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
             if($mail->send()){

                  }

android: data binding error: cannot find symbol class

I consistently run into this problem. I believe it has to do with android studio not being aware of dynamically generated files. If you have everything else right for databinding try to File > Invalidate Caches/Restart... and select Invalidate Caches and Restart. Then try and import the BR file... it should import fine.

You may have to throw in a Clean and Rebuild.

UINavigationBar custom back button without title

  1. Add new UIBarButtonItem to UINavigationItem to left
  2. Change UIBarButtonItem how to want use
  3. Now, click UINavigationItem and swipe barBackButtonItem from outlets to left UIBarButtonItem

enter image description here

Split varchar into separate columns in Oracle

With REGEXP_SUBSTR is as simple as:

SELECT REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 1) col_one,
       REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 2) col_two
FROM YOUR_TABLE t;

PHP How to fix Notice: Undefined variable:

It looks like you don't have any records that match your query, so you'd want to return an empty array (or null or something) if the number of rows == 0.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

  1. Remove the jar files in your gradle
  2. Sync it
  3. Copy that jar and sync it

This worked for me.

ASP.Net MVC: Calling a method from a view

This is how you call an instance method on the Controller:

@{
  ((HomeController)this.ViewContext.Controller).Method1();
}

This is how you call a static method in any class

@{
    SomeClass.Method();
}

This will work assuming the method is public and visible to the view.

Qt. get part of QString

Use the left function:

QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "

Also have a look at mid() if you want more control.

MySQL date formats - difficulty Inserting a date

An add-on to the previous answers since I came across this concern:

If you really want to insert something like 24-May-2005 to your DATE column, you could do something like this:

INSERT INTO someTable(Empid,Date_Joined)
VALUES
    ('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));

In the above query please note that if it's May(ie: the month in letters) the format should be %M.

NOTE: I tried this with the latest MySQL version 8.0 and it works!

Calling Non-Static Method In Static Method In Java

public class StaticMethod{

    public static void main(String []args)throws Exception{
        methodOne();
    }

    public int methodOne(){
        System.out.println("we are in first methodOne");
        return 1;
    }
}

the above code not executed because static method must have that class reference.

public class StaticMethod{
    public static void main(String []args)throws Exception{

        StaticMethod sm=new StaticMethod();
        sm.methodOne();
    }

    public int methodOne(){
        System.out.println("we are in first methodOne");
        return 1;
    }
}

This will be definitely get executed. Because here we are creating reference which nothing but "sm" by using that reference of that class which is nothing but (StaticMethod=new Static method()) we are calling method one (sm.methodOne()).

I hope this will be helpful.

Swift - Integer conversion to Hours/Minutes/Seconds

Building upon Vadian's answer, I wrote an extension that takes a Double (of which TimeInterval is a type alias) and spits out a string formatted as time.

extension Double {
  func asString(style: DateComponentsFormatter.UnitsStyle) -> String {
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute, .second, .nanosecond]
    formatter.unitsStyle = style
    guard let formattedString = formatter.string(from: self) else { return "" }
    return formattedString
  }
}

Here are what the various DateComponentsFormatter.UnitsStyle options look like:

10000.asString(style: .positional)  // 2:46:40
10000.asString(style: .abbreviated) // 2h 46m 40s
10000.asString(style: .short)       // 2 hr, 46 min, 40 sec
10000.asString(style: .full)        // 2 hours, 46 minutes, 40 seconds
10000.asString(style: .spellOut)    // two hours, forty-six minutes, forty seconds
10000.asString(style: .brief)       // 2hr 46min 40sec

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

Find and kill a process in one line using bash and regex

you can do it with awk and backtics

ps auxf |grep 'python csp_build.py'|`awk '{ print "kill " $2 }'`

$2 in awk prints column 2, and the backtics runs the statement that's printed.

But a much cleaner solution would be for the python process to store it's process id in /var/run and then you can simply read that file and kill it.

Built in Python hash() function

Most answers suggest this is because of different platforms, but there is more to it. From the documentation of object.__hash__(self):

By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n²) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).

Even running on the same machine will yield varying results across invocations:

$ python -c "print(hash('http://stackoverflow.com'))"
-3455286212422042986
$ python -c "print(hash('http://stackoverflow.com'))"
-6940441840934557333

While:

$ python -c "print(hash((1,2,3)))"
2528502973977326415
$ python -c "print(hash((1,2,3)))"
2528502973977326415

See also the environment variable PYTHONHASHSEED:

If this variable is not set or set to random, a random value is used to seed the hashes of str, bytes and datetime objects.

If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.

Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.

The integer must be a decimal number in the range [0, 4294967295]. Specifying the value 0 will disable hash randomization.

For example:

$ export PYTHONHASHSEED=0                            
$ python -c "print(hash('http://stackoverflow.com'))"
-5843046192888932305
$ python -c "print(hash('http://stackoverflow.com'))"
-5843046192888932305

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

The Microsoft way is this:

MSDN: How to determine Which .NET Framework Versions Are Installed (which directs you to the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\...)

If you want foolproof that's another thing. I wouldn't worry about an xcopy of the framework folder. If someone did that I would consider the computer broken.

The most foolproof way would be to write a small program that uses each version of .NET and the libraries that you care about and run them.

For a no install method, PowerBasic is an excellent tool. It creates small no runtime required exe's. It could automate the checks described in the MS KB article above.

How can I scroll a div to be visible in ReactJS?

For React 16, the correct answer is different from earlier answers:

class Something extends Component {
  constructor(props) {
    super(props);
    this.boxRef = React.createRef();
  }

  render() {
    return (
      <div ref={this.boxRef} />
    );
  }
}

Then to scroll, just add (after constructor):

componentDidMount() {
  if (this.props.active) { // whatever your test might be
    this.boxRef.current.scrollIntoView();
  }
}

Note: You must use '.current,' and you can send options to scrollIntoView:

scrollIntoView({
  behavior: 'smooth',
  block: 'center',
  inline: 'center',
});

(Found at http://www.albertgao.xyz/2018/06/07/scroll-a-not-in-view-component-into-the-view-using-react/)

Reading the spec, it was a little hard to suss out the meaning of block and inline, but after playing with it, I found that for a vertical scrolling list, block: 'end' made sure the element was visible without artificially scrolling the top of my content off the viewport. With 'center', an element near the bottom would be slid up too far and empty space appeared below it. But my container is a flex parent with justify: 'stretch' so that may affect the behavior. I didn't dig too much further. Elements with overflow hidden will impact how the scrollIntoView acts, so you'll probably have to experiment on your own.

My application has a parent that must be in view and if a child is selected, it then also scrolls into view. This worked well since parent DidMount happens before child's DidMount, so it scrolls to the parent, then when the active child is rendered, scrolls further to bring that one in view.

"Android library projects cannot be launched"?

our project surely is configured as "library" thats why you get the message : "Android library projects cannot be launched."

right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

Make sure that you have installed the correct NuGet package in your console application:

<package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" />

and that you are targeting at least .NET 4.0.

This being said, your GetAllFoos function is defined to return an IEnumerable<Prospect> whereas in your ReadAsAsync method you are passing IEnumerable<Foo> which obviously are not compatible types.

Install-Package Microsoft.AspNet.WebApi.Client

Select project in project manager console

Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

For Chrome they changed autoplay policy, so you can read about here:

var promise = document.querySelector('audio').play();

if (promise !== undefined) {
    promise.then(_ => {
        // Autoplay started!
    }).catch(error => {
        // Autoplay was prevented.
        // Show a "Play" button so that user can start playback.
    });
}

Fetching data from MySQL database using PHP, Displaying it in a form for editing

please try these

<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "User_name" value= "<?php echo $row['User_name']; ?> "size=10>
Password
<input type="text" name= "User_password" value= "<?php echo $row['User_password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>

Convert int to char in java

you may want it to be printed as '1' or as 'a'.

In case you want '1' as input then :

int a = 1;
char b = (char)(a + '0');
System.out.println(b);

In case you want 'a' as input then :

int a = 1;
char b = (char)(a-1 + 'a');
System.out.println(b);

java turns the ascii value to char :)

Python: Find a substring in a string and returning the index of the substring

There's a builtin method find on string objects.

s = "Happy Birthday"
s2 = "py"

print(s.find(s2))

Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)

find returns -1 if the string cannot be found.

scp or sftp copy multiple files with single command

Is more simple without using scp:

tar cf - file1 ... file_n | ssh user@server 'tar xf -'

This also let you do some things like compress the stream (-C) or (since OpenSSH v7.3) -J any times to jump through one (or more) proxy servers.

You can avoid using passwords coping your public key to ~/.ssh/authorized_keys with ssh-copy-id.

Posted also here (with more details) and here.

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

I fixed the issue (temporarily) by going to Edit Scheme, then in the Build section, removing my unit test target from being invoked in "Run".

How to make external HTTP requests with Node.js

You can use node.js http module to do that. You could check the documentation at Node.js HTTP.

You would need to pass the query string as well to the other HTTP Server. You should have that in ServerRequest.url.

Once you have those info, you could pass in the backend HTTP Server and port in the options that you will provide in the http.request()

Importing lodash into angular2 + typescript application

Install all thru terminal:

npm install lodash --save
tsd install lodash --save

Add paths in index.html

<script>
    System.config({
        packages: {
            app: {
                format: 'register',
                defaultExtension: 'js'
            }
        },
        paths: {
            lodash: './node_modules/lodash/lodash.js'
        }
    });
    System.import('app/init').then(null, console.error.bind(console));
</script>

Import lodash at the top of the .ts file

import * as _ from 'lodash'

Properties order in Margin

Margin="1,2,3,4"
  1. Left,
  2. Top,
  3. Right,
  4. Bottom

It is also possible to specify just two sizes like this:

Margin="1,2"
  1. Left AND right
  2. Top AND bottom

Finally you can specify a single size:

Margin="1"
  1. used for all sides

The order is the same as in WinForms.

Where does Vagrant download its .box files to?

As mentioned in the docs, boxes are stored at:

  • Mac OS X and Linux: ~/.vagrant.d/boxes
  • Windows: C:/Users/USERNAME/.vagrant.d/boxes

How do I reference a cell range from one worksheet to another using excel formulas?

If these worksheets reside in the same workbook, a simple solution would be to name the range, and have the formula refer to the named range. To name a range, select it, right click, and provide it with a meaningful name with Workbook scope.

For example =Sheet1!$A$1:$F$1 could be named: theNamedRange. Then your formula on Sheet2! could refer to it in your formula like this: =SUM(theNamedRange).

Incidentally, it is not clear from your question how you meant to use the range. If you put what you had in a formula (e.g., =SUM(Sheet1!A1:F1)) it will work, you simply need to insert that range argument in a formula. Excel does not resolve the range reference without a related formula because it does not know what you want to do with it.

Of the two methods, I find the named range convention is easier to work with.

How do I request and receive user input in a .bat and use it to run a certain program?

If the input is, say, N, your IF lines evaluate like this:

If N=="y" goto yes 
If N=="n" goto no
…

That is, you are comparing N with "y", then "n" etc. including "N". You are never going to get a match unless the user somehow decides to input "N" or "y" (i.e. either of the four characters, but enclosed in double quotes).

So you need either to remove " from around y, n, Y and N or put them around %INPUT% in your conditional statements. I would recommend the latter, because that way you would be escaping at least some of the characters that have special meaning in batch scripts (if the user managed to type them in). So, this is what you should get:

If "%INPUT%"=="y" goto yes 
If "%INPUT%"=="n" goto no
If "%INPUT%"=="Y" goto yes
If "%INPUT%"=="N" goto no

By the way, you could reduce the number of conditions by applying the /I switch to the IF statement, like this:

If /I "%INPUT%"=="y" goto yes 
If /I "%INPUT%"=="n" goto no

The /I switch makes the comparisons case-insensitive, and so you don't need separate checks for different-case strings.

One other issue is that, after the development mode command is executed, there's no jumping over the other command, and so, if the user agrees to run Java in the development mode, he'll get it run both in the development mode and the non-development mode. So maybe you need to add something like this to your script:

...
:yes
java -jar lib/RSBot-4030.jar -dev
echo Starting RSbot in developer mode
goto cont
:no
java -jar lib/RSBot-4030.jar
echo Starting RSbot in regular mode
:cont
pause

Finally, to address the issue of processing incorrect input, you could simply add another (unconditional) goto command just after the conditional statements, just before the yes label, namely goto Ask, to return to the beginning of your script where the prompt is displayed and the input is requested, or you could also add another ECHO command before the jump, explaining that the input was incorrect, something like this:

@echo off
:Ask
echo Would you like to use developer mode?(Y/N)
set INPUT=
set /P INPUT=Type input: %=%
If /I "%INPUT%"=="y" goto yes 
If /I "%INPUT%"=="n" goto no
echo Incorrect input & goto Ask
:yes
...

Note: Some of the issues mentioned here have also been addressed by @xmjx in their answer, which I fully acknowledge.

What is the difference between Release and Debug modes in Visual Studio?

Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.

As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

How to crop an image using C#?

Simpler than the accepted answer is this:

public static Bitmap cropAtRect(this Bitmap b, Rectangle r)
{
    Bitmap nb = new Bitmap(r.Width, r.Height);
    using (Graphics g = Graphics.FromImage(nb))
    {
        g.DrawImage(b, -r.X, -r.Y);
        return nb;
    }
}

and it avoids the "Out of memory" exception risk of the simplest answer.

Note that Bitmap and Graphics are IDisposable hence the using clauses.

EDIT: I find this is fine with PNGs saved by Bitmap.Save or Paint.exe, but fails with PNGs saved by e.g. Paint Shop Pro 6 - the content is displaced. Addition of GraphicsUnit.Pixel gives a different wrong result. Perhaps just these failing PNGs are faulty.

How to return a list of keys from a Hash Map?

Using map.keySet(), you can get a set of keys. Then convert this set into List by:

List<String> l = new ArrayList<String>(map.keySet());

And then use l.get(int) method to access keys.

PS:- source- Most concise way to convert a Set<String> to a List<String>

How to get distinct values from an array of objects in JavaScript?

Simple one-liner with great performance. 6% faster than the ES6 solutions in my tests.

var ages = array.map(function(o){return o.age}).filter(function(v,i,a) {
    return a.indexOf(v)===i
});

nginx: send all requests to a single html page

This worked for me:

location / {
    alias /path/to/my/indexfile/;
    try_files $uri /index.html;
}

This allowed me to create a catch-all URL for a javascript single-page app. All static files like css, fonts, and javascript built by npm run build will be found if they are in the same directory as index.html.

If the static files were in another directory, for some reason, you'd also need something like:

# Static pages generated by "npm run build"
location ~ ^/css/|^/fonts/|^/semantic/|^/static/ {
    alias /path/to/my/staticfiles/;
}

Make .gitignore ignore everything except a few files

A little more specific:

Example: Ignore everything in webroot/cache - but keep webroot/cache/.htaccess.

Notice the slash (/) after the cache folder:

FAILS

webroot/cache*
!webroot/cache/.htaccess

WORKS

webroot/cache/*
!webroot/cache/.htaccess

How to remove the querystring and get only the url?

You can use strtok to get string before first occurence of ?

$url = strtok($_SERVER["REQUEST_URI"], '?');

strtok() represents the most concise technique to directly extract the substring before the ? in the querystring. explode() is less direct because it must produce a potentially two-element array by which the first element must be accessed.

Some other techniques may break when the querystring is missing or potentially mutate other/unintended substrings in the url -- these techniques should be avoided.

A demonstration:

$urls = [
    'www.example.com/myurl.html?unwantedthngs#hastag',
    'www.example.com/myurl.html'
];

foreach ($urls as $url) {
    var_export(['strtok: ', strtok($url, '?')]);
    echo "\n";
    var_export(['strstr/true: ', strstr($url, '?', true)]); // not reliable
    echo "\n";
    var_export(['explode/2: ', explode('?', $url, 2)[0]]);  // limit allows func to stop searching after first encounter
    echo "\n";
    var_export(['substr/strrpos: ', substr($url, 0, strrpos( $url, "?"))]);  // not reliable; still not with strpos()
    echo "\n---\n";
}

Output:

array (
  0 => 'strtok: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'strstr/true: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'explode/2: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'substr/strrpos: ',
  1 => 'www.example.com/myurl.html',
)
---
array (
  0 => 'strtok: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'strstr/true: ',
  1 => false,                       // bad news
)
array (
  0 => 'explode/2: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'substr/strrpos: ',
  1 => '',                          // bad news
)
---

Could not find folder 'tools' inside SDK

If you install Eclipse properly then:

  1. Start Eclipse
  2. From the menu bar, select Window > Preferences > Android
  3. For Android location, browse the folder in which you install Android SDKs.
  4. In Android SDKs folder, rename the folder platforms-tools to tools.
  5. Select the folder Android SDKs through Preferences dialog box.

How does Python's super() work with multiple inheritance?

Consider calling super().Foo() called from a sub-class. The Method Resolution Order (MRO) method is the order in which method calls are resolved.

Case 1: Single Inheritance

In this, super().Foo() will be searched up in the hierarchy and will consider the closest implementation, if found, else raise an Exception. The "is a" relationship will always be True in between any visited sub-class and its super class up in the hierarchy. But this story isn't the same always in Multiple Inheritance.

Case 2: Multiple Inheritance

Here, while searching for super().Foo() implementation, every visited class in the hierarchy may or may not have is a relation. Consider following examples:

class A(object): pass
class B(object): pass
class C(A): pass
class D(A): pass
class E(C, D): pass
class F(B): pass
class G(B): pass
class H(F, G): pass
class I(E, H): pass

Here, I is the lowest class in the hierarchy. Hierarchy diagram and MRO for I will be

enter image description here

(Red numbers showing the MRO)

MRO is I E C D A H F G B object

Note that a class X will be visited only if all its sub-classes, which inherit from it, have been visited(i.e., you should never visit a class that has an arrow coming into it from a class below that you have not yet visited).

Here, note that after visiting class C , D is visited although C and D DO NOT have is a relationship between them(but both have with A). This is where super() differs from single inheritance.

Consider a slightly more complicated example:

enter image description here

(Red numbers showing the MRO)

MRO is I E C H D A F G B object

In this case we proceed from I to E to C. The next step up would be A, but we have yet to visit D, a subclass of A. We cannot visit D, however, because we have yet to visit H, a subclass of D. The leaves H as the next class to visit. Remember, we attempt to go up in hierarchy, if possible, so we visit its leftmost superclass, D. After D we visit A, but we cannot go up to object because we have yet to visit F, G, and B. These classes, in order, round out the MRO for I.

Note that no class can appear more than once in MRO.

This is how super() looks up in the hierarchy of inheritance.

Credits for resources: Richard L Halterman Fundamentals of Python Programming

Register 32 bit COM DLL to 64 bit Windows 7

If problem not resolved, when using SysWoW64 version of regsvr32, make sure all library dependencies have same archetecture. For example, when

regsvr32 lib_x86.dll fails to register library, and %SystemRoot%\SysWow64\regsvr32 lib_x86 also fails, try to load lib_x86 to Dependency Walker application to see whole list of dependencies. If any item have 64-bit archetecture, here is the reason, why regsvr32 fails to load 32-bit library.

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

What does the keyword "transient" mean in Java?

Google is your friend - first hit - also you might first have a look at what serialization is.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

Example from there, slightly modified (thanks @pgras):

public class Foo implements Serializable
 {
   private String saveMe;
   private transient String dontSaveMe;
   private transient String password;
   //...
 }

How can I get the last day of the month in C#?

Something like:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);

Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.

Undefined index error PHP

If you are using wamp server , then i recommend you to use xampp server . you . i get this error in less than i minute but i resolved this by using (isset) function . and i get no error . and after that i remove (isset) function and i don,t see any error.

by the way i am using xampp server

How can I list all of the files in a directory with Perl?

If you are a slacker like me you might like to use the File::Slurp module. The read_dir function will reads directory contents into an array, removes the dots, and if needed prefix the files returned with the dir for absolute paths

my @paths = read_dir( '/path/to/dir', prefix => 1 ) ;

Which MySQL data type to use for storing boolean values

BOOL and BOOLEAN are synonyms of TINYINT(1). Zero is false, anything else is true. More information here.

How can I convert a string to upper- or lower-case with XSLT?

In XSLT 1.0 the upper-case() and lower-case() functions are not available. If you're using a 1.0 stylesheet the common method of case conversion is translate():

<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />


<xsl:template match="/">
  <xsl:value-of select="translate(doc, $lowercase, $uppercase)" />
</xsl:template>

Detecting touch screen devices with Javascript

For my first post/comment: We all know that 'touchstart' is triggered before click. We also know that when user open your page he or she will: 1) move the mouse 2) click 3) touch the screen (for scrolling, or ... :) )

Let's try something :

//--> Start: jQuery

var hasTouchCapabilities = 'ontouchstart' in window && (navigator.maxTouchPoints || navigator.msMaxTouchPoints);
var isTouchDevice = hasTouchCapabilities ? 'maybe':'nope';

//attach a once called event handler to window

$(window).one('touchstart mousemove click',function(e){

    if ( isTouchDevice === 'maybe' && e.type === 'touchstart' )
        isTouchDevice = 'yes';
});

//<-- End: jQuery

Have a nice day!

How can I pad a value with leading zeros?

I used

Utilities.formatString("%04d", iThe_TWO_to_FOUR_DIGIT) 

which gives up to 4 leading 0s

NOTE: THIS REQUIRES Google's apps-script Utilities:

https://developers.google.com/apps-script/reference/utilities/utilities#formatstringtemplate-args

The ternary (conditional) operator in C

The fact that the ternary operator is an expression, not a statement, allows it to be used in macro expansions for function-like macros that are used as part of an expression. Const may not have been part of original C, but the macro pre-processor goes way back.

One place where I've seen it used is in an array package that used macros for bound-checked array accesses. The syntax for a checked reference was something like aref(arrayname, type, index), where arrayname was actually a pointer to a struct that included the array bounds and an unsigned char array for the data, type was the actual type of the data, and index was the index. The expansion of this was quite hairy (and I'm not going to do it from memory), but it used some ternary operators to do the bound checking.

You can't do this as a function call in C because of the need for polymorphism of the returned object. So a macro was needed to do the type casting in the expression. In C++ you could do this as a templated overloaded function call (probably for operator[]), but C doesn't have such features.

Edit: Here's the example I was talking about, from the Berkeley CAD array package (glu 1.4 edition). The documentation of the array_fetch usage is:

type
array_fetch(type, array, position)
typeof type;
array_t *array;
int position;

Fetch an element from an array. A runtime error occurs on an attempt to reference outside the bounds of the array. There is no type-checking that the value at the given position is actually of the type used when dereferencing the array.

and here is the macro defintion of array_fetch (note the use of the ternary operator and the comma sequencing operator to execute all the subexpressions with the right values in the right order as part of a single expression):

#define array_fetch(type, a, i)         \
(array_global_index = (i),              \
  (array_global_index >= (a)->num) ? array_abort((a),1) : 0,\
  *((type *) ((a)->space + array_global_index * (a)->obj_size)))

The expansion for array_insert ( which grows the array if necessary, like a C++ vector) is even hairier, involving multiple nested ternary operators.

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

Arrow functions => best ES6 feature so far. They are a tremendously powerful addition to ES6, that I use constantly.

Wait, you can't use arrow function everywhere in your code, its not going to work in all cases like this where arrow functions are not usable. Without a doubt, the arrow function is a great addition it brings code simplicity.

But you can’t use an arrow function when a dynamic context is required: defining methods, create objects with constructors, get the target from this when handling events.

Arrow functions should NOT be used because:

  1. They do not have this

    It uses “lexical scoping” to figure out what the value of “this” should be. In simple word lexical scoping it uses “this” from the inside the function’s body.

  2. They do not have arguments

    Arrow functions don’t have an arguments object. But the same functionality can be achieved using rest parameters.

    let sum = (...args) => args.reduce((x, y) => x + y, 0) sum(3, 3, 1) // output - 7 `

  3. They cannot be used with new

    Arrow functions can't be construtors because they do not have a prototype property.

When to use arrow function and when not:

  1. Don't use to add function as a property in object literal because we can not access this.
  2. Function expressions are best for object methods. Arrow functions are best for callbacks or methods like map, reduce, or forEach.
  3. Use function declarations for functions you’d call by name (because they’re hoisted).
  4. Use arrow functions for callbacks (because they tend to be terser).

How do I close a single buffer (out of many) in Vim?

Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville

I use:

"" Buffer Navigation                                                                                                                                                                                        
" Toggle left sidebar: NERDTree and BufferGator                                                                                                                                                             
fu! UiToggle()                                                                                                                                                                                              
  let b = bufnr("%")                                                                                                                                                                                        
  execute "NERDTreeToggle | BuffergatorToggle"                                                                                                                                                              
  execute ( bufwinnr(b) . "wincmd w" )                                                                                                                                                                      
  execute ":set number!"                                                                                                                                                                                    
endf                                                                                                                                                                                                        
map  <silent> <Leader>w  <esc>:call UiToggle()<cr>   

Where "NERDTreeToggle" in that list is the same as typing :NERDTreeToggle. You can modify this function to integrate with your own configuration.

Handling ExecuteScalar() when no results are returned

I have seen in VS2010 string getusername = command.ExecuteScalar(); gives compilation error, Cannot implicitly convert type object to string. So you need to write string getusername = command.ExecuteScalar().ToString(); when there is no record found in database it gives error Object reference not set to an instance of an object and when I comment '.ToString()', it is not give any error. So I can say ExecuteScalar not throw an exception. I think anserwer given by @Rune Grimstad is right.

Python Pandas Error tokenizing data

Issue could be with file Issues, In my case, Issue was solved after renaming the file. yet to figure out the reason..

ReferenceError: fetch is not defined

It seems fetch support URL scheme with "http" or "https" for CORS request.

Install node fetch library npm install node-fetch, read the file and parse to json.

const fs = require('fs')
const readJson = filename => {
  return new Promise((resolve, reject) => {
    if (filename.toLowerCase().endsWith(".json")) {
      fs.readFile(filename, (err, data) => {
        if (err) {
          reject(err)
          return
        }
        resolve(JSON.parse(data))
      })
    }
    else {
      reject(new Error("Invalid filetype, <*.json> required."))
      return
    }
  })
}

// usage
const filename = "../data.json"
readJson(filename).then(data => console.log(data)).catch(err => console.log(err.message))

Android: Clear Activity Stack

In my case, LoginActivity was closed as well. As a result,

Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK

did not help.

However, setting

Intent.FLAG_ACTIVITY_NEW_TASK

helped me.

Changing background color of ListView items on Android

You have to create a different state drawable for each color you want to use.

For example: list_selector_read.xml and list_selector_unread.xml.

All you need to do is set everything to transparent except the android:state_window_focused="false" item.

Then when you are drawing your list you call setBackgroundResource(R.drawable.list_selector_unread/read) for each row.

You don't set a listSelector on the ListView at all. That will maintain the default selector for your particular flavor of Android.

Is it possible to create a temporary table in a View and drop it after select?

Try creating another SQL view instead of a temporary table and then referencing it in the main SQL view. In other words, a view within a view. You can then drop the first view once you are done creating the main view.

How to make exe files from a node.js app?

There a few alternatives, both free and commercial. I haven't used any of them but in theory they should work:

Most will require you to keep the batch file as main executable, and then bundle node.exe and your scripts.

Depending on your script, you also have the option to port it to JSDB, which supports an easy way to create executables by simply appending resources to it.

A third quasi-solution is to keep node somewhere like C:\utils and add this folder to your PATH environment variable. Then you can create .bat files in that dir that run node + your preferred scripts - I got coffeescript's coffee working on windows this way. This setup can be automated with a batch file, vb script or installer.

Single quotes vs. double quotes in C or C++

Some compilers also implement an extension, that allows multi-character constants. The C99 standard says:

6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."

This could look like this, for instance:

const uint32_t png_ihdr = 'IHDR';

The resulting constant (in GCC, which implements this) has the value you get by taking each character and shifting it up, so that 'I' ends up in the most significant bits of the 32-bit value. Obviously, you shouldn't rely on this if you are writing platform independent code.

difference between width auto and width 100 percent

The initial width of a block level element like div or p is auto.

Use width:auto to undo explicitly specified widths.

if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border.

So, next time you find yourself setting the width of a block level element to 100% to make it occupy all available width, consider if what you really want is setting it to auto.

Setting table column width

Don't use the border attribute, use CSS for all your styling needs.

<table style="border:1px; width:100%;">
    <tr>
            <th style="width:15%;">From</th>
            <th style="width:70%;">Subject</th>
            <th style="width:15%;">Date</th>
    </tr>
... rest of the table code...
</table>

But embedding CSS like that is poor practice - one should use CSS classes instead, and put the CSS rules in an external CSS file.

Returning a stream from File.OpenRead()

You need

    str.CopyTo(data);
    data.Position = 0; // reset to beginning
    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);  

And since your Test() method is imitating the client it ought to Close() or Dispose() the str Stream. And the memoryStream too, just out of principal.

Solving "adb server version doesn't match this client" error

One possible reason for the occurrence of this error is due to the difference in adb versions in the development machine and the connected connected device/emulator being used for debugging.

So resolution is:

  1. Firstly disconnect device/emulator.
  2. Run on terminal/command prompt following commands:

    adb kill-server
    adb start-server
    

This will start the adb successfully. Now you can connect device. Hope it helps.

How to disable text selection using jQuery?

This can easily be done using JavaScript This is applicable to all Browsers

<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE 
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}
 </script>

Call to this function

<script type="text/javascript">
   disableSelection(document.body)
</script>

How to call a SOAP web service on Android

SOAP is an ill-suited technology for use on Android (or mobile devices in general) because of the processing/parsing overhead that's required. A REST services is a lighter weight solution and that's what I would suggest. Android comes with a SAX parser, and it's fairly trivial to use. If you are absolutely required to handle/parse SOAP on a mobile device then I feel sorry for you, the best advice I can offer is just not to use SOAP.

How to find a hash key containing a matching value

You can invert the hash. clients.invert["client_id"=>"2180"] returns "orange"

WHERE clause on SQL Server "Text" data type

That is not what the error message says. It says that you cannot use the = operator. Try for instance LIKE 'foo'.

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Add a UIView above all, even the navigation bar

Add you view as the subview of NavigationController.

[self.navigationController.navigationBar addSubview: overlayView)]

You can also add it over the window:

UIView *view = /* Your custom view */;
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[window addSubview:view];

Hope this helps.. :)

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

How to add two edit text fields in an alert dialog

I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.

But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here

How to use _CRT_SECURE_NO_WARNINGS

If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General

Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.

It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.

SDL checks in vs2012 and later

404 Not Found The requested URL was not found on this server

change this

Include conf/extra/httpd-vhosts.conf

to

#Include conf/extra/httpd-vhosts.conf

and restart all services

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

Bootstrap modal - close modal when "call to action" button is clicked

Make as shown.

_x000D_
_x000D_
  $(document).ready(function(){_x000D_
    $('#myModal').modal('show');_x000D_
_x000D_
    $('#myBtn').on('click', function(){_x000D_
      $('#myModal').modal('show');_x000D_
    });_x000D_
    _x000D_
  });_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Activate Modal with JavaScript</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert string to datetime format in pandas python?

Approach: 1

Given original string format: 2019/03/04 00:08:48

you can use

updated_df = df['timestamp'].astype('datetime64[ns]')

The result will be in this datetime format: 2019-03-04 00:08:48

Approach: 2

updated_df = df.astype({'timestamp':'datetime64[ns]'})

count of entries in data frame in R

You could use table:

R> x <- read.table(textConnection('
   Believe Age Gender Presents Behaviour
1    FALSE   9   male       25   naughty
2     TRUE   5   male       20      nice
3     TRUE   4 female       30      nice
4     TRUE   4   male       34   naughty'
), header=TRUE)

R> table(x$Believe)

FALSE  TRUE 
    1     3 

Postgres: check if array field contains value?

This worked for me:

select * from mytable
where array_to_string(pub_types, ',') like '%Journal%'

Depending on your normalization needs, it might be better to implement a separate table with a FK reference as you may get better performance and manageability.

Google Maps V3 - How to calculate the zoom level for a given bounds

A similar question has been asked on the Google group: http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/e6448fc197c3c892

The zoom levels are discrete, with the scale doubling in each step. So in general you cannot fit the bounds you want exactly (unless you are very lucky with the particular map size).

Another issue is the ratio between side lengths e.g. you cannot fit the bounds exactly to a thin rectangle inside a square map.

There's no easy answer for how to fit exact bounds, because even if you are willing to change the size of the map div, you have to choose which size and corresponding zoom level you change to (roughly speaking, do you make it larger or smaller than it currently is?).

If you really need to calculate the zoom, rather than store it, this should do the trick:

The Mercator projection warps latitude, but any difference in longitude always represents the same fraction of the width of the map (the angle difference in degrees / 360). At zoom zero, the whole world map is 256x256 pixels, and zooming each level doubles both width and height. So after a little algebra we can calculate the zoom as follows, provided we know the map's width in pixels. Note that because longitude wraps around, we have to make sure the angle is positive.

var GLOBE_WIDTH = 256; // a constant in Google's map projection
var west = sw.lng();
var east = ne.lng();
var angle = east - west;
if (angle < 0) {
  angle += 360;
}
var zoom = Math.round(Math.log(pixelWidth * 360 / angle / GLOBE_WIDTH) / Math.LN2);

Duplicate AssemblyVersion Attribute

This usually happens for me if I compiled the project in Visual Studio 2017 & then I try to rebuild & run it with .NET Core with the command line command "dotnet run".

Simply deleting all the "bin" & "obj" folders - both inside "ClientApp" & directly in the project folder - allowed the .NET Core command "dotnet run" to rebuild & run successfully.

How to quickly and conveniently disable all console.log statements in my code?

I wrote this:

//Make a copy of the old console.
var oldConsole = Object.assign({}, console);

//This function redefine the caller with the original one. (well, at least i expect this to work in chrome, not tested in others)
function setEnabled(bool) {
    if (bool) {
        //Rewrites the disable function with the original one.
        console[this.name] = oldConsole[this.name];
        //Make sure the setEnable will be callable from original one.
        console[this.name].setEnabled = setEnabled;
    } else {
        //Rewrites the original.
        var fn = function () {/*function disabled, to enable call console.fn.setEnabled(true)*/};
        //Defines the name, to remember.
        Object.defineProperty(fn, "name", {value: this.name});
        //replace the original with the empty one.
        console[this.name] = fn;
        //set the enable function
        console[this.name].setEnabled = setEnabled

    }
}

Unfortunately it doesn't work on use strict mode.

So using console.fn.setEnabled = setEnabled and then console.fn.setEnabled(false) where fn could be almost any console function. For your case would be:

console.log.setEnabled = setEnabled;
console.log.setEnabled(false);

I wrote this too:

var FLAGS = {};
    FLAGS.DEBUG = true;
    FLAGS.INFO = false;
    FLAGS.LOG = false;
    //Adding dir, table, or other would put the setEnabled on the respective console functions.

function makeThemSwitchable(opt) {
    var keysArr = Object.keys(opt);
    //its better use this type of for.
    for (var x = 0; x < keysArr.length; x++) {
        var key = keysArr[x];
        var lowerKey = key.toLowerCase();
        //Only if the key exists
        if (console[lowerKey]) {
            //define the function
            console[lowerKey].setEnabled = setEnabled;
            //Make it enabled/disabled by key.
            console[lowerKey].setEnabled(opt[key]);
        }
    }
}
//Put the set enabled function on the original console using the defined flags and set them.
makeThemSwitchable(FLAGS);

so then you just need to put in the FLAGS the default value (before execute the above code), like FLAGS.LOG = false and the log function would be disabled by default, and still you could enabled it calling console.log.setEnabled(true)

"Eliminate render-blocking CSS in above-the-fold content"

Hi For jQuery You can only use like this

Use async and type="text/javascript" only

Export to csv in jQuery

I recently posted a free software library for this: "html5csv.js" -- GitHub

It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.

After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:

CSV.begin('#PrintDiv').download('MyData.csv').go();

Here is a JSFiddle demo of your example with this code.

Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE

The CSV.begin() call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download() generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.

According to caniuse IE10 doesn't support <a download=...>. So for IE my library calls navigator.msSaveBlob() internally, as suggested by @Manu Sharma

How to edit an Android app?

You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.

You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.

If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.

In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.

Moving Average Pandas

In case you are calculating more than one moving average:

for i in range(2,10):
   df['MA{}'.format(i)] = df.rolling(window=i).mean()

Then you can do an aggregate average of all the MA

df[[f for f in list(df) if "MA" in f]].mean(axis=1)

iOS 8 UITableView separator inset 0 not working

My solution is adding an UIView as a container for the cell subviews. Then set this UIView constraints (top,bottom,trailing,leading) to 0 points. And all the unnecessary mass go away.the image showing the logic

Need to find a max of three numbers in java

It would help if you provided the error you are seeing. Look at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html and you will see that max only returns the max between two numbers, so likely you code is not even compiling.

Solve all your compilation errors first.

Then your homework will consist of finding the max of three numbers by comparing the first two together, and comparing that max result with the third value. You should have enough to find your answer now.

List<object>.RemoveAll - How to create an appropriate Predicate

A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.

{
    List<Vehicle> vehicles;
    // Using a lambda
    vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
    // Using an equivalent anonymous method
    vehicles.RemoveAll(delegate(Vehicle vehicle)
    {
        return vehicle.EnquiryID == 123;
    });
    // Using an equivalent actual method
    vehicles.RemoveAll(VehiclePredicate);
}

private static bool VehiclePredicate(Vehicle vehicle)
{
    return vehicle.EnquiryID == 123;
}

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Application Crashes With "Internal Error In The .NET Runtime"

I've experienced "internal errors" in the .NET runtime that turned out to be caused by bugs in my code; don't think that just because it was an "internal error" in the .NET runtime that there isn't a bug in your code as the root cause. Always always always blame your own code before you blame someone else's.

Hopefully you have logging and exception/stack trace information to point you where to start looking, or that you can repeat the state of the system before the crash.

Proper way of checking if row exists in table in PL/SQL block

You can do EXISTS in Oracle PL/SQL.

You can do the following:

DECLARE
    n_rowExist NUMBER := 0;
BEGIN
    SELECT CASE WHEN EXISTS (
      SELECT 1
      FROM person
      WHERE ID = 10
    ) THEN 1 ELSE 0 INTO n_rowExist END FROM DUAL;
    
    IF n_rowExist = 1 THEN
       -- do things when it exists
    ELSE
       -- do things when it doesn't exist
    END IF;

END;
/

Explanation:

In the query nested where it starts with SELECT CASE WHEN EXISTS and after the parenthesis (SELECT 1 FROM person WHERE ID = 10) it will return a result if it finds a person of ID of 10. If the there's a result on the query then it will assign the value of 1 otherwise it will assign the value of 0 to n_rowExist variable. Afterwards, the if statement checks if the value returned equals to 1 then is true otherwise it will be 0 = 1 and that is false.

OSError [Errno 22] invalid argument when use open() in Python

Just replace with "/" for file path :

   open("description_files/program_description.txt","r")

How to get a user's time zone?

func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let gmtAbbreviation = (localTimeZoneAbbreviation / 60)
        return "\(gmtAbbreviation)"
}

You can get current time zone abbreviation.

Add leading zeroes to number in Java?

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3

How to get previous page url using jquery

    $(document).ready(function() {
               var referrer =  document.referrer;

               if(referrer.equals("Setting.jsp")){                     
                   function goBack() {  
                        window.history.go();                            
                    }
               }  
                   if(referrer.equals("http://localhost:8080/Ads/Terms.jsp")){                     
                        window.history.forward();
                        function noBack() {
                        window.history.forward(); 
                    }
                   }
    }); 

using this you can avoid load previous page load

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
    {
        return null;
    }

Then when you click on the button -

enter image description here

How to redirect to previous page in Ruby On Rails?

This is how we do it in our application

def store_location
  session[:return_to] = request.fullpath if request.get? and controller_name != "user_sessions" and controller_name != "sessions"
end

def redirect_back_or_default(default)
  redirect_to(session[:return_to] || default)
end

This way you only store last GET request in :return_to session param, so all forms, even when multiple time POSTed would work with :return_to.

Is Python strongly typed?

class testme(object):
    ''' A test object '''
    def __init__(self):
        self.y = 0

def f(aTestMe1, aTestMe2):
    return aTestMe1.y + aTestMe2.y




c = testme            #get a variable to the class
c.x = 10              #add an attribute x inital value 10
c.y = 4               #change the default attribute value of y to 4

t = testme()          # declare t to be an instance object of testme
r = testme()          # declare r to be an instance object of testme

t.y = 6               # set t.y to a number
r.y = 7               # set r.y to a number

print(f(r,t))         # call function designed to operate on testme objects

r.y = "I am r.y"      # redefine r.y to be a string

print(f(r,t))         #POW!!!!  not good....

The above would create a nightmare of unmaintainable code in a large system over a long period time. Call it what you want, but the ability to "dynamically" change a variables type is just a bad idea...

How to check if type of a variable is string?

In Python 2.x, you would do

isinstance(s, basestring)

basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode.


In Python 3.x, the correct test is

isinstance(s, str)

The bytes class isn't considered a string type in Python 3.

How can I change default dialog button text color in android 5

Here's a natural way to do it with styles:

If your AppTheme is inherited from Theme.MaterialComponents, then:

<style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>

<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">#f00</item>
</style>

<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">#00f</item>
</style>

If your AppTheme is inherited from Theme.AppCompat:

<style name="AlertDialogTheme" parent="ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>

<style name="NegativeButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">#f00</item>
</style>

<style name="PositiveButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">#00f</item>
</style>

Use your AlertDialogTheme in your AppTheme

<item name="alertDialogTheme">@style/AlertDialogTheme</item>

or in constructor

androidx.appcompat.app.AlertDialog.Builder(context, R.style.AlertDialogTheme)

Possible to make labels appear when hovering over a point in matplotlib?

mplcursors worked for me. mplcursors provides clickable annotation for matplotlib. It is heavily inspired from mpldatacursor (https://github.com/joferkington/mpldatacursor), with a much simplified API

import matplotlib.pyplot as plt
import numpy as np
import mplcursors

data = np.outer(range(10), range(1, 5))

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
             "Annotations can be dragged.")

mplcursors.cursor(lines) # or just mplcursors.cursor()

plt.show()

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

How to retrieve the LoaderException property?

try
{
  // load the assembly or type
}
catch (Exception ex)
{
  if (ex is System.Reflection.ReflectionTypeLoadException)
  {
    var typeLoadException = ex as ReflectionTypeLoadException;
    var loaderExceptions  = typeLoadException.LoaderExceptions;
  }
}

CodeIgniter 404 Page Not Found, but why?

The cause of the problem was that the server was running PHP using FastCGI.

After changing the config.php to

$config['uri_protocol'] = "REQUEST_URI";

everything worked.

Need to list all triggers in SQL Server database with table name and table's schema

One difficulty is that the text, or description has line feeds. My clumsy kludge, to get it in something more tabular, is to add an HTML literal to the SELECT clause, copy and paste everything to notepad, save with an html extension, open in a browser, then copy and paste to a spreadsheet. example

SELECT obj.NAME AS TBL,trg.name,sm.definition,'<br>'
FROM SYS.OBJECTS obj
LEFT JOIN (SELECT trg1.object_id,trg1.parent_object_id,trg1.name FROM sys.objects trg1 WHERE trg1.type='tr' AND trg1.name like 'update%') trg
 ON obj.object_id=trg.parent_object_id
LEFT JOIN (SELECT sm1.object_id,sm1.definition FROM sys.sql_modules sm1 where sm1.definition like '%suser_sname()%') sm ON trg.object_id=sm.object_id
WHERE obj.type='u'
ORDER BY obj.name;

you may still need to fool around with tabs to get the description into one field, but at least it'll be on one line, which I find very helpful.

"Proxy server connection failed" in google chrome

Try following these steps:

  1. Run Chrome as Administrator.
  2. Go to the settings in Chrome.
  3. Go to Advanced Settings (its all the way down).
  4. Scroll to Network Section and click on ''Change proxy settings''.
  5. A window will pop up with the name ''Internet Properties''
  6. Click on ''LAN settings''
  7. Un-check ''Use a proxy server for your LAN''
  8. Check ''Automatically detect settings''
  9. Click everything ''OK'' and you are done!

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

The developers of this app have not set up this app properly for Facebook Login?

do setup by following bellow link and domain name you need to mention as like wht you have mentioned in facebook app domain name.

Go to https://developers.facebook.com/

Click on the Apps menu on the top bar.

Javascript array value is undefined ... how do I test for that

There are more (many) ways to Rome:

//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null

cheers!

Regular expression to match balanced parentheses

You need the first and last parentheses. Use something like this:

str.indexOf('('); - it will give you first occurrence

str.lastIndexOf(')'); - last one

So you need a string between,

String searchedString = str.substring(str1.indexOf('('),str1.lastIndexOf(')');

How do you round UP a number in Python?

Interesting Python 2.x issue to keep in mind:

>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.0

The problem is that dividing two ints in python produces another int and that's truncated before the ceiling call. You have to make one value a float (or cast) to get a correct result.

In javascript, the exact same code produces a different result:

console.log(Math.ceil(4500/1000));
5

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

SQL Left Join first match only

After careful consideration this dillema has a few different solutions:

Aggregate Everything Use an aggregate on each column to get the biggest or smallest field value. This is what I am doing since it takes 2 partially filled out records and "merges" the data.

http://sqlfiddle.com/#!3/59cde/1

SELECT
  UPPER(IDNo) AS user_id
, MAX(FirstName) AS name_first
, MAX(LastName) AS name_last
, MAX(entry) AS row_num
FROM people P
GROUP BY 
  IDNo

Get First (or Last record)

http://sqlfiddle.com/#!3/59cde/23

-- ------------------------------------------------------
-- Notes
-- entry: Auto-Number primary key some sort of unique PK is required for this method
-- IDNo:  Should be primary key in feed, but is not, we are making an upper case version
-- This gets the first entry to get last entry, change MIN() to MAX()
-- ------------------------------------------------------

SELECT 
   PC.user_id
  ,PData.FirstName
  ,PData.LastName
  ,PData.entry
FROM (
  SELECT 
      P2.user_id
     ,MIN(P2.entry) AS rownum
  FROM (
    SELECT
        UPPER(P.IDNo) AS user_id 
      , P.entry 
    FROM people P
  ) AS P2
  GROUP BY 
    P2.user_id
) AS PC
LEFT JOIN people PData
ON PData.entry = PC.rownum
ORDER BY 
   PData.entry

In Go's http package, how do I get the query string on a POST request?

Below words come from the official document.

Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

func parseRequest(req *http.Request) error {
    var err error

    if err = req.ParseForm(); err != nil {
        log.Error("Error parsing form: %s", err)
        return err
    }

    _ = req.Form.Get("xxx")

    return nil
}

What is the difference between MVC and MVVM?

It surprises me that this is a highly voted answers without mentioning the origin of MVVM. MVVM is a popular term used in Microsoft community and it is originated from Martin Fowler's Presentation Model. So to understand the motive of the pattern and the differences with others, the original article about the pattern is the first thing to read.

Are there .NET implementation of TLS 1.2?

The latest version of SSPI (bundled with Windows 7) has an implementation of TLS 1.2, which can be found in schannel.dll

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

How can I convert a date into an integer?

Here what you can try:

var d = Date.parse("2016-07-19T20:23:01.804Z");
alert(d); //this is in milliseconds

Do you have to put Task.Run in a method to make it async?

First, let's clear up some terminology: "asynchronous" (async) means that it may yield control back to the calling thread before it starts. In an async method, those "yield" points are await expressions.

This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".

To futher confuse the issue, async is very different than "awaitable"; there are some async methods whose return types are not awaitable, and many methods returning awaitable types that are not async.

Enough about what they aren't; here's what they are:

  • The async keyword allows an asynchronous method (that is, it allows await expressions). async methods may return Task, Task<T>, or (if you must) void.
  • Any type that follows a certain pattern can be awaitable. The most common awaitable types are Task and Task<T>.

So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run:

private Task<int> DoWorkAsync() // No async because the method does not need await
{
  return Task.Run(() =>
  {
    return 1 + 2;
  });
}

(But this pattern is a poor approach; see below).

But if your question is "how do I create an async method that can yield back to its caller instead of blocking", the answer is to declare the method async and use await for its "yielding" points:

private async Task<int> GetWebPageHtmlSizeAsync()
{
  var client = new HttpClient();
  var html = await client.GetAsync("http://www.example.com/");
  return html.Length;
}

So, the basic pattern of things is to have async code depend on "awaitables" in its await expressions. These "awaitables" can be other async methods or just regular methods returning awaitables. Regular methods returning Task/Task<T> can use Task.Run to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T> or one of its shortcuts (TaskFactory.FromAsync, Task.FromResult, etc). I don't recommend wrapping an entire method in Task.Run; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run:

private int DoWork()
{
  return 1 + 2;
}

private void MoreSynchronousProcessing()
{
  // Execute it directly (synchronously), since we are also a synchronous method.
  var result = DoWork();
  ...
}

private async Task DoVariousThingsFromTheUIThreadAsync()
{
  // I have a bunch of async work to do, and I am executed on the UI thread.
  var result = await Task.Run(() => DoWork());
  ...
}

I have an async/await intro on my blog; at the end are some good followup resources. The MSDN docs for async are unusually good, too.

For loop example in MySQL

You can exchange this local variable for a global, it would be easier.

DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      SET @a = 0;
      simple_loop: LOOP
         SET @a=@a+1;
         select @a;
         IF @a=5 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

How do I fit an image (img) inside a div and keep the aspect ratio?

HTML

<div>
    <img src="something.jpg" alt="" />
</div>

CSS

div {
   width: 48px;
   height: 48px;
}

div img {
   display: block;
   width: 100%;
}

This will make the image expand to fill its parent, of which its size is set in the div CSS.

AngularJS : Factory and Service?

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory)

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.

Reference

Linux: Which process is causing "device busy" when doing umount?

Check for open loop devices mapped to a file on the filesystem with "losetup -a". They wont show up with either lsof or fuser.

Import python package from local directory into interpreter

Using sys.path should include current directory already.

Try:

import .

or:

from . import sth

however it may be not a good practice, so why not just use:

import mypackage

Change div height on button click

Do this:

function changeHeight() {
document.getElementById('chartdiv').style.height = "200px"
}
<button type="button" onClick="changeHeight();"> Click Me!</button>

Bootstrap 3 - How to load content in modal body via AJAX?

create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.

 $.ajax({url: "registration.html", success: function(result){
            //alert("success"+result);
              $("#contentBody").html(result);
            $("#myModal").modal('show'); 

        }});

once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.

You can call controller and get the page content and you can show that in your modal.

below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...

index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script type="text/javascript">
function loadme(){
    //alert("loadig");

    $.ajax({url: "registration.html", success: function(result){
        //alert("success"+result);
          $("#contentBody").html(result);
        $("#myModal").modal('show'); 

    }});
}
</script>
</head>
<body>

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>


<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content" >
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body" id="contentBody">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

</body>
</html>

registration.html
-------------------- 
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}

form {
    border: 3px solid #f1f1f1;
    font-family: Arial;
}

.container {
    padding: 20px;
    background-color: #f1f1f1;
    width: 560px;
}

input[type=text], input[type=submit] {
    width: 100%;
    padding: 12px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

input[type=checkbox] {
    margin-top: 16px;
}

input[type=submit] {
    background-color: #4CAF50;
    color: white;
    border: none;
}

input[type=submit]:hover {
    opacity: 0.8;
}
</style>
<body>

<h2>CSS Newsletter</h2>

<form action="/action_page.php">
  <div class="container">
    <h2>Subscribe to our Newsletter</h2>
    <p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
  </div>

  <div class="container" style="background-color:white">
    <input type="text" placeholder="Name" name="name" required>
    <input type="text" placeholder="Email address" name="mail" required>
    <label>
      <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
    </label>
  </div>

  <div class="container">
    <input type="submit" value="Subscribe">
  </div>
</form>

</body>
</html>

Postgres: INSERT if does not exist already

If you say that many of your rows are identical you will end checking many times. You can send them and the database will determine if insert it or not with the ON CONFLICT clause as follows

  INSERT INTO Hundred (name,name_slug,status) VALUES ("sql_string += hundred  
  +",'" + hundred_slug + "', " + status + ") ON CONFLICT ON CONSTRAINT
  hundred_pkey DO NOTHING;" cursor.execute(sql_string);

Remove an entire column from a data.frame in R

There are several options for removing one or more columns with dplyr::select() and some helper functions. The helper functions can be useful because some do not require naming all the specific columns to be dropped. Note that to drop columns using select() you need to use a leading - to negate the column names.

Using the dplyr::starwars sample data for some variety in column names:

library(dplyr)

starwars %>% 
  select(-height) %>%                  # a specific column name
  select(-one_of('mass', 'films')) %>% # any columns named in one_of()
  select(-(name:hair_color)) %>%       # the range of columns from 'name' to 'hair_color'
  select(-contains('color')) %>%       # any column name that contains 'color'
  select(-starts_with('bi')) %>%       # any column name that starts with 'bi'
  select(-ends_with('er')) %>%         # any column name that ends with 'er'
  select(-matches('^v.+s$')) %>%       # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%          # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

You can also drop by column number:

starwars %>% 
  select(-2, -(4:10)) # column 2 and columns 4 through 10

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

React Native Change Default iOS Simulator Device

There are multiple ways to achieve this:

  1. By using --simulator flag
  2. By using --udid flag

Firstly you need to list all the available devices. To list all the devices run

xcrun simctl list device

This will give output as follows:

These are the available devices for iOS 13.0 onwards:

== Devices ==
-- iOS 13.6 --
    iPhone 8 (5C7EF61D-6080-4065-9C6C-B213634408F2) (Shutdown) 
    iPhone 8 Plus (5A694E28-EF4D-4CDD-85DD-640764CAA25B) (Shutdown) 
    iPhone 11 (D6820D3A-875F-4CE0-B907-DAA060F60440) (Shutdown) 
    iPhone 11 Pro (B452E7A1-F21C-430E-98F0-B02F0C1065E1) (Shutdown) 
    iPhone 11 Pro Max (94973B5E-D986-44B1-8A80-116D1C54665B) (Shutdown) 
    iPhone SE (2nd generation) (90953319-BF9A-4C6E-8AB1-594394AD26CE) (Booted) 
    iPad Pro (9.7-inch) (9247BC07-00DB-4673-A353-46184F0B244E) (Shutdown) 
    iPad (7th generation) (3D5B855D-9093-453B-81EB-B45B7DBF0ADF) (Shutdown) 
    iPad Pro (11-inch) (2nd generation) (B3AA4C36-BFB9-4ED8-BF5A-E37CA38394F8) (Shutdown) 
    iPad Pro (12.9-inch) (4th generation) (DBC7B524-9C75-4C61-A568-B94DA0A9BCC4) (Shutdown) 
    iPad Air (3rd generation) (03E3FE18-AB46-481E-80A0-D37383ADCC2C) (Shutdown) 
-- tvOS 13.4 --
    Apple TV (41579EEC-0E68-4D36-9F98-5822CD1A4104) (Shutdown) 
    Apple TV 4K (B168EF40-F2A4-4A91-B4B0-1F541201479B) (Shutdown) 
    Apple TV 4K (at 1080p) (D55F9086-A56E-4893-ACAD-579FB63C561E) (Shutdown) 
-- watchOS 6.2 --
    Apple Watch Series 4 - 40mm (D4BA8A57-F9C1-4F55-B3E0-6042BA7C4ED4) (Shutdown) 
    Apple Watch Series 4 - 44mm (65D5593D-29B9-42CD-9417-FFDBAE9AED87) (Shutdown) 
    Apple Watch Series 5 - 40mm (1B73F8CC-9ECB-4018-A212-EED508A68AE3) (Shutdown) 
    Apple Watch Series 5 - 44mm (5922489B-5CF9-42CD-ACB0-B11FAF88562F) (Shutdown) 

Then from the output you can select the name or the uuid then proceed as you wish.

  1. To run using --simulator run:
npx react-native run-ios --simulator="iPhone SE"
  1. To run using --udid flag run:
npx react-native run-ios --udid 90953319-BF9A-4C6E-8AB1-594394AD26CE

I hope this answer helped you.

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

/usr/bin/codesign failed with exit code 1

Another reason, Check your Developer account is connected with xCode

enter image description here

How to convert entire dataframe to numeric while preserving decimals?

df2 <- data.frame(apply(df1, 2, function(x) as.numeric(as.character(x))))

Find objects between two dates MongoDB

Querying for a Date Range (Specific Month or Day) in the MongoDB Cookbook has a very good explanation on the matter, but below is something I tried out myself and it seems to work.

items.save({
    name: "example",
    created_at: ISODate("2010-04-30T00:00:00.000Z")
})
items.find({
    created_at: {
        $gte: ISODate("2010-04-29T00:00:00.000Z"),
        $lt: ISODate("2010-05-01T00:00:00.000Z")
    }
})
=> { "_id" : ObjectId("4c0791e2b9ec877893f3363b"), "name" : "example", "created_at" : "Sun May 30 2010 00:00:00 GMT+0300 (EEST)" }

Based on my experiments you will need to serialize your dates into a format that MongoDB supports, because the following gave undesired search results.

items.save({
    name: "example",
    created_at: "Sun May 30 18.49:00 +0000 2010"
})
items.find({
    created_at: {
        $gte:"Mon May 30 18:47:00 +0000 2015",
        $lt: "Sun May 30 20:40:36 +0000 2010"
    }
})
=> { "_id" : ObjectId("4c079123b9ec877893f33638"), "name" : "example", "created_at" : "Sun May 30 18.49:00 +0000 2010" }

In the second example no results were expected, but there was still one gotten. This is because a basic string comparison is done.

Start an external application from a Google Chrome Extension?

I go for hypothesys since I can't verify now.

With Apache, if you make a php script on your local machine calling your executable, and then call this script via POST or GET via html/javascript?

would it function?

let me know.

Validate date in dd/mm/yyyy format using JQuery Validate

If you use the moment js library it can easily be done like this -

jQuery.validator.addMethod("validDate", function(value, element) {
        return this.optional(element) || moment(value,"DD/MM/YYYY").isValid();
    }, "Please enter a valid date in the format DD/MM/YYYY");

How do I know which version of Javascript I'm using?

JavaScript 1.2 was introduced with Netscape Navigator 4 in 1997. That version number only ever had significance for Netscape browsers. For example, Microsoft's implementation (as used in Internet Explorer) is called JScript, and has its own version numbering which bears no relation to Netscape's numbering.

How to join three table by laravel eloquent model

Try:

$articles = DB::table('articles')
            ->select('articles.id as articles_id', ..... )
            ->join('categories', 'articles.categories_id', '=', 'categories.id')
            ->join('users', 'articles.user_id', '=', 'user.id')

            ->get();

Angular 6: saving data to local storage

you can use localStorage for storing the json data:

the example is given below:-

let JSONDatas = [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    {"id": "ZoomIn", "label": "Zoom In"},
    {"id": "ZoomOut", "label": "Zoom Out"},
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"}
]

localStorage.setItem("datas", JSON.stringify(JSONDatas));

let data = JSON.parse(localStorage.getItem("datas"));

console.log(data);

How to extract custom header value in Web API message handler?

One line solution

var id = request.Headers.GetValues("MyCustomID").FirstOrDefault();

What are NR and FNR and what does "NR==FNR" imply?

Look for keys (first word of line) in file2 that are also in file1.
Step 1: fill array a with the first words of file 1:

awk '{a[$1];}' file1

Step 2: Fill array a and ignore file 2 in the same command. For this check the total number of records until now with the number of the current input file.

awk 'NR==FNR{a[$1]}' file1 file2

Step 3: Ignore actions that might come after } when parsing file 1

awk 'NR==FNR{a[$1];next}' file1 file2 

Step 4: print key of file2 when found in the array a

awk 'NR==FNR{a[$1];next} $1 in a{print $1}' file1 file2

How can I install Python's pip3 on my Mac?

I solved the same problem with these commands:

curl -O https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py

How to make links in a TextView clickable?

You need only this:

android:autoLink="web"

Insert this line to TextView, that can be clickable with reference to the web. URL address set as a text of this TextView.

Example:

 <TextView
    android:id="@+id/textViewWikiURL"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textStyle="bold"
    android:text="http://www.wikipedia.org/"
    android:autoLink="web" />

Function in JavaScript that can be called only once

try this

var fun = (function() {
  var called = false;
  return function() {
    if (!called) {
      console.log("I  called");
      called = true;
    }
  }
})()

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

> is not in the documentation.

< is for one-way binding.

@ binding is for passing strings. These strings support {{}} expressions for interpolated values.

= binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope.

& binding is for passing a method into your directive's scope so that it can be called within your directive.

When we are setting scope: true in directive, Angular js will create a new scope for that directive. That means any changes made to the directive scope will not reflect back in parent controller.

How to manually update datatables table with new JSON data

In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).

My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null, for example).

Then I instantiate my table in the on load method

$(function () {
            //.... some code here
            table = $("#detailReportTable").DataTable();
            .... more code here
        });

and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:

function getOrderDetail() {
            table.clear();
            table.destroy();
            ...
            $.ajax({
             //.....api call here
            });
            ....
            table = $("#detailReportTable").DataTable();
   }

I hope someone finds this useful!

Drop data frame columns by name

Another solution if you don't want to use @hadley's above: If "COLUMN_NAME" is the name of the column you want to drop:

df[,-which(names(df) == "COLUMN_NAME")]

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I had this issue when working with Django, I use brew to install a lot of my Open Source programs and I needed to do the following since I used brew to install mysql:

sudo ln -s /usr/local/Cellar/mysql/5.5.20/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Be sure to replace with your version of the libraries!

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Oracle query to fetch column names

The query to use with Oracle is:

String sqlStr="select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='"+_db+".users' and COLUMN_NAME not in ('password','version','id')"

Never heard of HQL for such queries. I assume it doesn't make sense for ORM implementations to deal with it. ORM is an Object Relational Mapping, and what you're looking for is metadata mapping... You wouldn't use HQL, rather use API methods for this purpose, or direct SQL. For instance, you can use JDBC DatabaseMetaData.

I think tablespace has nothing to do with schema. AFAIK tablespaces are mainly used for logical internal technical purposes which should bother DBAs. For more information regarding tablespaces, see Oracle doc.

How to embed a video into GitHub README.md?

just to extend @GabLeRoux's answer:

[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)

this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.

Exists Angularjs code/naming conventions?

Update : STYLE GUIDE is now on Angular docs.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

If you are looking for an opinionated style guide for syntax, conventions, and structuring AngularJS applications, then step right in. The styles contained here are based on my experience with AngularJS, presentations, training courses and working in teams.

The purpose of this style guide is to provide guidance on building AngularJS applications by showing the conventions I use and, more importantly, why I choose them.

- John Papa

Here is the Awesome Link (Latest and Up-to-date) : AngularJS Style Guide

Install specific version using laravel installer

use laravel new blog --5.1
make sure you must have laravel installer 1.3.4 version.

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

That's how I would handle different images (sizes and proportions) in a flexible grid.

_x000D_
_x000D_
.images {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  margin: -20px;_x000D_
}_x000D_
_x000D_
.imagewrapper {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  width: calc(50% - 20px);_x000D_
  height: 300px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.image {_x000D_
  display: block;_x000D_
  object-fit: cover;_x000D_
  width: 100%;_x000D_
  height: 100%; /* set to 'auto' in IE11 to avoid distortions */_x000D_
}
_x000D_
<div class="images">_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/800x600" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1024x768" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1000x800" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/500x800" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/800x600" />_x000D_
  </div>_x000D_
  <div class="imagewrapper">_x000D_
    <img class="image" src="https://via.placeholder.com/1024x768" />_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make (link)button function as hyperlink?

There is a middle way. If you want a HTML control but you need to access it server side you can simply add the runat="server" attribute:

<a runat="server" Id="lnkBack">Back</a>

You can then alter the href server side using Attributes

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       lnkBack.Attributes.Add("href", url);
    }
}

resulting in:

<a id="ctl00_ctl00_mainContentPlaceHolder_contentPlaceHolder_lnkBack" 
      href="url.aspx">Back</a>

How to get CRON to call in the correct PATHs

Adding a PATH definition into the user crontab with correct values will help... I've filled mine with this line on top (after comments, and before cron jobs):

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

And it's enough to get all my scripts working... Include any custom path there if you need to.

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

Change selected value of kendo ui dropdownlist

Seems there's an easier way, at least in Kendo UI v2015.2.624:

$('#myDropDownSelector').data('kendoDropDownList').search('Text value to find');

If there's not a match in the dropdown, Kendo appears to set the dropdown to an unselected value, which makes sense.


I couldn't get @Gang's answer to work, but if you swap his value with search, as above, we're golden.

How to save .xlsx data to file as a blob

The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data.

Here's what I did on the server side (asp.net mvc core):

string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);

On the client side, I did the following code:

const xhr = new XMLHttpRequest();

xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");

xhr.onload = () => {
    var bin = atob(xhr.response);
    var ab = s2ab(bin); // from example above
    var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });

    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'demo.xlsx';

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
};

xhr.send();

And it works perfectly for me.

How do I perform the SQL Join equivalent in MongoDB?

This page on the official mongodb site addresses exactly this question:

https://mongodb-documentation.readthedocs.io/en/latest/ecosystem/tutorial/model-data-for-ruby-on-rails.html

When we display our list of stories, we'll need to show the name of the user who posted the story. If we were using a relational database, we could perform a join on users and stores, and get all our objects in a single query. But MongoDB does not support joins and so, at times, requires bit of denormalization. Here, this means caching the 'username' attribute.

Relational purists may be feeling uneasy already, as if we were violating some universal law. But let’s bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole. In the case of a social news site, it can be argued that a username is intrinsic to the story being posted.

Prevent users from submitting a form by hitting Enter

If you use a script to do the actual submit, then you can add "return false" line to the onsubmit handler like this:

<form onsubmit="return false;">

Calling submit() on the form from JavaScript will not trigger the event.

What is C# equivalent of <map> in C++?

.NET Framework provides many collection classes too. You can use Dictionary in C#. Please find the below msdn link for details and samples http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

conversion from string to json object android

its work

    String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";

    try {

        JSONObject obj = new JSONObject(json);

        Log.d("My App", obj.toString());
        Log.d("phonetype value ", obj.getString("phonetype"));

    } catch (Throwable tx) {
        Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
    }

Android: making a fullscreen application

I recently had the exact same issue and benefitted from the following post as well (in addition to Rohit5k2's solution above):

https://bsgconsultancy.wordpress.com/2015/09/13/convert-any-website-into-android-application-by-using-android-studio/

In Step 3, MainActivity extends Activity instead of ActionBarActivity (as Rohit5k2 mentioned). Putting the NoTitleBar and Fullscreen theme elements into the correct places in the AndroidManifest.xml file is also very important (take a look at Step 4).

How to set Java environment path in Ubuntu

Open file /etc/environment with a text editor Add the line JAVA_HOME="[path to your java]" Save and close then run source /etc/environment

Using Thymeleaf when the value is null

I use

<div th:text ="${variable != null} ? (${variable != ''} ? ${variable} : 'empty string message') : 'null message' "></div>

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Add border-bottom to table row <tr>

Several interesting answers. Since you just want a border bottom (or top) here are two more. Assuming you want a blue border 3px thick. In the style section you could add

.blueB {background-color:blue; height:3px} or
hr {background-color:blue; color:blue height:3px}

In the table code either

<tr><td colspan='3' class='blueB></td></tr> or
<tr><td colspan='3'><hr></td></tr>