Programs & Examples On #Fact

Ansible date variable

The lookup module of ansible works fine for me. The yml is:

- hosts: test
  vars:
    time: "{{ lookup('pipe', 'date -d \"1 day ago\" +\"%Y%m%d\"') }}"

You can replace any command with date to get result of the command.

jQuery calculate sum of values in all text fields

This should fix it:

var total = 0;   
$(".price").each( function(){
          total += $(this).val() * 1;
});

Copy data from another Workbook through VBA

Are you looking for the syntax to open them:

Dim wkbk As Workbook

Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")

Then, you can use wkbk.Sheets(1).Range("3:3") (or whatever you need)

Order discrete x scale by frequency/value

Hadley has been developing a package called forcats. This package makes the task so much easier. You can exploit fct_infreq() when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars example in this post, you want to reorder levels of cyl by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq().

library(ggplot2)
library(forcats)

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")

If you wanna go the other way around, you can use fct_rev() along with fct_infreq().

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl") 

enter image description here

How to gzip all files in all sub-directories into one compressed file in bash

there are lots of compression methods that work recursively command line and its good to know who the end audience is.

i.e. if it is to be sent to someone running windows then zip would probably be best:

zip -r file.zip folder_to_zip

unzip filenname.zip

for other linux users or your self tar is great

tar -cvzf filename.tar.gz folder

tar -cvjf filename.tar.bz2 folder  # even more compression

#change the -c to -x to above to extract

One must be careful with tar and how things are tarred up/extracted, for example if I run

cd ~
tar -cvzf passwd.tar.gz /etc/passwd
tar: Removing leading `/' from member names
/etc/passwd


pwd

/home/myusername

tar -xvzf passwd.tar.gz

this will create /home/myusername/etc/passwd

unsure if all versions of tar do this:

 Removing leading `/' from member names

How to change row color in datagridview?

If you bind to a (collection) of concrete objects, you can get the that concrete object via the DataBoundItem property of the row. (To avoid check for magic strings in the cell and using "real" properties of the object)

Skeleton example below:

DTO/POCO

public class Employee
{
    public int EmployeeKey {get;set;}

    public string LastName {get;set;}

    public string FirstName {get;set;}

    public bool IsActive {get;set;}
}       

Binding to the datagridview

    private void BindData(ICollection<Employee> emps)
    {
        System.ComponentModel.BindingList<Employee> bindList = new System.ComponentModel.BindingList<Employee>(emps.OrderBy(emp => emp.LastName).ThenBy(emp => emp.FirstName).ToList());
        this.dgvMyDataGridView.DataSource = bindList;
    }       

then the event handler and getting the concrete object (instead of a DataGridRow and/or cells)

        private void dgvMyDataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            Employee concreteSelectedRowItem = this.dgvMyDataGridView.Rows[e.RowIndex].DataBoundItem as Employee;
            if (null != concreteSelectedRowItem && !concreteSelectedRowItem.IsActive)
            {
                dgvMyDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGray;
            }
        }

Trigger a Travis-CI rebuild without pushing a commit?

Here's what worked for me to trigger a rebuild on a PR that Dependabot had opened, but failed due to errors in .travis.yml:

  1. Close the PR
  2. Wait for Dependabot to comment ("OK, I won't notify you again about this release, but will get in touch when a new version is available."). It will remove its branch.
  3. Restore the branch Dependabot removed (something like dependabot/cargo/tempfile-3.0.4).
  4. Open the PR again

Updating to latest version of CocoaPods?

Below are steps to update cocoapods :

  1. Open terminal (Shortcut : Press cmd + space tab to open Spotlight then text in terminal)
  2. Use command sudo gem install cocoapods. This will ask for system password due to security concern thereafter it installs gems

Screenshot 1

  1. Now, set up pod using pod setup command. This will setup cocoapods master repo.

Screenshot 2

  1. You can check the version of cocoapods using pod --version command.

Screenshot 3

Wait 5 seconds before executing next line

Try this:

//the code will execute in 1 3 5 7 9 seconds later
function exec() {
    for(var i=0;i<5;i++) {
        setTimeout(function() {
            console.log(new Date());   //It's you code
        },(i+i+1)*1000);
    }
}

Change the color of a checked menu item in a navigation drawer

I believe app:itemBackground expects a drawable. So follow the steps below :

Make a drawable file highlight_color.xml with following contents :

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
     <solid android:color="YOUR HIGHLIGHT COLOR"/>
</shape>

Make another drawable file nav_item_drawable.xml with following contents:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/highlight_color" android:state_checked="true"/>
</selector>

Finally add app:itemBackground tag in the NavView :

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
app:itemBackground="@drawable/nav_item_drawable"
app:menu="@menu/menu_drawer">

here the highlight_color.xml file defines a solid color drawable for the background. Later this color drawable is assigned to nav_item_drawable.xml selector.

This worked for me. Hopefully this will help.

********************************************** UPDATED **********************************************

Though the above mentioned answer gives you fine control over some properties, but the way I am about to describe feels more SOLID and is a bit COOLER.

So what you can do is, you can define a ThemeOverlay in the styles.xml for the NavigationView like this :

    <style name="ThemeOverlay.AppCompat.navTheme">

        <!-- Color of text and icon when SELECTED -->
        <item name="colorPrimary">@color/color_of_your_choice</item> 

        <!-- Background color when SELECTED -->
        <item name="colorControlHighlight">@color/color_of_your_choice</item> 

    </style>

now apply this ThemeOverlay to app:theme attribute of NavigationView, like this:

<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:theme="@style/ThemeOverlay.AppCompat.navTheme"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/menu_drawer">

I hope this will help.

How to plot two columns of a pandas data frame using points?

Pandas uses matplotlib as a library for basic plots. The easiest way in your case will using the following:

import pandas as pd
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
df.plot(x='col_name_1', y='col_name_2', style='o')

enter image description here

However, I would recommend to use seaborn as an alternative solution if you want have more customized plots while not going into the basic level of matplotlib. In this case you the solution will be following:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20)}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df)

enter image description here

Counter inside xsl:for-each loop

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <newBooks>
                <xsl:for-each select="books/book">
                        <newBook>
                                <countNo><xsl:value-of select="position()"/></countNo>
                                <title>
                                        <xsl:value-of select="title"/>
                                </title>
                        </newBook>
                </xsl:for-each>
        </newBooks>
    </xsl:template>
</xsl:stylesheet>

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How to download a folder from github?

There is a button Download ZIP. If you want to do a sparse checkout there are many solutions on the site. For example here.

How do I move files in node.js?

this is a rehash of teoman shipahi's answer with a slightly less ambiguous name, and following the design priciple of defining code before you attempt to call it. (Whilst node allows you to do otherwise, it's not good a practice to put the cart before the horse.)

function rename_or_copy_and_delete (oldPath, newPath, callback) {

    function copy_and_delete () {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);

        readStream.on('error', callback);
        writeStream.on('error', callback);
        readStream.on('close', 
              function () {
                fs.unlink(oldPath, callback);
              }
        );

        readStream.pipe(writeStream);
    }

    fs.rename(oldPath, newPath, 
        function (err) {
          if (err) {
              if (err.code === 'EXDEV') {
                  copy_and_delete();
              } else {
                  callback(err);
              }
              return;// << both cases (err/copy_and_delete)
          }
          callback();
        }
    );
}

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How to Empty Caches and Clean All Targets Xcode 4 and later

You have to be careful about the xib file. I tried all the above and nothing worked for me. I was using custom UIButtons defined in the xib, and realized it might be related to the fact that I had assigned attributes there which were not changing programmatically. If you've defined images or text there, remove them. When I did, my programmatic changes began to take effect.

How do I space out the child elements of a StackPanel?

I improved on Elad Katz' answer.

  • Add LastItemMargin property to MarginSetter to specially handle the last item
  • Add Spacing attached property with Vertical and Horizontal properties that adds spacing between items in vertical and horizontal lists and eliminates any trailing margin at the end of the list

Source code in gist.

Example:

<StackPanel Orientation="Horizontal" foo:Spacing.Horizontal="5">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

<StackPanel Orientation="Vertical" foo:Spacing.Vertical="5">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

<!-- Same as vertical example above -->
<StackPanel Orientation="Vertical" foo:MarginSetter.Margin="0 0 0 5" foo:MarginSetter.LastItemMargin="0">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

How to display databases in Oracle 11g using SQL*Plus

Oracle does not have a simple database model like MySQL or MS SQL Server. I find the closest thing is to query the tablespaces and the corresponding users within them.

For example, I have a DEV_DB tablespace with all my actual 'databases' within them:

SQL> SELECT TABLESPACE_NAME FROM USER_TABLESPACES;

Resulting in:

SYSTEM
SYSAUX
UNDOTBS1
TEMP
USERS
EXAMPLE
DEV_DB

It is also possible to query the users in all tablespaces:

SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS;

Or within a specific tablespace (using my DEV_DB tablespace as an example):

SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS where DEFAULT_TABLESPACE = 'DEV_DB';

ROLES DEV_DB
DATAWARE DEV_DB
DATAMART DEV_DB
STAGING DEV_DB

Spring Boot Java Config Set Session Timeout

You should be able to set the server.session.timeout in your application.properties file.

ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

How to add elements to an empty array in PHP?

$cart = array();
$cart[] = 11;
$cart[] = 15;

// etc

//Above is correct. but below one is for further understanding

$cart = array();
for($i = 0; $i <= 5; $i++){
          $cart[] = $i;  

//if you write $cart = [$i]; you will only take last $i value as first element in array.

}
echo "<pre>";
print_r($cart);
echo "</pre>";

How to find a Java Memory Leak

NetBeans has a built-in profiler.

UNION with WHERE clause

SELECT colA, colB FROM tableA  WHERE colA > 1
UNION
SELECT colX, colA FROM tableB

Finish all activities at a time

close the app

Intent intent = new Intent(getApplicationContext(), Splash_Screen.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("EXIT", true);
                startActivity(intent);

put this in the oncreate and onResume of the very first activity that is opened. ex. is on splash screen activity

if (getIntent().getBooleanExtra("EXIT", false)) {
            this.finish();
            System.exit(0);
        }

Selectors in Objective-C?

In this case, the name of the selector is wrong. The colon here is part of the method signature; it means that the method takes one argument. I believe that you want

SEL sel = @selector(lowercaseString);

How to set CATALINA_HOME variable in windows 7?

Here is tutorial how to do that (CATALINA_HOME is path to your Tomcat, so I suppose something like C:/Program Files/Tomcat/. And for starting server, you need to execute script startup.bat from command line, this will make it:)

No module named pkg_resources

I have had the same problem when I used easy-install to install pip for python 2.7.14. For me the solution was (might not be the best, but worked for me, and this is probably the simplest) that the folder that contained the easy-install.py also contained a folder pkg_resources, and i have copy-pasted this folder into the same folder where my pip-script.py script was (python27\Scripts). Since then, I found it in the python27\Lib\site-packages\pip-9.0.1-py2.7.egg\pip\_vendor folder as well, it might be a better solution to modify the pip-script.py file to import this.

How do I set up Eclipse/EGit with GitHub?

In Eclipse, go to Help -> Install New Software -> Add -> Name: any name like egit; Location: http://download.eclipse.org/egit/updates -> Okay. Now Search for egit in Work with and select all the check boxes and press Next till finish.

File -> Import -> search Git and select "Projects from Git" -> Clone URI. In the URI, paste the HTTPS URL of the repository (the one with .git extension). -> Next ->It will show all the branches "Next" -> Local Destination "Next" -> "Import as a general project" -> Next till finish.

You can refer to this Youtube tutorial: https://www.youtube.com/watch?v=ptK9-CNms98

How to send email by using javascript or jquery

You can send Email by Jquery just follow these steps 

include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :

$( document ).ready(function() {
 Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});

Moment.js - how do I get the number of years since a date, not rounded up?

Try this:

 moment("02/26/1978", "MM/DD/YYYY").fromNow().split(" ")[0];

Explanation:

We receive string something like this: '23 days ago'. Split it to array: ['23', 'days', 'ago'] and then take first item '23'.

How can I detect when the mouse leaves the window?

I've tried all the above, but nothing seems to work as expected. After a little research I found that e.relatedTarget is the html just before the mouse exits the window.

So ... I've end up with this:


document.body.addEventListener('mouseout', function(e) {
    if (e.relatedTarget === document.querySelector('html')) {
        console.log('We\'re OUT !');
    }
});

Please let me know if you find any issues or improvements !

2019 Update

(as user1084282 found out)

document.body.addEventListener('mouseout', function(e) {
    if (!e.relatedTarget && !e.toElement) {
        console.log('We\'re OUT !');
    }
});

How to set image width to be 100% and height to be auto in react native?

Right click on you image to get resolution. In my case 1233 x 882

const { width } = Dimensions.get('window');

const ratio = 882 / 1233;

    const style = {
      width,
      height: width * ratio
    }

<Image source={image} style={style} resizeMode="contain" />

That all

How can I update a single row in a ListView?

I found the answer, thanks to your information Michelle. You can indeed get the right view using View#getChildAt(int index). The catch is that it starts counting from the first visible item. In fact, you can only get the visible items. You solve this with ListView#getFirstVisiblePosition().

Example:

private void updateView(int index){
    View v = yourListView.getChildAt(index - 
        yourListView.getFirstVisiblePosition());

    if(v == null)
       return;

    TextView someText = (TextView) v.findViewById(R.id.sometextview);
    someText.setText("Hi! I updated you manually!");
}

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

It's a table-valued function, but you're using it as a scalar function.

Try:

where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)

But... also consider changing your function into an inline TVF, as it'll perform better.

How to pass url arguments (query string) to a HTTP request on Angular?

The HttpClient methods allow you to set the params in it's options.

You can configure it by importing the HttpClientModule from the @angular/common/http package.

import {HttpClientModule} from '@angular/common/http';

@NgModule({
  imports: [ BrowserModule, HttpClientModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

After that you can inject the HttpClient and use it to do the request.

import {HttpClient} from '@angular/common/http'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor(private httpClient: HttpClient) {
    this.httpClient.get('/url', {
      params: {
        appid: 'id1234',
        cnt: '5'
      },
      observe: 'response'
    })
    .toPromise()
    .then(response => {
      console.log(response);
    })
    .catch(console.log);
  }
}

For angular versions prior to version 4 you can do the same using the Http service.

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

The search field of that object can be used to set a string or a URLSearchParams object.

An example:

 // Parameters obj-
 let params: URLSearchParams = new URLSearchParams();
 params.set('appid', StaticSettings.API_KEY);
 params.set('cnt', days.toString());

 //Http request-
 return this.http.get(StaticSettings.BASE_URL, {
   search: params
 }).subscribe(
   (response) => this.onGetForecastResult(response.json()), 
   (error) => this.onGetForecastError(error.json()), 
   () => this.onGetForecastComplete()
 );

The documentation for the Http class has more details. It can be found here and an working example here.

MySQL : transaction within a stored procedure

Here's an example of a transaction that will rollback on error and return the error code.

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_CREATE_SERVER_USER`(
    IN P_server_id VARCHAR(100),
    IN P_db_user_pw_creds VARCHAR(32),
    IN p_premium_status_name VARCHAR(100),
    IN P_premium_status_limit INT,
    IN P_user_tag VARCHAR(255),
    IN P_first_name VARCHAR(50),
    IN P_last_name VARCHAR(50)
)
BEGIN

    DECLARE errno INT;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
    GET CURRENT DIAGNOSTICS CONDITION 1 errno = MYSQL_ERRNO;
    SELECT errno AS MYSQL_ERROR;
    ROLLBACK;
    END;

    START TRANSACTION;

    INSERT INTO server_users(server_id, db_user_pw_creds, premium_status_name, premium_status_limit)
    VALUES(P_server_id, P_db_user_pw_creds, P_premium_status_name, P_premium_status_limit);

    INSERT INTO client_users(user_id, server_id, user_tag, first_name, last_name, lat, lng)
    VALUES(P_server_id, P_server_id, P_user_tag, P_first_name, P_last_name, 0, 0);

    COMMIT WORK;

END$$
DELIMITER ;

This is assuming that autocommit is set to 0. Hope this helps.

Bootstrap navbar Active State not working

As someone who doesn't know javascript, here's a PHP method that works for me and is easy to understand. My whole navbar is in a PHP function that is in a file of common components I include from my pages. So for example in my 'index.php' page I have... `

<?php
   $calling_file = basename(__FILE__);
   include 'my_common_includes.php';    // Going to use my navbar function "my_navbar"
   my_navbar($calling_file);    // Call the navbar function
 ?>

Then in the 'my_common_includes.php' I have...

<?php
   function my_navbar($calling_file)
   {
      // All your usual nabvbar code here up to the menu items
      if ($calling_file=="index.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="index.php">Home</a>
</li>';
      if ($calling_file=="about.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="about.php">About</a>
</li>';
      if ($calling_file=="galleries.php")   {   echo '<li class="nav-item active">';    } else {    echo '<li class="nav-item">';   }
    echo '<a class="nav-link" href="galleries.php">Galleries</a>
</li>';
       // etc for the rest of the menu items and closing out the navbar
     }
  ?>

Print number of keys in Redis

DBSIZE returns the number of keys and it's easier to parse.

Downside: if a key has expired it may still count.

http://redis.io/commands/dbsize

Is there a way to 'uniq' by column?

or if u want to use uniq:

<mycvs.cvs tr -s ',' ' ' | awk '{print $3" "$2" "$1}' | uniq -c -f2

gives:

1 01:05:47.893000000 2009-11-27 [email protected]
2 00:58:29.793000000 2009-11-27 [email protected]
1

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:

Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.

Batch file to map a drive when the folder name contains spaces

net use "m:\Server01\my folder" /USER:mynetwork\Administrator "Mypassword" /persistent:yes 

does not work?

how to change onclick event with jquery?

(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});

I tried $('#'+id).off().on(...), but it wouldn't work to reset the onClick attribute every time it was called to be reset.

I use .on('click',function(){...}); to stay away from having to quote block all my javascript functions.

The O.P. could now use:

$(this).removeAttr('onclick').off('click').on('click', function(){ displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this); });

Where this came through for me is when my div was set with the onClick attribute set statically:

<div onclick = '...'>

Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});.

Without the off('click') my onClick listeners were being appended not replaced.

Calling startActivity() from outside of an Activity?

When you want to open an activity within your app then you can call the startActivity() method with an Intent as parameter. That intent would be the activity that you want to open. First you have to create an object of that intent with first parameter to be the context and second parameter to be the targeted activity class.

Intent intent = new Intent(this, Activity_a.class);
startActivity(intent);

Hope this will help.

How to tell if string starts with a number with Python?

Surprising that after such a long time there is still the best answer missing.

The downside of the other answers is using [0] to select the first character, but as noted, this breaks on the empty string.

Using the following circumvents this problem, and, in my opinion, gives the prettiest and most readable syntax of the options we have. It also does not import/bother with regex either):

>>> string = '1abc'
>>> string[:1].isdigit()
True

>>> string = ''
>>> string[:1].isdigit()
False

Change Schema Name Of Table In SQL

Be very very careful renaming objects in sql. You can cause dependencies to fail if you are not fully away with what you are doing. Having said that this works easily(too much so) for renaming things provided you have access proper on the environment:

exec sp_rename 'Nameofobject', 'ReNameofobject'

ant build.xml file doesn't exist

Please install at ubuntu openjdk-7-jdk

sudo apt-get install openjdk-7-jdk

on Windows try find find openjdk

How to change color in circular progress bar?

To customize circular ProgressBar we need to create a indeterminateDrawable to show custom progress bar

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="1">

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false">

        <size
            android:height="48dip"
            android:width="48dip" />

        <gradient
            android:centerColor="#f96047"
            android:centerY="0.50"
            android:endColor="#fb9c8d"
            android:startColor="#f72d0c"
            android:type="sweep"
            android:useLevel="false" />

    </shape>

</rotate>

We need to include drawable in progressbar just as below:

<ProgressBar
    android:layout_width="wrap_content"
    android:layout_centerInParent="true"
    style="?android:attr/progressBarStyleLarge"
    android:visibility="visible"
    android:progressDrawable="@drawable/widget_progressbar"
    android:indeterminateDrawable="@drawable/widget_progressbar"
    android:layout_height="wrap_content" />

Is there a way to only install the mysql client (Linux)?

[root@localhost administrador]# yum search mysql | grep client
community-mysql.i686 : MySQL client programs and shared libraries
                            : client
community-mysql-libs.i686 : The shared libraries required for MySQL clients
root-sql-mysql.i686 : MySQL client plugin for ROOT
mariadb-libs.i686 : The shared libraries required for MariaDB/MySQL clients
[root@localhost administrador]# yum install  -y community-mysql

One DbContext per web request... why?

Not a single answer here actually answers the question. The OP did not ask about a singleton/per-application DbContext design, he asked about a per-(web)request design and what potential benefits could exist.

I'll reference http://mehdi.me/ambient-dbcontext-in-ef6/ as Mehdi is a fantastic resource:

Possible performance gains.

Each DbContext instance maintains a first-level cache of all the entities its loads from the database. Whenever you query an entity by its primary key, the DbContext will first attempt to retrieve it from its first-level cache before defaulting to querying it from the database. Depending on your data query pattern, re-using the same DbContext across multiple sequential business transactions may result in a fewer database queries being made thanks to the DbContext first-level cache.

It enables lazy-loading.

If your services return persistent entities (as opposed to returning view models or other sorts of DTOs) and you'd like to take advantage of lazy-loading on those entities, the lifetime of the DbContext instance from which those entities were retrieved must extend beyond the scope of the business transaction. If the service method disposed the DbContext instance it used before returning, any attempt to lazy-load properties on the returned entities would fail (whether or not using lazy-loading is a good idea is a different debate altogether which we won't get into here). In our web application example, lazy-loading would typically be used in controller action methods on entities returned by a separate service layer. In that case, the DbContext instance that was used by the service method to load these entities would need to remain alive for the duration of the web request (or at the very least until the action method has completed).

Keep in mind there are cons as well. That link contains many other resources to read on the subject.

Just posting this in case someone else stumbles upon this question and doesn't get absorbed in answers that don't actually address the question.

I need an unordered list without any bullets

If you're unable to make it work at the <ul> level, you might need to place the list-style-type: none; at the <li> level:

<ul>
    <li style="list-style-type: none;">Item 1</li>
    <li style="list-style-type: none;">Item 2</li>
</ul>

You can create a CSS class to avoid this repetition:

<style>
ul.no-bullets li
{
    list-style-type: none;
}
</style>

<ul class="no-bullets">
    <li>Item 1</li>
    <li>Item 2</li>
</ul>

When necessary, use !important:

<style>
ul.no-bullets li
{
    list-style-type: none !important;
}
</style>

unsigned APK can not be installed

I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.

I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.

Send Email to multiple Recipients with MailMessage?

According to the Documentation :

MailMessage.To property - Returns MailAddressCollection that contains the list of recipients of this email message

Here MailAddressCollection has a in built method called

   public void Add(string addresses)

   1. Summary:
          Add a list of email addresses to the collection.

   2. Parameters:
          addresses: 
                *The email addresses to add to the System.Net.Mail.MailAddressCollection. Multiple
                *email addresses must be separated with a comma character (",").     

Therefore requirement in case of multiple recipients : Pass a string that contains email addresses separated by comma

In your case :

simply replace all the ; with ,

Msg.To.Add(toEmail.replace(";", ","));

For reference :

  1. https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=netframework-4.8
  2. https://www.geeksforgeeks.org/c-sharp-replace-method/

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Select random lines from a file

My preferred option is very fast, I sampled a tab-delimited data file with 13 columns, 23.1M rows, 2.0GB uncompressed.

# randomly sample select 5% of lines in file
# including header row, exclude blank lines, new seed

time \
awk 'BEGIN  {srand()} 
     !/^$/  { if (rand() <= .05 || FNR==1) print > "data-sample.txt"}' data.txt

# awk  tsv004  3.76s user 1.46s system 91% cpu 5.716 total

Convert .cer certificate to .jks

Use the following will help

keytool -import -v -trustcacerts -alias keyAlias -file server.cer -keystore cacerts.jks -keypass changeit

pop/remove items out of a python tuple

In Python 3 this is no longer an issue, and you really don't want to use list comprehension, coercion, filters, functions or lambdas for something like this.

Just use

popped = unpopped[:-1]

Remember that it's an immutable, so you will have to reassign the value if you want it to change

my_tuple = my_tuple[:-1]

Example

>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
foo[:-1]
(3, 5, 2, 4, 78, 2)

How to sort rows of HTML table that are called from MySQL

The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.

The HTML would look like this:

<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>

And in the php code, do something like this:

<?php

$sql = "SELECT * FROM MyTable";

if ($_GET['sort'] == 'type')
{
    $sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
    $sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
    $sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
    $sql .= " ORDER BY DateAdded";
}

$>

Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;

Java: how do I check if a Date is within a certain range?

An easy way is to convert the dates into milliseconds after January 1, 1970 (use Date.getTime()) and then compare these values.

How to add a TextView to a LinearLayout dynamically in Android?

layout:

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

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

class file:

setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());

textView.setText("testDynamic textView");
layoutTest.addView(textView);

Multi-character constant warnings

If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:

-Wno-multichar

I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.

How to disable text selection highlighting

Maybe you can use this solution through :before:

_x000D_
_x000D_
nav li {_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
nav li a {_x000D_
    display: inline-block;_x000D_
    padding: 10px 20px;_x000D_
}_x000D_
_x000D_
nav li a:hover {_x000D_
    color: red;_x000D_
}_x000D_
_x000D_
nav li.disabled:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    right: 0;_x000D_
}
_x000D_
<nav>_x000D_
    <ul>_x000D_
    <li><a href="#">Link</a></li>_x000D_
    <li class="disabled"><a href="#">Link</a></li>_x000D_
    <li><a href="#">Link</a></li>_x000D_
    </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

JsFiddle - https://jsfiddle.net/grinmax_/9L1cckxu/

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How can I build multiple submit buttons django form?

Eg:

if 'newsletter_sub' in request.POST:
    # do subscribe
elif 'newsletter_unsub' in request.POST:
    # do unsubscribe

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

The server encountered an internal error or misconfiguration and was unable to complete your request

Check your servers error log, typically /var/log/apache2/error.log.

Difference between onStart() and onResume()

Reference to http://developer.android.com/training/basics/activity-lifecycle/starting.html

onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it. Always followed by onPause().

onPause() Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns. Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

Last segment of URL in jquery

you can first remove if there is / at the end and then get last part of url

let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
  locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);

How do you divide each element in a list by an int?

I was running some of the answers to see what is the fastest way for a large number. So, I found that we can convert the int to an array and it can give the correct results and it is faster.

  arrayint=np.array(myInt)
  newList = myList / arrayint

This a comparison of all answers above

import numpy as np
import time
import random
myList = random.sample(range(1, 100000), 10000)
myInt = 10
start_time = time.time()
arrayint=np.array(myInt)
newList = myList / arrayint
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.array(myList) / myInt
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
myList[:] = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = map(lambda x: x/myInt, myList)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [i/myInt for i in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList  = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList  = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)

Finding diff between current and last version

I use Bitbucket with the Eclipse IDE with the Eclipse EGit plugin installed.

I compare a file from any version of its history (like SVN).

Menu Project Explorer → File → right click → TeamShow in history.

This will bring the history of all changes on that file. Now Ctrl click and select any two versions→ "Compare with each other".

Unexpected character encountered while parsing value

If you are using downloading data using url...may need to use

var result = client.DownloadData(url);

How can I generate an MD5 hash?

MD5 is perfectly fine if you don't need the best security, and if you're doing something like checking file integrity then security is not a consideration. In such as case you might want to consider something simpler and faster, such as Adler32, which is also supported by the Java libraries.

How to update Ruby with Homebrew?

I would use ruby-build with rbenv. The following lines install Ruby 3.0.0 and set it as your default Ruby version:

$ brew update
$ brew install ruby-build
$ brew install rbenv

$ rbenv install 3.0.0
$ rbenv global 3.0.0

Constructors in Go

I like the explanation from this blog post:

The function New is a Go convention for packages that create a core type or different types for use by the application developer. Look at how New is defined and implemented in log.go, bufio.go and cypto.go:

log.go

// New creates a new Logger. The out variable sets the
// destination to which log data will be written.
// The prefix appears at the beginning of each generated log line.
// The flag argument defines the logging properties.
func New(out io.Writer, prefix string, flag int) * Logger {
    return &Logger{out: out, prefix: prefix, flag: flag}
}

bufio.go

// NewReader returns a new Reader whose buffer has the default size.
func NewReader(rd io.Reader) * Reader {
    return NewReaderSize(rd, defaultBufSize)
}

crypto.go

// New returns a new hash.Hash calculating the given hash function. New panics
// if the hash function is not linked into the binary.
func (h Hash) New() hash.Hash {
    if h > 0 && h < maxHash {
        f := hashes[h]
        if f != nil {
            return f()
        }
    }
    panic("crypto: requested hash function is unavailable")
}

Since each package acts as a namespace, every package can have their own version of New. In bufio.go multiple types can be created, so there is no standalone New function. Here you will find functions like NewReader and NewWriter.

Any way of using frames in HTML5?

I know your class is over, but in professional coding, let this be a lesson:

  • "Deprecated" means "avoid use; it's going to be removed in the future"
  • Deprecated things still work - just don't expect support or future-proofing
  • If the requirement requires it, and you can't negotiate it away, just use the deprecated construct.
    • If you're really concerned, develop the alternative implementation on the side and keep it ready for the inevitable failure
    • Charge for the extra work now. By requesting a deprecated feature, they are asking you to double the work. You're going to see it again anyway, so might as well front-load it.
    • When the failure happens, let the interested party know that this was what you feared; that you prepared for it, but it'll take some time
    • Deploy your solution as quickly as you can (there will be bugs)
    • Gain rep for preventing excessive downtime.

Element-wise addition of 2 lists?

I haven't timed it but I suspect this would be pretty quick:

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

list_sum = (np.add(list1, list2)).tolist()

[5, 7, 9]

How do I make a branch point at a specific commit?

git branch -f <branchname> <commit>

I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on

git branch -f <branchname> <commit>

Here is a scenario where I have needed to do this.

Scenario

Develop on the wrong branch and hence need to reset it.

Start Okay

Cleanly develop and release some software.

So far so good

Develop on wrong branch

Mistake: Accidentally stay on the release branch while developing further.

After a mistake

Realize the mistake

"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.

Create a branch for the development that is up to date holding the work committed so far and switch to it.

git branch development
git checkout development 

Changed to another branch

Correct the branch

Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.

Correct the release branch to point back to the last real release.

git branch -f release release2

The release branch is now correct again, like this ...

Corrected

What if I pushed the mistake to a remote?

git push -f <remote> <branch> is well described in another thread, though the word "overwrite" in the title is misleading. Force "git push" to overwrite remote files

When should I use cross apply over inner join?

cross apply sometimes enables you to do things that you cannot do with inner join.

Example (a syntax error):

select F.* from sys.objects O  
inner join dbo.myTableFun(O.name) F   
on F.schema_id= O.schema_id

This is a syntax error, because, when used with inner join, table functions can only take variables or constants as parameters. (I.e., the table function parameter cannot depend on another table's column.)

However:

select F.* from sys.objects O  
cross apply ( select * from dbo.myTableFun(O.name) ) F  
where F.schema_id= O.schema_id

This is legal.

Edit: Or alternatively, shorter syntax: (by ErikE)

select F.* from sys.objects O  
cross apply dbo.myTableFun(O.name) F
where F.schema_id= O.schema_id

Edit:

Note: Informix 12.10 xC2+ has Lateral Derived Tables and Postgresql (9.3+) has Lateral Subqueries which can be used to a similar effect.

C/C++ check if one bit is set in, i.e. int variable

Use std::bitset

#include <bitset>
#include <iostream>

int main()
{
    int temp = 0x5E;
    std::bitset<sizeof(int)*CHAR_BITS>   bits(temp);

    // 0 -> bit 1
    // 2 -> bit 3
    std::cout << bits[2] << std::endl;
}

Swift do-try-catch syntax

Create enum like this:

//Error Handling in swift
enum spendingError : Error{
case minus
case limit
}

Create method like:

 func calculateSpending(morningSpending:Double,eveningSpending:Double) throws ->Double{
if morningSpending < 0 || eveningSpending < 0{
    throw spendingError.minus
}
if (morningSpending + eveningSpending) > 100{
    throw spendingError.limit
}
return morningSpending + eveningSpending
}

Now check error is there or not and handle it:

do{
try calculateSpending(morningSpending: 60, eveningSpending: 50)
} catch spendingError.minus{
print("This is not possible...")
} catch spendingError.limit{
print("Limit reached...")
}

How do I set a ViewModel on a window in XAML using DataContext property?

Try this instead.

<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:VM="clr-namespace:BuildAssistantUI.ViewModels">
    <Window.DataContext>
        <VM:MainViewModel />
    </Window.DataContext>
</Window>

What's the difference between a 302 and a 307 redirect?

The difference concerns redirecting POST, PUT and DELETE requests and what the expectations of the server are for the user agent behavior (RFC 2616):

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

Also, read Wikipedia article on the 30x redirection codes.

Get ID from URL with jQuery

const url = "http://www.example.com/1234"
const id = url.split('/').pop();

Try this, it is much easier

The output gives 1234

Where is HttpContent.ReadAsAsync?

Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.

How to find serial number of Android device?

Yes. It is a device hardware serial number and it is unique. So on api level 2.3 and above you can use android.os.Build.ANDROID_ID to get it. For below 2.3 API level use TelephonyManager.getDeviceID().

you can read this http://android-developers.blogspot.in/2011/03/identifying-app-installations.html

Scanner vs. StringTokenizer vs. String.Split

String.split seems to be much slower than StringTokenizer. The only advantage with split is that you get an array of the tokens. Also you can use any regular expressions in split. org.apache.commons.lang.StringUtils has a split method which works much more faster than any of two viz. StringTokenizer or String.split. But the CPU utilization for all the three is nearly the same. So we also need a method which is less CPU intensive, which I am still not able to find.

Android selector & text color

Here's my implementation, which behaves exactly as item in list (at least on 2.3)

res/layout/list_video_footer.xml

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

    <TextView
        android:id="@+id/list_video_footer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:drawable/list_selector_background"
        android:clickable="true"
        android:gravity="center"
        android:minHeight="98px"
        android:text="@string/more"
        android:textColor="@color/bright_text_dark_focused"
        android:textSize="18dp"
        android:textStyle="bold" />

</FrameLayout>

res/color/bright_text_dark_focused.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true" android:color="#444"/>
    <item android:state_focused="true" android:color="#444"/>
    <item android:state_pressed="true" android:color="#444"/>
    <item android:color="#ccc"/>

</selector>

Max or Default?

Sounds like a case for DefaultIfEmpty (untested code follows):

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).DefaultIfEmpty.Max

Create a new file in git bash

If you are using the Git Bash shell, you can use the following trick:

> webpage.html

This is actually the same as:

echo "" > webpage.html

Then, you can use git add webpage.html to stage the file.

Is it possible to modify a registry entry via a .bat/.cmd script?

You can make a .reg file and call start on it. You can export any part of the registry as a .reg file to see what the format is.

Format here:

http://support.microsoft.com/kb/310516

This can be run on any Windows machine without installing other software.

What is process.env.PORT in Node.js?

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

creating json object with variables

var formValues = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    phone: $('#phoneNumber').val(),
    address: $('#address').val()
};

Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

jQuery - Add active class and remove active from other element on click

You can remove class active from all .tab and use $(this) to target current clicked .tab:

$(document).ready(function() {
    $(".tab").click(function () {
        $(".tab").removeClass("active");
        $(this).addClass("active");     
    });
});

Your code won't work because after removing class active from all .tab, you also add class active to all .tab again. So you need to use $(this) instead of $('.tab') to add the class active only to the clicked .tab anchor

Updated Fiddle

How to get error message when ifstream open fails

You could try letting the stream throw an exception on failure:

std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);

try {
  f.open(fileName);
}
catch (std::ios_base::failure& e) {
  std::cerr << e.what() << '\n';
}

e.what(), however, does not seem to be very helpful:

  • I tried it on Win7, Embarcadero RAD Studio 2010 where it gives "ios_base::failbit set" whereas strerror(errno) gives "No such file or directory."
  • On Ubuntu 13.04, gcc 4.7.3 the exception says "basic_ios::clear" (thanks to arne)

If e.what() does not work for you (I don't know what it will tell you about the error, since that's not standardized), try using std::make_error_condition (C++11 only):

catch (std::ios_base::failure& e) {
  if ( e.code() == std::make_error_condition(std::io_errc::stream) )
    std::cerr << "Stream error!\n"; 
  else
    std::cerr << "Unknown failure opening file.\n";
}

node.js Error: connect ECONNREFUSED; response from server

I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

JavaScript check if value is only undefined, null or false

Boolean(val) === false. This worked for me to check if value was falsely.

Read input stream twice

You can use org.apache.commons.io.IOUtils.copy to copy the contents of the InputStream to a byte array, and then repeatedly read from the byte array using a ByteArrayInputStream. E.g.:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(in, baos);
byte[] bytes = baos.toByteArray();

// either
while (needToReadAgain) {
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    yourReadMethodHere(bais);
}

// or
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
while (needToReadAgain) {
    bais.reset();
    yourReadMethodHere(bais);
}

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.

Show red border for all invalid fields after submitting form angularjs

Reference article: Show red color border for invalid input fields angualrjs

I used ng-class on all input fields.like below

<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>

when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).

So now my input field contains classes like this

class="ng-pristine ng-invalid submitted"

now I am using below css code to show red border on all invalid input fields(after submitting the form)

input.submitted.ng-invalid
{
  border:1px solid #f00;
}

Thank you !!

Update:

We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector

form.submitted .ng-invalid
{
    border:1px solid #f00;
}

How do I specify the JDK for a GlassFish domain?

In Linux file system , Edit below file as this steps

Path - /opt/glassfish3/glassfish/config

File Name - asenv.conf

Add the JAVA HOME path as below to the end of file.

AS_JAVA=/opt/jdk1.8.0_201

Now start the glassfish server.

how to POST/Submit an Input Checkbox that is disabled?

There is no other option other than a hidden field, so try to use a hidden field like demonstrated in the code below:

<input type="hidden" type="text" name="chk1[]" id="tasks" value="xyz" >
<input class="display_checkbox" type="checkbox" name="chk1[]" id="tasks" value="xyz" checked="check"  disabled="disabled" >Tasks

How do I fix MSB3073 error in my post-build event?

Prefer the MsBuild "Copy" task in an AfterBuild target over a post-build event.

Append this Target into your project file and remove the PostBuildEvent.

<Target Name="AfterBuild">
    <Copy SourceFiles="C:\Users\scogan\Documents\Visual Studio 2012\Projects\Organizr\Server\bin\Debug\Organizr.Services.*" 
          DestinationFolder="C:\inetpub\wwwroot\AppServer\bin\" 
          OverwriteReadOnlyFiles="true" 
          SkipUnchangedFiles="false" />
</Target>

How to use a variable for the database name in T-SQL?

You can also use sqlcmd mode for this (enable this on the "Query" menu in Management Studio).

:setvar dbname "TEST" 

CREATE DATABASE $(dbname)
GO
ALTER DATABASE $(dbname) SET COMPATIBILITY_LEVEL = 90
GO
ALTER DATABASE $(dbname) SET RECOVERY SIMPLE 
GO

EDIT:

Check this MSDN article to set parameters via the SQLCMD tool.

Which @NotNull Java annotation should I use?

If you're developing for android, you're somewhat tied to Eclipse (edit: at time of writing, not anymore), which has its own annotations. It's included in Eclipse 3.8+ (Juno), but disabled by default.

You can enable it at Preferences > Java > Compiler > Errors/Warnings > Null analysis (collapsable section at the bottom).

Check "Enable annotation-based null analysis"

http://wiki.eclipse.org/JDT_Core/Null_Analysis#Usage has recommendations on settings. However, if you have external projects in your workspace (like the facebook SDK), they may not satisfy those recommendations, and you probably don't want to fix them with each SDK update ;-)

I use:

  1. Null pointer access: Error
  2. Violation of null specification: Error (linked to point #1)
  3. Potential null pointer access: Warning (otherwise facebook SDK would have warnings)
  4. Conflict between null annotations and null inference: Warning (linked to point #3)

Detect if a page has a vertical scrollbar?

I wrote an updated version of Kees C. Bakker's answer:

const hasVerticalScroll = (node) => {
  if (!node) {
    if (window.innerHeight) {
      return document.body.offsetHeight > window.innerHeight
    }
    return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
      || (document.body.scrollHeight > document.body.offsetHeight)
  }
  return node.scrollHeight > node.offsetHeight
}

if (hasVerticalScroll(document.querySelector('body'))) {
  this.props.handleDisableDownScrollerButton()
}

The function returns true or false depending whether the page has a vertical scrollbar or not.

For example:

const hasVScroll = hasVerticalScroll(document.querySelector('body'))

if (hasVScroll) {
  console.log('HAS SCROLL', hasVScroll)
}

laravel 5.4 upload image

if ($request->hasFile('input_img')) {
    if($request->file('input_img')->isValid()) {
        try {
            $file = $request->file('input_img');
            $name = time() . '.' . $file->getClientOriginalExtension();

            $request->file('input_img')->move("fotoupload", $name);
        } catch (Illuminate\Filesystem\FileNotFoundException $e) {

        }
    } 
}

or follow
https://laracasts.com/discuss/channels/laravel/image-upload-file-does-not-working
or
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12

Is there a “not in” operator in JavaScript for checking object properties?

Personally I find

if (id in tutorTimes === false) { ... }

easier to read than

if (!(id in tutorTimes)) { ... }

but both will work.

wkhtmltopdf: cannot connect to X server

sudo -i
apt-get install wkhtmltopdf xvfb libicu48
mv /usr/bin/wkhtmltopdf /usr/bin/wkhtmltopdf-origin
touch /usr/bin/wkhtmltopdf && chmod +x /usr/bin/wkhtmltopdf && cat > /usr/bin/wkhtmltopdf << END
#!/bin/bash

/usr/bin/xvfb-run -a -s "-screen 0 1024x768x24" /usr/bin/wkhtmltopdf-origin  "\$@"
END

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

I also experienced this error when working with CMake:

No CMAKE_C_COMPILER could be found.
No CMAKE_CXX_COMPILER could be found.

The 'warning' box in the MSDN library article Visual C++ in Visual Studio 2015 gave me the help that I needed.

Visual Studio 2015 doesn't come with C++ installed by default. So, creating a new C++ project will prompt you to download the necessary C++ components.

Does file_get_contents() have a timeout setting?

Yes! By passing a stream context in the third parameter:

Here with a timeout of 1s:

file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));

Source in comment section of https://www.php.net/manual/en/function.file-get-contents.php

HTTP context options:

method
header
user_agent
content
request_fulluri
follow_location
max_redirects
protocol_version
timeout

Other contexts: https://www.php.net/manual/en/context.php

how to fix groovy.lang.MissingMethodException: No signature of method:

This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.

class name - User is accepted but user is not.

Pass user defined environment variable to tomcat

You can use setenv.bat or .sh to pass the environment variables to the Tomcat.

Create CATALINA_BASE/bin/setenv.bat or .sh file and put the following line in it, and then start the Tomcat.

On Windows:

set APP_MASTER_PASSWORD=foo

On Unix like systems:

export APP_MASTER_PASSWORD=foo

How to present UIActionSheet iOS Swift?

Generetic Action Sheet working for Swift 4, 4.2, 5

If you like a generic version that you can call from every ViewController and in every project try this one:

class Alerts {
 static func showActionsheet(viewController: UIViewController, title: String, message: String, actions: [(String, UIAlertActionStyle)], completion: @escaping (_ index: Int) -> Void) {
    let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
    for (index, (title, style)) in actions.enumerated() {
        let alertAction = UIAlertAction(title: title, style: style) { (_) in
            completion(index)
        }
        alertViewController.addAction(alertAction)
     }
     viewController.present(alertViewController, animated: true, completion: nil)
    }
}

Call like this in your ViewController.

    var actions: [(String, UIAlertActionStyle)] = []
    actions.append(("Action 1", UIAlertActionStyle.default))
    actions.append(("Action 2", UIAlertActionStyle.destructive))
    actions.append(("Action 3", UIAlertActionStyle.cancel))

    //self = ViewController
    Alerts.showActionsheet(viewController: self, title: "D_My ActionTitle", message: "General Message in Action Sheet", actions: actions) { (index) in
        print("call action \(index)")
        /*
         results
         call action 0
         call action 1
         call action 2
         */
    }

enter image description here

Attention: Maybe you're wondering why I add Action 1/2/3 but got results like 0,1,2. In the line for (index, (title, style)) in actions.enumerated() I get the index of actions. Arrays always begin with the index 0. So the completion is 0,1,2.

If you like to set a enum, an id or another identifier I would recommend to hand over an object in parameter actions.

Batch: Remove file extension

You can use %%~nf to get the filename only as described in the reference for for:

@echo off
    for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
    echo %%~nf
)
pause

The following options are available:

Variable with modifier  Description

%~I                     Expands %I which removes any surrounding 
                        quotation marks ("").
%~fI                    Expands %I to a fully qualified path name.
%~dI                    Expands %I to a drive letter only.
%~pI                    Expands %I to a path only.
%~nI                    Expands %I to a file name only.
%~xI                    Expands %I to a file extension only.
%~sI                    Expands path to contain short names only.
%~aI                    Expands %I to the file attributes of file.
%~tI                    Expands %I to the date and time of file.
%~zI                    Expands %I to the size of file.
%~$PATH:I               Searches the directories listed in the PATH environment 
                        variable and expands %I to the fully qualified name of 
                        the first one found. If the environment variable name is 
                        not defined or the file is not found by the search,
                        this modifier expands to the empty string.    

angular2 manually firing click event on particular element

This worked for me:

<button #loginButton ...

and inside the controller:

@ViewChild('loginButton') loginButton;
...
this.loginButton.getNativeElement().click();

Setting HttpContext.Current.Session in a unit test

Milox solution is better than the accepted one IMHO but I had some problems with this implementation when handling urls with querystring.

I made some changes to make it work properly with any urls and to avoid Reflection.

public static HttpContext FakeHttpContext(string url)
{
    var uri = new Uri(url);
    var httpRequest = new HttpRequest(string.Empty, uri.ToString(),
                                        uri.Query.TrimStart('?'));
    var stringWriter = new StringWriter();
    var httpResponse = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponse);

    var sessionContainer = new HttpSessionStateContainer("id",
                                    new SessionStateItemCollection(),
                                    new HttpStaticObjectsCollection(),
                                    10, true, HttpCookieMode.AutoDetect,
                                    SessionStateMode.InProc, false);

    SessionStateUtility.AddHttpSessionStateToContext(
                                         httpContext, sessionContainer);

    return httpContext;
}

Check if textbox has empty value

var inp = $("#txt").val();
if(jQuery.trim(inp).length > 0)
{
   //do something
}

Removes white space before checking. If the user entered only spaces then this will still work.

Unable to verify leaf signature

CoolAJ86's solution is correct and it does not compromise your security like disabling all checks using rejectUnauthorized or NODE_TLS_REJECT_UNAUTHORIZED. Still, you may need to inject an additional CA's certificate explicitly.

I tried first the root CAs included by the ssl-root-cas module:

require('ssl-root-cas/latest')
  .inject();

I still ended up with the UNABLE_TO_VERIFY_LEAF_SIGNATURE error. Then I found out who issued the certificate for the web site I was connecting to by the COMODO SSL Analyzer, downloaded the certificate of that authority and tried to add only that one:

require('ssl-root-cas/latest')
  .addFile(__dirname + '/comodohigh-assurancesecureserverca.crt');

I ended up with another error: CERT_UNTRUSTED. Finally, I injected the additional root CAs and included "my" (apparently intermediary) CA, which worked:

require('ssl-root-cas/latest')
  .inject()
  .addFile(__dirname + '/comodohigh-assurancesecureserverca.crt');

Java keytool easy way to add server cert from url/port

There were a few ways I found to do this:

    java InstallCert [host]:[port] 
    keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert
    keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

How to run Gulp tasks sequentially one after the other

I generated a node/gulp app using the generator-gulp-webapp Yeoman generator. It handled the "clean conundrum" this way (translating to the original tasks mentioned in the question):

gulp.task('develop', ['clean'], function () {
  gulp.start('coffee');
});

Run an exe from C# code

Example:

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

Is the 'as' keyword required in Oracle to define an alias?

My conclusion is that(Tested on 12c):

  • AS is always optional, either with or without ""; AS makes no difference (column alias only, you can not use AS preceding table alias)
  • However, with or without "" does make difference because "" lets lower case possible for an alias

thus :

SELECT {T / t} FROM (SELECT 1 AS T FROM DUAL); -- Correct
SELECT "tEST" FROM (SELECT 1 AS "tEST" FROM DUAL); -- Correct
SELECT {"TEST" / tEST} FROM (SELECT 1 AS "tEST" FROM DUAL ); -- Incorrect

SELECT test_value AS "doggy" FROM test ORDER BY "doggy"; --Correct
SELECT test_value AS "doggy" FROM test WHERE "doggy" IS NOT NULL; --You can not do this, column alias not supported in WHERE & HAVING
SELECT * FROM test "doggy" WHERE "doggy".test_value IS NOT NULL; -- Do not use AS preceding table alias

So, the reason why USING AS AND "" causes problem is NOT AS

Note: "" double quotes are required if alias contains space OR if it contains lower-case characters and MUST show-up in Result set as lower-case chars. In all other scenarios its OPTIONAL and can be ignored.

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()

log4net hierarchy and logging levels

Here is some code telling about priority of all log4net levels:

TraceLevel(Level.All); //-2147483648

TraceLevel(Level.Verbose);   //  10 000
TraceLevel(Level.Finest);    //  10 000
    
TraceLevel(Level.Trace);     //  20 000
TraceLevel(Level.Finer);     //  20 000
    
TraceLevel(Level.Debug);     //  30 000
TraceLevel(Level.Fine);      //  30 000
    
TraceLevel(Level.Info);      //  40 000
TraceLevel(Level.Notice);    //  50 000
    
TraceLevel(Level.Warn);      //  60 000
TraceLevel(Level.Error);     //  70 000
TraceLevel(Level.Severe);    //  80 000
TraceLevel(Level.Critical);  //  90 000
TraceLevel(Level.Alert);     // 100 000
TraceLevel(Level.Fatal);     // 110 000
TraceLevel(Level.Emergency); // 120 000
    
TraceLevel(Level.Off); //2147483647


private static void TraceLevel(log4net.Core.Level level)
{
   Debug.WriteLine("{0} = {1}", level, level.Value);
}

Inner join of DataTables in C#

I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:

private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
    DataTable result = new DataTable();
    foreach (DataColumn col in t1.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataColumn col in t2.Columns)
    {
        if (result.Columns[col.ColumnName] == null)
            result.Columns.Add(col.ColumnName, col.DataType);
    }
    foreach (DataRow row1 in t1.Rows)
    {
        var joinRows = t2.AsEnumerable().Where(row2 =>
            {
                foreach (var parameter in joinOn)
                {
                    if (!parameter(row1, row2)) return false;
                }
                return true;
            });
        foreach (DataRow fromRow in joinRows)
        {
            DataRow insertRow = result.NewRow();
            foreach (DataColumn col1 in t1.Columns)
            {
                insertRow[col1.ColumnName] = row1[col1.ColumnName];
            }
            foreach (DataColumn col2 in t2.Columns)
            {
                insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
            }
            result.Rows.Add(insertRow);
        }
    }
    return result;
}

An example of how you might use this:

var test = JoinDataTables(transactionInfo, transactionItems,
               (row1, row2) =>
               row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));

One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

Recursively/deep update a dict

def deepupdate(original, update):
    """
    Recursively update a dict.
    Subdict's won't be overwritten but also updated.
    """
    for key, value in original.iteritems(): 
        if key not in update:
            update[key] = value
        elif isinstance(value, dict):
            deepupdate(value, update[key]) 
    return update

Demonstration:

pluto_original = {
    'name': 'Pluto',
    'details': {
        'tail': True,
        'color': 'orange'
    }
}

pluto_update = {
    'name': 'Pluutoo',
    'details': {
        'color': 'blue'
    }
}

print deepupdate(pluto_original, pluto_update)

Outputs:

{
    'name': 'Pluutoo',
    'details': {
        'color': 'blue',
        'tail': True
    }
}

Thanks rednaw for edits.

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Changing the CommandTimeout in SQL Management studio

Changing Command Execute Timeout in Management Studio:

Click on Tools -> Options

Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.

Changing Command Timeout in Server:

In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.

Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property

Remote query timeout (in seconds, 0 = no timeout):
[up/down control]

you can set the value in up/down control.

PHP Try and Catch for SQL Insert

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.

array filter in python?

This was just asked a couple of days ago (but I cannot find it):

>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = set([6, 9, 12])
>>> [i for i in A if i not in subset_of_A]
[7, 8, 10, 11]

It might be better to use sets from the beginning, depending on the context. Then you can use set operations like other answers show.

However, converting lists to sets and back only for these operations is slower than list comprehension.

COPY with docker but with exclusion

FOR A ONE LINER SOLUTION, type the following in Command prompt or Terminal at project root.

echo node_modules > .dockerignore

This creates the extension-less . prefixed file without any issue. Replace node_modules with the folder you want to exclude.

C# Clear Session

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.

What is the difference between Session.Abandon() and Session.Clear()

Clear - Removes all keys and values from the session-state collection.

Abandon - removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out. It also raises events like Session_End.

Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.

...

Generally, in most cases you need to use Session.Clear. You can use Session.Abandon if you are sure the user is going to leave your site.

So back to the differences:

  • Abandon raises Session_End request.
  • Clear removes items immediately, Abandon does not.
  • Abandon releases the SessionState object and its items so it can garbage collected.
  • Clear keeps SessionState and resources associated with it.

Session.Clear() or Session.Abandon() ?

You use Session.Clear() when you don't want to end the session but rather just clear all the keys in the session and reinitialize the session.

Session.Clear() will not cause the Session_End eventhandler in your Global.asax file to execute.

But on the other hand Session.Abandon() will remove the session altogether and will execute Session_End eventhandler.

Session.Clear() is like removing books from the bookshelf

Session.Abandon() is like throwing the bookshelf itself.

Question

I check on some sessions if not equal null in the page load. if one of them equal null i wanna to clear all the sessions and redirect to the login page?

Answer

If you want the user to login again, use Session.Abandon.

How can I find the link URL by link text with XPath?

Too late for you, but for anyone else with the same question...

//a[contains(text(), 'programming')]/@href

Of course, 'programming' can be any text fragment.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.

Transpose a data frame

You can use the transpose function from the data.table library. Simple and fast solution that keeps numeric values as numeric.

library(data.table)

# get data
  data("mtcars")

# transpose
  t_mtcars <- transpose(mtcars)

# get row and colnames in order
  colnames(t_mtcars) <- rownames(mtcars)
  rownames(t_mtcars) <- colnames(mtcars)

PHP Get name of current directory

$myVar = str_replace('/', '', $_SERVER[REQUEST_URI]);

libs/images/index.php
Result: images

Why SpringMVC Request method 'GET' not supported?

method = POST will work if you 'post' a form to the url /test.

if you type a url in address bar of a browser and hit enter, it's always a GET request, so you had to specify POST request.

Google for HTTP GET and HTTP POST (there are several others like PUT DELETE). They all have their own meaning.

git push: permission denied (public key)

This worked for me. Simplest solution by far.

If you are using GitHub for Windows and getting this error, the problem might be that you are trying to run the command in the wrong shell or mode. If you are trying to do git push origin master in the regular command prompt or PowerShell, this is the problem.

You need to do it in a git shell. Simply open Github for Windows, right click, and select "Open Shell Here". It looks like a regular PowerShell window, but it's not, which makes it really confusing for newbies to git, like myself.

I hope others find this useful.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

The steps I needed to perform were:

  1. Add reference to System.Web.Http.WebHost.
  2. Add App_Start\WebApiConfig.cs (see code snippet below).
  3. Import namespace System.Web.Http in Global.asax.cs.
  4. Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.
  5. Add a controller deriving from System.Web.Http.ApiController.

I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.

App_Start\WebApiConfig.cs:

using System.Web.Http;

class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });
    }
}

Global.asax.cs:

using System.Web.Http;

...

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Update 10.16.2015:

Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.

How to pass an array into a function, and return the results with an array

You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)

function foo(&$arr) { # note the &
  $arr[3] = $arr[0]+$arr[1]+$arr[2];
}
$waffles = array(1,2,3);
foo($waffles);
echo $waffles[3]; # prints 6

That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

Is it ok to scrape data from Google results?

Google will eventually block your IP when you exceed a certain amount of requests.

Artisan migrate could not find driver

I know this is a little late, nevertheless i'm answering this for anyone still experiencing this issue on windows (USING XAMPP).

Step 1. Verify that there is a mismatch in your PHP version. To do this, open routes/web.php and create a simple route to return the php information like so:

Route::get('/', function() {
   return response()->json([
    'stuff' => phpinfo()
   ]);
})

phpinfo

and compare this with output from your command line

enter image description here

As we can see, in my case there is a mismatch, this usually happens if you have multiple versions of php installed.

Step 2. Add the php version being used by your xampp to your system path enter image description here

Step 3. Verify that you have the extension enabled in your php.ini file. NB. Make sure you are editing the php.ini file that is shown under the 'loaded configuration file' entry in the results of phpinfo() command. enter image description here

Convert blob to base64

Another way is to use a simple wrapper around FileReader returning Observable:

  function toBase64(blob: Blob): Observable<string> {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return fromEvent(reader, 'load')
      .pipe(map(() => (reader.result as string).split(',')[1]));
  }

Usage:

toBase64(blob).subscribe(base64 => console.log(base64));

Which equals operator (== vs ===) should be used in JavaScript comparisons?

The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...

var x = 0;
var isTrue = x == null;
var isFalse = x === null;

Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...

CString x;
delete x;

Which obviously during runtime does very undefined things...

Google for implicit conversions in C++ and STL to get some of the arguments against it...

MySQL Delete all rows from table and reset ID to zero

if you want to use truncate use this:

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

How can I get all a form's values that would be submitted without submitting

In straight Javascript you could do something similar to the following:

var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
   var e = form.elements[i];
   kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var queryString = kvpairs.join("&");

In short, this creates a list of key-value pairs (name=value) which is then joined together using "&" as a delimiter.

Traverse a list in reverse order in Python

If you don't mind the index being negative, you can do:

>>> a = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
...     print(~i, a[~i]))
-1 baz
-2 bar
-3 foo

SELECT data from another schema in oracle

Depending on the schema/account you are using to connect to the database, I would suspect you are missing a grant to the account you are using to connect to the database.

Connect as PCT account in the database, then grant the account you are using select access for the table.

grant select on pi_int to Account_used_to_connect

Declaring & Setting Variables in a Select Statement

I have tried this and it worked:

define PROPp_START_DT = TO_DATE('01-SEP-1999')

select * from proposal where prop_start_dt = &PROPp_START_DT

 

Splitting comma separated string in a PL/SQL stored proc

Many good solutions have been provided already. However, if he text is provided in a very simple comma delimited format or similar, and speed is of importance, then I have for you a solution with a TABLE function (in PL/SQL). I have also provided a rundown of some other solutions.

Please see more on the Blog Entry on Parsing a CSV into multiple columns.

How to alter a column's data type in a PostgreSQL table?

See documentation here: http://www.postgresql.org/docs/current/interactive/sql-altertable.html

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE varchar (11);

How to access a RowDataPacket object

You can copy all enumerable own properties of an object to a new one by Object.assign(target, ...sources):

trivial_object = Object.assign({}, non_trivial_object);

so in your scenario, it should be enough to change

ret.push(i);

to

ret.push(Object.assign({}, i));

Why Response.Redirect causes System.Threading.ThreadAbortException?

There is no simple and elegant solution to the Redirect problem in ASP.Net WebForms. You can choose between the Dirty solution and the Tedious solution

Dirty: Response.Redirect(url) sends a redirect to the browser, and then throws a ThreadAbortedException to terminate the current thread. So no code is executed past the Redirect()-call. Downsides: It is bad practice and have performance implications to kill threads like this. Also, ThreadAbortedExceptions will show up in exception logging.

Tedious: The recommended way is to call Response.Redirect(url, false) and then Context.ApplicationInstance.CompleteRequest() However, code execution will continue and the rest of the event handlers in the page lifecycle will still be executed. (E.g. if you perform the redirect in Page_Load, not only will the rest of the handler be executed, Page_PreRender and so on will also still be called - the rendered page will just not be sent to the browser. You can avoid the extra processing by e.g. setting a flag on the page, and then let subsequent event handlers check this flag before before doing any processing.

(The documentation to CompleteRequest states that it "Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution". This can easily be misunderstood. It does bypass further HTTP filters and modules, but it doesn't bypass further events in the current page lifecycle.)

The deeper problem is that WebForms lacks a level of abstraction. When you are in a event handler, you are already in the process of building a page to output. Redirecting in an event handler is ugly because you are terminating a partially generated page in order to generate a different page. MVC does not have this problem since the control flow is separate from rendering views, so you can do a clean redirect by simply returning a RedirectAction in the controller, without generating a view.

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

How do I write JSON data to a file?

Writing JSON to a File

import json

data = {}
data['people'] = []
data['people'].append({
    'name': 'Scott',
    'website': 'stackabuse.com',
    'from': 'Nebraska'
})
data['people'].append({
    'name': 'Larry',
    'website': 'google.com',
    'from': 'Michigan'
})
data['people'].append({
    'name': 'Tim',
    'website': 'apple.com',
    'from': 'Alabama'
})

with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)

Reading JSON from a File

import json

with open('data.txt') as json_file:
    data = json.load(json_file)
    for p in data['people']:
        print('Name: ' + p['name'])
        print('Website: ' + p['website'])
        print('From: ' + p['from'])
        print('')

How can I upload fresh code at github?

git init
git add .
git commit -m "Initial commit"

After this, make a new GitHub repository and follow on-screen instructions.

phpmailer - The following SMTP Error: Data not accepted

your server dosen't allow different sender and username you should config: $mail->From like $mail->Username

PHP error: "The zip extension and unzip command are both missing, skipping."

PHP-ZIP needs some dependancies or library missing, depends on the image from Dockerfile you need to install them first

RUN set -eux \
   && apt-get update \
   && apt-get install -y libzip-dev zlib1g-dev \
   && docker-php-ext-install zip

How to read a file into vector in C++?

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
fstream dataFile;
string name , word , new_word;
vector<string> test;
char fileName[80];
cout<<"Please enter the file name : ";
cin >> fileName;
dataFile.open(fileName);
if(dataFile.fail())
{
     cout<<"File can not open.\n";
     return 0;
}
cout<<"File opened.\n";
cout<<"Please enter the word : ";
cin>>word;
cout<<"Please enter the new word : ";
cin >> new_word;
while (!dataFile.fail() && !dataFile.eof())
{
      dataFile >> name;
      test.push_back(name);
}
dataFile.close();

}

How to delete specific characters from a string in Ruby?

Here is an even shorter way of achieving this:

1) using Negative character class pattern matching

irb(main)> "((String1))"[/[^()]+/]
=> "String1"

^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )

Or with global substitution "AKA: gsub" like others have mentioned.

irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"

How to move an element down a litte bit in html

A simple way is to set line-height to the height of the element.

Android Paint: .measureText() vs .getTextBounds()

Sorry for answering again on that question... I needed to embed the image.

I think the results @mice found are missleading. The observations might be correct for the font size of 60 but they turn much more different when the text is smaller. Eg. 10px. In that case the text is actually drawn BEYOND the bounds.

enter image description here

Sourcecode of the screenshot:

  @Override
  protected void onDraw( Canvas canvas ) {
    for( int i = 0; i < 20; i++ ) {
      int startSize = 10;
      int curSize = i + startSize;
      paint.setTextSize( curSize );
      String text = i + startSize + " - " + TEXT_SNIPPET;
      Rect bounds = new Rect();
      paint.getTextBounds( text, 0, text.length(), bounds );
      float top = STEP_DISTANCE * i + curSize;
      bounds.top += top;
      bounds.bottom += top;
      canvas.drawRect( bounds, bgPaint );
      canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint );
    }
  }

What is the meaning of ToString("X2")?

It prints the byte in Hexadecimal format.

No format string: 13

'X2' format string: 0D

http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx

Formatting struct timespec

The following will return an ISO8601 and RFC3339-compliant UTC timestamp, including nanoseconds.

It uses strftime(), which works with struct timespec just as well as with struct timeval because all it cares about is the number of seconds, which both provide. Nanoseconds are then appended (careful to pad with zeros!) as well as the UTC suffix 'Z'.

Example output: 2021-01-19T04:50:01.435561072Z

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int utc_system_timestamp(char[]);

int main(void) {
    char buf[31];
    utc_system_timestamp(buf);
    printf("%s\n", buf);
}

// Allocate exactly 31 bytes for buf
int utc_system_timestamp(char buf[]) {
        const int bufsize = 31;
        struct timespec now;
        struct tm tm;
        int retval = clock_gettime(CLOCK_REALTIME, &now);
        gmtime_r(&now.tv_sec, &tm);
        strftime(buf, bufsize, "%Y-%m-%dT%H:%M:%S.", &tm);
        sprintf(buf, "%s%09luZ", buf, now.tv_nsec);
        return retval;
}

How do I cast a JSON Object to a TypeScript class?

In the lates TS you can do like this:

const isMyInterface = (val: any): val is MyInterface => {
  if (!val) { return false; }
  if (!val.myProp) { return false; }
  return true;
};

And than user like this:

if (isMyInterface(data)) {
 // now data will be type of MyInterface
}

How do I clone a job in Jenkins?

All above answers are good. But if you have created "folders" for your jobs, things are slightly different.

Click on the folder under which you want to create a new job. Then click "New Item" on the left menu. Now your "new job" URL will look like this (assuming you are creating the new job under "my-folder"):

http://my-jenkins:8080/job/my-folder/newJob

Under Enter an item name, enter your desired new job name. Then use the Copy from text box at the bottom. Enter job path of he source job.

E.g. If your source job is under folder src-folder and name of the job is src-job, you will have to enter src-folder/src-job in "Copy from" box.

Hope it helps.

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

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

First part of accepted answer does not work for MSSQL.
This worked for me:

select email, COUNT(*) as C from table 
group by email having COUNT(*) >1 order by C desc

How do you set up use HttpOnly cookies in PHP

<?php
//None HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, FALSE); 

//HttpOnly cookie:
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE); 

?>

Source

How can I create a Java method that accepts a variable number of arguments?

This is just an extension to above provided answers.

  1. There can be only one variable argument in the method.
  2. Variable argument (varargs) must be the last argument.

Clearly explained here and rules to follow to use Variable Argument.

Android add placeholder text to EditText

You have to use the android:hint attribute

<EditText
android:id="@+id/message"
android:hint="<<Your placeholder>>"
/>

In Android Studio, you can switch from XML -> Design View and click on the Component in the layout, the EditText field in this case. This will show all the applicable attributes for that GUI component. This will be handy when you don't know about all the attributes that are there.

You would be surprised to see that EditText has more than 140 attributes for customization.

How do I center align horizontal <UL> menu?

Try this:

div.topmenu-design ul
{
  display:block;
  width:600px; /* or whatever width value */
  margin:0px auto;
}

Paritition array into N chunks with Numpy

Try numpy.array_split.

From the documentation:

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]

Identical to numpy.split, but won't raise an exception if the groups aren't equal length.

If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a, then you can remove empty arrays by:

[x for x in a if x.size > 0]

Just save that back in a if you wish.

Get full path of the files in PowerShell

Add | select FullName to the end of your line above. If you need to actually do something with that afterwards, you might have to pipe it into a foreach loop, like so:

get-childitem "C:\windows\System32" -recurse | where {$_.extension -eq ".txt"} | % {
     Write-Host $_.FullName
}

How to remove certain characters from a string in C++?

I want to remove the "(", ")", and "-" characters from the string.

You can use the std::remove_if() algorithm to remove only the characters you specify:

#include <iostream>
#include <algorithm>
#include <string>

bool IsParenthesesOrDash(char c)
{
    switch(c)
    {
    case '(':
    case ')':
    case '-':
        return true;
    default:
        return false;
    }
}

int main()
{
    std::string str("(555) 555-5555");
    str.erase(std::remove_if(str.begin(), str.end(), &IsParenthesesOrDash), str.end());
    std::cout << str << std::endl; // Expected output: 555 5555555
}

The std::remove_if() algorithm requires something called a predicate, which can be a function pointer like the snippet above.

You can also pass a function object (an object that overloads the function call () operator). This allows us to create an even more general solution:

#include <iostream>
#include <algorithm>
#include <string>

class IsChars
{
public:
    IsChars(const char* charsToRemove) : chars(charsToRemove) {};

    bool operator()(char c)
    {
        for(const char* testChar = chars; *testChar != 0; ++testChar)
        {
            if(*testChar == c) { return true; }
        }
        return false;
    }

private:
    const char* chars;
};

int main()
{
    std::string str("(555) 555-5555");
    str.erase(std::remove_if(str.begin(), str.end(), IsChars("()- ")), str.end());
    std::cout << str << std::endl; // Expected output: 5555555555
}

You can specify what characters to remove with the "()- " string. In the example above I added a space so that spaces are removed as well as parentheses and dashes.

Get a list of all git commits, including the 'lost' ones

git log --reflog

saved me! I lost mine while merging HEAD and could not find my lates commit! Not showing in source tree but git log --reflog show all my local commits before

Getting time elapsed in Objective-C

NSDate *start = [NSDate date];
// do stuff...
NSTimeInterval timeInterval = [start timeIntervalSinceNow];

timeInterval is the difference between start and now, in seconds, with sub-millisecond precision.

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());

This works for me.

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

The problem:

Microsoft Office 2010 products (or later) install updates that break compatibility of MSCOMCTL.ocx and COMCTL32.ocx. Unfortunately this affects many other programs such Visual Basic 6 SP6 and even Oracle Virtual Box v5. The actual problem is HKEY_CLASSES_ROOT\TypeLib\{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}\2.0 registry key. You can find detailed background information about this problem here.

Here is another working solution:

The solution assumes you have not damaged your registry by deleting, replacing and re-registering MSCOMCTL.ocx and COMCTL32.ocx without unregistering the Office patch files.

Create a batch file called fix.cmd and place the following commands in it:

regsvr32 /s /u %windir%\SysWOW64\comctl32.ocx
regsvr32 /s /u %windir%\SysWOW64\mscomctl.ocx
del /y %windir%\SysWOW64\comctl32.ocx
del /y %windir%\SysWOW64\mscomctl.ocx
msiexec /passive /norestart /i KB2708437.msi
msiexec /passive /a KB2708437.msi
regtlib %windir%\SysWOW64\msdatsrc.tlb

Download from Security update for Visual Basic 6.0 Service Pack 6: August 14, 2012 the msi file and rename it to KB2708437.msi.

Note: A direct link to the Service Pack 6 download is located HERE.

Run fix.cmd and the problem will be fixed!

What fix.cmd does is to properly unregister and then delete the current MSCOMCTL.ocx and COMCTL32.ocx files, and then apply the latest Visual Basic 6 SP6 rollup patch. In fact, the script enforces the patch to be installed and then re-installed by updating every file, regardless of version. Finally it registers msdatsrc.tlb type library.

Please let me know if this works for you.

======================================================================

Advanced Solution:

If however you have accidentally damaged your registry, you need to get as many versions of MSCOMCTL.ocx and COMCTL32.ocx you can find. Then you need to start from the newer version going back to the older and register and unregister the ocx files.

The latest version of MSCOMCTL.ocx is 6.1.98.39 (v2.1) of May 2012 which is more likely the one installed on your system and causing all your problems.

The oldest (legacy) version is that shipped with Visual Basic 6 on 1998 6.1.97.82 (v2.0), or the one shipped with an early service pack 6.1.97.86 on April 2005.

Example:

regsvr32 /s comctl32.6.0.98.34.ocx
regsvr32 /s /u comctl32.6.0.98.34.ocx

regsvr32 /s comctl32.6.0.81.6.ocx
regsvr32 /s /u comctl32.6.0.81.6.ocx 

regsvr32 /s comctl32.6.0.81.5.ocx
regsvr32 /s /u comctl32.6.0.81.5.ocx

regsvr32 /s mscomctl.6.1.98.39.(2.1).ocx
regsvr32 /s /u mscomctl.6.1.98.39.(2.1).ocx

regsvr32 /s mscomctl.6.1.98.34.ocx
regsvr32 /s /u mscomctl.6.1.98.34.ocx

regsvr32 /s mscomctl.6.1.97.86.ocx
regsvr32 /s /u mscomctl.6.1.97.86.ocx

regsvr32 /s mscomctl.6.1.97.82.(2.0).ocx
regsvr32 /s /u mscomctl.6.1.97.82.(2.0).ocx

regsvr32 /s /u %windir%\SysWOW64\comctl32.ocx
regsvr32 /s /u %windir%\SysWOW64\mscomctl.ocx

del /q %windir%\SysWOW64\comctl32.ocx
del /q %windir%\SysWOW64\mscomctl.ocx

msiexec /passive /norestart /i KB2708437.msi
msiexec /passive /a KB2708437.msi

regtlib %windir%\SysWOW64\msdatsrc.tlb   

WARNING:

Do not search the internet for those files. To find different version of the OCX files download and extract official Microsoft Installer packages such as the following:

2005 Apr - Microsoft KB896559

2008 Dec - Microsoft KB926857

2009 Apr - Microsoft KB957924

2012 May - Microsoft KB2708437

It is also recommended to run CCleaner version 4.0 or later to fix any other ActiveX related problems on your computer.

What's the source of Error: getaddrinfo EAI_AGAIN?

Enabled Blaze and it still doesn't work?

Most probably you need to set .env from the right path, require('dotenv').config({ path: __dirname + './../.env' }); won't work (or any other path). Simply put the .env file in the functions directory, from which you deploy to Firebase.

DateTime "null" value

You can set the DateTime to Nullable. By default DateTime is not nullable. You can make it nullable in a couple of ways. Using a question mark after the type DateTime? myTime or using the generic style Nullable.

DateTime? nullDate = null;

or

DateTime? nullDate;

How to group an array of objects by key

You can also make use of array#forEach() method like this:

_x000D_
_x000D_
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];_x000D_
_x000D_
let newcars = {}_x000D_
_x000D_
cars.forEach(car => {_x000D_
  newcars[car.make] ? // check if that array exists or not in newcars object_x000D_
    newcars[car.make].push({model: car.model, year: car.year})  // just push_x000D_
   : (newcars[car.make] = [], newcars[car.make].push({model: car.model, year: car.year})) // create a new array and push_x000D_
})_x000D_
_x000D_
console.log(newcars);
_x000D_
_x000D_
_x000D_

The APK file does not exist on disk

I tried all of these things and none of them worked. I ended up having to do a couple of these things are the same time. Very frustrating that it took this much time.

The problem I had was related to running my unit tests following the upgrade to AS 3.1.

Here is what I did... 1.) Run / Edit Configurations / Select Tests.... 2.) Add options to "Gradle-aware Make" 3.) Select check box "Skip installation if ADK has not changed" on Misc tab

Good luck.

What is the difference between a candidate key and a primary key?

John Woo's answer is correct, as far as it goes. Here are a few additional points.

A primary key is always one of the candidate keys. Fairly often, it's the only candidate.

A table with no candidate keys does not represent a relation. If you're using the relational model to help you build a good database, then every table you design will have at least one candidate key.

The relational model would be complete without the concept of primary key. It wasn't in the original presentation of the relational model. As a practical matter, the use of foreign key references without a declared primary key leads to a mess. It could be a logically correct mess, but it's a mess nonetheless. Declaring a primary key lets the DBMS help you enforce the data rules. Most of the time, having the DBMS help you enforce the data rules is a good thing, and well worth the cost.

Some database designers and some users have some mental confusion about whether the primary key identifies a row (record) in a table or an instance of an entity in the subject matter that the table represents. In an ideal world, it's supposed to do both, and there should be a one-for-one correspondence between rows in an entity table and instances of the corresponding entity.

In the real world, things get screwed up. Somebody enters the same new employee twice, and the employee ends up with two ids. Somebody gets hired, but the data entry slips through the cracks in some manual process, and the employee doesn't get an id, until the omission is corrected. A database that does not collapse the first time things get screwed up is more robust than one that does.

Select SQL Server database size

You can check how this query works following this link.

    IF OBJECT_ID('tempdb..#spacetable') IS NOT NULL 
    DROP TABLE tempdb..#spacetable 
    create table #spacetable
    (
    database_name varchar(50) ,
    total_size_data int,
    space_util_data int,
    space_data_left int,
    percent_fill_data float,
    total_size_data_log int,
    space_util_log int,
    space_log_left int,
    percent_fill_log char(50),
    [total db size] int,
    [total size used] int,
    [total size left] int
    )
    insert into  #spacetable
    EXECUTE master.sys.sp_MSforeachdb 'USE [?];
    select x.[DATABASE NAME],x.[total size data],x.[space util],x.[total size data]-x.[space util] [space left data],
    x.[percent fill],y.[total size log],y.[space util],
    y.[total size log]-y.[space util] [space left log],y.[percent fill],
    y.[total size log]+x.[total size data] ''total db size''
    ,x.[space util]+y.[space util] ''total size used'',
    (y.[total size log]+x.[total size data])-(y.[space util]+x.[space util]) ''total size left''
     from (select DB_NAME() ''DATABASE NAME'',
    sum(size*8/1024) ''total size data'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
    ,case when sum(size*8/1024)=0 then ''divide by zero'' else
    substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
    from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=0
    group by type_desc  ) as x ,
    (select 
    sum(size*8/1024) ''total size log'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
    ,case when sum(size*8/1024)=0 then ''divide by zero'' else
    substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
    from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=1
    group by type_desc  )y'
    select * from #spacetable 
    order by database_name
    drop table #spacetable

Delete files older than 10 days using shell script in Unix

If you can afford working via the file data, you can do

find -mmin +14400 -delete

Set equal width of columns in table layout in Android

Try this.

It boils down to adding android:stretchColumns="*" to your TableLayout root and setting android:layout_width="0dp" to all the children in your TableRows.

<TableLayout
    android:stretchColumns="*"   // Optionally use numbered list "0,1,2,3,..."
>
    <TableRow
        android:layout_width="0dp"
    >

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

How to specify the private SSH-key to use when executing shell command on Git?

None of these solutions worked for me.

Instead, I elaborate on @Martin v. Löwis 's mention of setting a config file for SSH.

SSH will look for the user's ~/.ssh/config file. I have mine setup as:

Host gitserv
    Hostname remote.server.com
    IdentityFile ~/.ssh/id_rsa.github
    IdentitiesOnly yes # see NOTES below

And I add a remote git repository:

git remote add origin git@gitserv:myrepo.git

And then git commands work normally for me.

git push -v origin master

NOTES

  • The IdentitiesOnly yes is required to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. If you have a file named ~/.ssh/id_rsa that will get tried BEFORE your ~/.ssh/id_rsa.github without this option.

References

How to iterate object keys using *ngFor

If you are using a map() operator on your response,you could maybe chain a toArray() operator to it...then you should be able to iterate through newly created array...at least that worked for me :)

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

How to run script as another user without password?

Call visudo and add this:

user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh

The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh from a user1 shell. Done.

Simplest way to do grouped barplot

I wrote a function wrapper called bar() for barplot() to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do

bar(dv = Species, 
    factors = c(Category, Reason), 
    dataframe = Reasonstats, 
    errbar = FALSE, 
    ylim=c(0, 140))  #I increased the upper y-limit to accommodate the legend. 

The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE

enter image description here

How to insert an element after another element in JavaScript without using a library?

This code is work to insert a link item right after the last existing child to inlining a small css file

var raf, cb=function(){
    //create newnode
    var link=document.createElement('link');
    link.rel='stylesheet';link.type='text/css';link.href='css/style.css';

    //insert after the lastnode
    var nodes=document.getElementsByTagName('link'); //existing nodes
    var lastnode=document.getElementsByTagName('link')[nodes.length-1]; 
    lastnode.parentNode.insertBefore(link, lastnode.nextSibling);
};

//check before insert
try {
    raf=requestAnimationFrame||
        mozRequestAnimationFrame||
        webkitRequestAnimationFrame||
        msRequestAnimationFrame;
}
catch(err){
    raf=false;
}

if (raf)raf(cb); else window.addEventListener('load',cb);

Div Background Image Z-Index Issue

For z-index to work, you also need to give it a position:

header {
    width: 100%;
    height: 100px;
    background: url(../img/top.png) repeat-x;
    z-index: 110;
    position: relative;
}