Programs & Examples On #Facebook chat

For questions relating to Facebook's Chat API (now deprecated with v2.0)

Running Facebook application on localhost

Forward is a great tool for helping with development of facebook apps locally, it supports SSL so the cert thing isn't a problem.

https://forwardhq.com/in-use/facebook

DISCLAIMER: I'm one of the devs

Background color of text in SVG

this is my favorite hack (not sure it should work). It refer an element that is not yet displayed, and it works pretty well

_x000D_
_x000D_
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 620 40" preserveAspectRatio="xMidYMid meet">_x000D_
    <defs>_x000D_
        <filter x="-0.02" y="0" width="1.04" height="1.1" id="removebackground">_x000D_
            <feFlood flood-color="#00ffff"/>_x000D_
        </filter>_x000D_
    </defs>_x000D_
_x000D_
    <!--Draw the text--> _x000D_
    <use xlink:href="#mygroup" filter="url(#removebackground)" />_x000D_
    <g id="mygroup">_x000D_
        <text id="text1" x="9" y="20" style="text-anchor:start;font-size:14px;">custom text with background</text>  _x000D_
        <line x1="200" y1="18" x2="200" y2="36" stroke="#000" stroke-width="5"/> _x000D_
        <line x1="120" y1="27" x2="203" y2="27" stroke="#000" stroke-width="5"/> _x000D_
    </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How to SSH to a VirtualBox guest externally through a host?

How to do host-only network (better than bridged) for Solaris 10 and Ubuntu 16.04

Add Host-only interface

  1. Virtualbox > File > Preferences > Network > Host-only Networks > Add
  2. Shutdown vm.
  3. VM's Settings > Network. First adapter should be Nat, second Host-only.
  4. Start cmd.exe and run ipconfig /all. You should see lines:

    Ethernet adapter VirtualBox Host-Only Network:
       ...
       IPv4 Address. . . . . . . . . . . : 192.168.59.1
    

    Second adapter in guest should also be in 192.168.59.*.

  5. Start VM.

Solaris 10

  1. Check settings ifconfig -a. You should see e1000g0 and e1000g1. We are interested in e1000g1.
  2. ifconfig e1000g down
  3. ifconfig e1000g 192.168.56.10 netmask 255.255.255.0 up
  4. Check from host if this interface is reachable: ping 192.168.56.10

Preserve those settings upon reboot

# vi /etc/hostname.e1000g1
192.168.56.10 netmask 255.255.255.0
# reboot

Configure ssh service (administering) to login as root (not adviced)

Check if ssh is enabled

# svcs -a | grep ssh
online         15:29:57 svc:/network/ssh:default

Modify /etc/ssh/sshd_config so there is

PermitRootLogin yes

Restart ssh service

svcadm restart ssh

From host check it

ssh [email protected]

Ubuntu 16.04

List interfaces:

ip addr

You should see three interfaces like lo, enp0s3, enp0s8. We will use the third.

Edit /etc/network/interfaces

auto enp0s8
iface enp0s8 inet static
    address 192.168.56.10
    netmask 255.255.255.0

Then sudo ifup enp0s8. Check if enp0s8 got correct address. You should see your ip:

 $ ip addr show enp0s8
 ...
    inet 192.168.56.10/24 brd 192.168.56.255 scope global secondary enp0s8

If not, you may run sudo ifdown enp0s8 && sudo ifup enp0s8

https://superuser.com/questions/424083/virtualbox-host-ssh-to-guest/424115#424115

How to embed a Google Drive folder in a website

At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:

<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>

In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.

To get the API key:

1.) Go to https://console.developers.google.com/ Create a new project.

2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.

3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.

4.) Copy the newly generated API key.

To get the folder ID:

1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.

2.) Copy the part after 'folders/', this is your folder ID.

Now put both the API key and folder id in the above code and embed.

Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.

I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.

The file preview looks like this The content of the iframe looks like this

How do you properly use namespaces in C++?

I did not see any mention of it in the other answers, so here are my 2 Canadian cents:

On the "using namespace" topic, a useful statement is the namespace alias, allowing you to "rename" a namespace, normally to give it a shorter name. For example, instead of:

Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;

you can write:

namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;
Shorter::TheClassName foo;
Shorter::AnotherClassName bar;

How to get the total number of rows of a GROUP BY query?

You have to use rowCount — Returns the number of rows affected by the last SQL statement

$query = $dbh->prepare("SELECT * FROM table_name");
$query->execute();
$count =$query->rowCount();
echo $count;

$apply already in progress error

You are getting this error because you are calling $apply inside an existing digestion cycle.

The big question is: why are you calling $apply? You shouldn't ever need to call $apply unless you are interfacing from a non-Angular event. The existence of $apply usually means I am doing something wrong (unless, again, the $apply happens from a non-Angular event).

If $apply really is appropriate here, consider using a "safe apply" approach:

https://coderwall.com/p/ngisma

Advantages of SQL Server 2008 over SQL Server 2005?

Be aware that a lot of the really killer features are only in Enterprise Edition. Data compression and backup compression are among two of my top favorites - they give you free performance improvements right off the bat. Data compression lessens the amount of I/O you have to do, so a lot of queries speed up 20-40%. CPU use goes up, but in today's multi-core environments, we often have more CPU power but not more IO. Anyway, those are only in Enterprise.

If you're only going to use Standard Edition, then most of the improvements require changes to your application code and T-SQL code, so it's not quite as easy of a sell.

Python Pandas - Find difference between two data frames

In addition to accepted answer, I would like to propose one more wider solution that can find a 2D set difference of two dataframes with any index/columns (they might not coincide for both datarames). Also method allows to setup tolerance for float elements for dataframe comparison (it uses np.isclose)


import numpy as np
import pandas as pd

def get_dataframe_setdiff2d(df_new: pd.DataFrame, 
                            df_old: pd.DataFrame, 
                            rtol=1e-03, atol=1e-05) -> pd.DataFrame:
    """Returns set difference of two pandas DataFrames"""

    union_index = np.union1d(df_new.index, df_old.index)
    union_columns = np.union1d(df_new.columns, df_old.columns)

    new = df_new.reindex(index=union_index, columns=union_columns)
    old = df_old.reindex(index=union_index, columns=union_columns)

    mask_diff = ~np.isclose(new, old, rtol, atol)

    df_bool = pd.DataFrame(mask_diff, union_index, union_columns)

    df_diff = pd.concat([new[df_bool].stack(),
                         old[df_bool].stack()], axis=1)

    df_diff.columns = ["New", "Old"]

    return df_diff

Example:

In [1]

df1 = pd.DataFrame({'A':[2,1,2],'C':[2,1,2]})
df2 = pd.DataFrame({'A':[1,1],'B':[1,1]})

print("df1:\n", df1, "\n")

print("df2:\n", df2, "\n")

diff = get_dataframe_setdiff2d(df1, df2)

print("diff:\n", diff, "\n")
Out [1]

df1:
   A  C
0  2  2
1  1  1
2  2  2 

df2:
   A  B
0  1  1
1  1  1 

diff:
     New  Old
0 A  2.0  1.0
  B  NaN  1.0
  C  2.0  NaN
1 B  NaN  1.0
  C  1.0  NaN
2 A  2.0  NaN
  C  2.0  NaN 

How do I center a window onscreen in C#?

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

What's the purpose of META-INF?

From the official JAR File Specification (link goes to the Java 7 version, but the text hasn't changed since at least v1.3):

The META-INF directory

The following files/directories in the META-INF directory are recognized and interpreted by the Java 2 Platform to configure applications, extensions, class loaders and services:

  • MANIFEST.MF

The manifest file that is used to define extension and package related data.

  • INDEX.LIST

This file is generated by the new "-i" option of the jar tool, which contains location information for packages defined in an application or extension. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process.

  • x.SF

The signature file for the JAR file. 'x' stands for the base file name.

  • x.DSA

The signature block file associated with the signature file with the same base file name. This file stores the digital signature of the corresponding signature file.

  • services/

This directory stores all the service provider configuration files.

What does the "$" sign mean in jQuery or JavaScript?

In jQuery, the $ sign is just an alias to jQuery(), then an alias to a function.

This page reports:

Basic syntax is: $(selector).action()

  • A dollar sign to define jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)

jquery toggle slide from left to right and back

Hide #categories initially

#categories {
    display: none;
}

and then, using JQuery UI, animate the Menu slowly

var duration = 'slow';

$('#cat_icon').click(function () {
    $('#cat_icon').hide(duration, function() {
        $('#categories').show('slide', {direction: 'left'}, duration);});
});
$('.panel_title').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

You can use any time in milliseconds as well

var duration = 2000;

If you want to hide on class='panel_item' too, select both panel_title and panel_item

$('.panel_title,.panel_item').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

You need to understand the content in M2E_plugin_execution_not_covered and follow the steps mentioned below:

  • Pick org.eclipse.m2e.lifecyclemapping.defaults jar from the eclipse plugin folder
  • Extract it and open lifecycle-mapping-metadata.xml where you can find all the pluginExecutions.
  • Add the pluginExecutions of your plugins which are shown as errors with <ignore/> under <action> tags.

eg: for write-project-properties error, add this snippet under the <pluginExecutions> section of the lifecycle-mapping-metadata.xml file:

 <pluginExecution>
    <pluginExecutionFilter>
       <groupId>org.codehaus.mojo</groupId>
       <artifactId>properties-maven-plugin</artifactId>
       <versionRange>1.0-alpha-2</versionRange>
       <goals>
         <goal>write-project-properties</goal>
       </goals>
    </pluginExecutionFilter>
     <action>
       <ignore />
     </action>
   </pluginExecution>
  • Replace that XML file in the JAR
  • Replace the updated JAR in Eclipse's plugin folder
  • Restart Eclipse

You should see no errors in the future for any project.

Remove style attribute from HTML tags

$html = preg_replace('/\sstyle=("|\').*?("|\')/i', '', $html);

For replacing all style="" with blank.

WebService Client Generation Error with JDK8

Another alternative is to update wsimport.sh shell script by adding the following:

The wsimport.sh is located in this directory:

jaxws-ri.2.2.28/bin

exec "$JAVA" $WSIMPORT_OPTS -Djavax.xml.accessExternalSchema=all -jar "$JAXWS_HOME/lib/jaxws-tools.jar" "$@"

How can I add a table of contents to a Jupyter / JupyterLab notebook?

There is an ipython nbextension that constructs a table of contents for a notebook. It seems to only provide navigation, not section folding.

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

Remove columns from dataframe where ALL values are NA

The two approaches offered thus far fail with large data sets as (amongst other memory issues) they create is.na(df), which will be an object the same size as df.

Here are two approaches that are more memory and time efficient

An approach using Filter

Filter(function(x)!all(is.na(x)), df)

and an approach using data.table (for general time and memory efficiency)

library(data.table)
DT <- as.data.table(df)
DT[,which(unlist(lapply(DT, function(x)!all(is.na(x))))),with=F]

examples using large data (30 columns, 1e6 rows)

big_data <- replicate(10, data.frame(rep(NA, 1e6), sample(c(1:8,NA),1e6,T), sample(250,1e6,T)),simplify=F)
bd <- do.call(data.frame,big_data)
names(bd) <- paste0('X',seq_len(30))
DT <- as.data.table(bd)

system.time({df1 <- bd[,colSums(is.na(bd) < nrow(bd))]})
# error -- can't allocate vector of size ...
system.time({df2 <- bd[, !apply(is.na(bd), 2, all)]})
# error -- can't allocate vector of size ...
system.time({df3 <- Filter(function(x)!all(is.na(x)), bd)})
## user  system elapsed 
## 0.26    0.03    0.29 
system.time({DT1 <- DT[,which(unlist(lapply(DT, function(x)!all(is.na(x))))),with=F]})
## user  system elapsed 
## 0.14    0.03    0.18 

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

This is a quirk of the C grammar. A label (Cleanup:) is not allowed to appear immediately before a declaration (such as char *str ...;), only before a statement (printf(...);). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.

You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:

int main (void) 
{
    char *str;
    printf("Hello ");
    goto Cleanup;
Cleanup:
    str = "World\n";
    printf("%s\n", str);
    return 0;
}

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

What is the difference between docker-compose ports vs expose

ports:

  1. Activates the container to listen for specified port(s) from the world outside of the docker(can be same host machine or a different machine) AND also accessible world inside docker.
  2. More than one port can be specified (that's is why ports not port)

enter image description here

expose:

  1. Activates container to listen for a specific port only from the world inside of docker AND not accessible world outside of the docker.
  2. More than one port can be specified

enter image description here

C# DateTime to UTC Time without changing the time

Use the DateTime.ToUniversalTime method.

TSQL - Cast string to integer or return default value

As has been mentioned, you may run into several issues if you use ISNUMERIC:

-- Incorrectly gives 0:
SELECT CASE WHEN ISNUMERIC('-') = 1 THEN CAST('-' AS INT) END   

-- Error (conversion failure):
SELECT CASE WHEN ISNUMERIC('$') = 1 THEN CAST('$' AS INT) END
SELECT CASE WHEN ISNUMERIC('4.4') = 1 THEN CAST('4.4' AS INT) END
SELECT CASE WHEN ISNUMERIC('1,300') = 1 THEN CAST('1,300' AS INT) END

-- Error (overflow):
SELECT CASE WHEN ISNUMERIC('9999999999') = 1 THEN CAST('9999999999' AS INT) END

If you want a reliable conversion, you'll need to code one yourself.

Update: My new recommendation would be to use an intermediary test conversion to FLOAT to validate the number. This approach is based on adrianm's comment. The logic can be defined as an inline table-valued function:

CREATE FUNCTION TryConvertInt (@text NVARCHAR(MAX)) 
RETURNS TABLE
AS
RETURN
(
    SELECT
        CASE WHEN ISNUMERIC(@text + '.e0') = 1 THEN 
             CASE WHEN CONVERT(FLOAT, @text) BETWEEN -2147483648 AND 2147483647 
                  THEN CONVERT(INT, @text) 
             END 
         END AS [Result]
)

Some tests:

SELECT [Conversion].[Result]
FROM ( VALUES
     ( '1234'                     )   -- 1234
   , ( '1,234'                    )   -- NULL
   , ( '1234.0'                   )   -- NULL
   , ( '-1234'                    )   -- -1234
   , ( '$1234'                    )   -- NULL
   , ( '1234e10'                  )   -- NULL
   , ( '1234 5678'                )   -- NULL
   , ( '123-456'                  )   -- NULL
   , ( '1234.5'                   )   -- NULL
   , ( '123456789000000'          )   -- NULL
   , ( 'N/A'                      )   -- NULL
   , ( '-'                        )   -- NULL
   , ( '$'                        )   -- NULL
   , ( '4.4'                      )   -- NULL
   , ( '1,300'                    )   -- NULL
   , ( '9999999999'               )   -- NULL
   , ( '00000000000000001234'     )   -- 1234
   , ( '212110090000000235698741' )   -- NULL
) AS [Source] ([Text])
OUTER APPLY TryConvertInt ([Source].[Text]) AS [Conversion]

Results are similar to Joseph Sturtevant's answer, with the following main differences:

  • My logic does not tolerate occurrences of . or , in order to mimic the behaviour of native INT conversions. '1,234' and '1234.0' return NULL.
  • Since it does not use local variables, my function can be defined as an inline table-valued function, allowing for better query optimization.
  • Joseph's answer can lead to incorrect results due to silent truncations of the argument; '00000000000000001234' evaluates to 12. Increasing the parameter length would result in errors on numbers that overflow BIGINT, such as BBANs (basic bank account numbers) like '212110090000000235698741'.

Withdrawn: The approach below is no longer recommended, as is left just for reference.

The snippet below works on non-negative integers. It checks that your string does not contain any non-digit characters, is not empty, and does not overflow (by exceeding the maximum value for the int type). However, it also gives NULL for valid integers whose length exceeds 10 characters due to leading zeros.

SELECT 
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 
                OR LEN(@text) = 10 AND @text <= '2147483647' 
              THEN CAST (@text AS INT)
         END
    END 

If you want to support any number of leading zeros, use the below. The nested CASE statements, albeit unwieldy, are required to promote short-circuit evaluation and reduce the likelihood of errors (arising, for example, from passing a negative length to LEFT).

SELECT 
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
              WHEN LEN(@text) >= 10 THEN
              CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
                    AND RIGHT(@text, 10) <= '2147483647'
                   THEN CAST (@text AS INT)
              END
         END
    END

If you want to support positive and negative integers with any number of leading zeros:

SELECT 
         -- Positive integers (or 0):
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
              WHEN LEN(@text) >= 10 THEN
              CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
                    AND RIGHT(@text, 10) <= '2147483647'
                   THEN CAST (@text AS INT)
              END
         END
         -- Negative integers:
         WHEN LEFT(@text, 1) = '-' THEN
         CASE WHEN RIGHT(@text, LEN(@text) - 1) NOT LIKE '%[^0-9]%' THEN
              CASE WHEN LEN(@text) BETWEEN 2 AND 10 THEN CAST (@text AS INT)
                   WHEN LEN(@text) >= 11 THEN
                   CASE WHEN SUBSTRING(@text, 2, LEN(@text) - 11) NOT LIKE '%[^0]%'
                         AND RIGHT(@text, 10) <= '2147483648'
                        THEN CAST (@text AS INT)
                   END
              END
         END
    END

How do I convert an interval into a number of hours with postgres?

If you want integer i.e. number of days:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int

How do I find out if first character of a string is a number?

IN KOTLIN :

Suppose that you have a String like this :

private val phoneNumber="9121111111"

At first you should get the first one :

val firstChar=phoneNumber.slice(0..0)

At second you can check the first char that return a Boolean :

firstChar.isInt() // or isFloat()

Convert command line argument to string

#include <iostream>

std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));

Do conditional INSERT with SQL?

It is possible with EXISTS condition. WHERE EXISTS tests for the existence of any records in a subquery. EXISTS returns true if the subquery returns one or more records. Here is an example

UPDATE  TABLE_NAME 
SET val1=arg1 , val2=arg2
WHERE NOT EXISTS
    (SELECT FROM TABLE_NAME WHERE val1=arg1 AND val2=arg2)

py2exe - generate single executable file

No, it's doesn't give you a single executable in the sense that you only have one file afterwards - but you have a directory which contains everything you need for running your program, including an exe file.

I just wrote this setup.py today. You only need to invoke python setup.py py2exe.

Undefined Reference to

Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:

foo.h:

namespace foo {
    void bar();
}

foo.cc:

namespace foo {
    namespace {  // wrong
        void bar() { cout << "hello"; };
    }
}

other.cc file:

#include "foo.h"

void baz() {
    foo::bar();
}

Submit HTML form, perform javascript function (alert then redirect)

You need to prevent the default behaviour. You can either use e.preventDefault() or return false; In this case, the best thing is, you can use return false; here:

<form onsubmit="completeAndRedirect(); return false;">

Javascript, Change google map marker color

In Google Maps API v3 you can try changing marker icon. For example for green icon use:

marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')

Or as part of marker init:

marker = new google.maps.Marker({
    icon: 'http://...'
});

Other colors:

Etc.

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

HTML Submit-button: Different value / button-text?

Following the @greg0ire suggestion in comments:

<input type="submit" name="add_tag" value="Lägg till tag" />

In your server side, you'll do something like:

if (request.getParameter("add_tag") != null)
    tags.addTag( /*...*/ );

(Since I don't know that language (java?), there may be syntax errors.)

I would prefer the <button> solution, but it doesn't work as expected on IE < 9.

How do you change the value inside of a textfield flutter?

Simply change the text property

    TextField(
      controller: txt,
    ),
    RaisedButton(onPressed: () {
        txt.text = "My Stringt";
    }),

while txt is just a TextEditingController

  var txt = TextEditingController();

Algorithm for Determining Tic Tac Toe Game Over

If the board is n × n then there are n rows, n columns, and 2 diagonals. Check each of those for all-X's or all-O's to find a winner.

If it only takes x < n consecutive squares to win, then it's a little more complicated. The most obvious solution is to check each x × x square for a winner. Here's some code that demonstrates that.

(I didn't actually test this *cough*, but it did compile on the first try, yay me!)

public class TicTacToe
{
    public enum Square { X, O, NONE }

    /**
     * Returns the winning player, or NONE if the game has
     * finished without a winner, or null if the game is unfinished.
     */
    public Square findWinner(Square[][] board, int lengthToWin) {
        // Check each lengthToWin x lengthToWin board for a winner.    
        for (int top = 0; top <= board.length - lengthToWin; ++top) {
            int bottom = top + lengthToWin - 1;

            for (int left = 0; left <= board.length - lengthToWin; ++left) {
                int right = left + lengthToWin - 1;

                // Check each row.
                nextRow: for (int row = top; row <= bottom; ++row) {
                    if (board[row][left] == Square.NONE) {
                        continue;
                    }

                    for (int col = left; col <= right; ++col) {
                        if (board[row][col] != board[row][left]) {
                            continue nextRow;
                        }
                    }

                    return board[row][left];
                }

                // Check each column.
                nextCol: for (int col = left; col <= right; ++col) {
                    if (board[top][col] == Square.NONE) {
                        continue;
                    }

                    for (int row = top; row <= bottom; ++row) {
                        if (board[row][col] != board[top][col]) {
                            continue nextCol;
                        }
                    }

                    return board[top][col];
                }

                // Check top-left to bottom-right diagonal.
                diag1: if (board[top][left] != Square.NONE) {
                    for (int i = 1; i < lengthToWin; ++i) {
                        if (board[top+i][left+i] != board[top][left]) {
                            break diag1;
                        }
                    }

                    return board[top][left];
                }

                // Check top-right to bottom-left diagonal.
                diag2: if (board[top][right] != Square.NONE) {
                    for (int i = 1; i < lengthToWin; ++i) {
                        if (board[top+i][right-i] != board[top][right]) {
                            break diag2;
                        }
                    }

                    return board[top][right];
                }
            }
        }

        // Check for a completely full board.
        boolean isFull = true;

        full: for (int row = 0; row < board.length; ++row) {
            for (int col = 0; col < board.length; ++col) {
                if (board[row][col] == Square.NONE) {
                    isFull = false;
                    break full;
                }
            }
        }

        // The board is full.
        if (isFull) {
            return Square.NONE;
        }
        // The board is not full and we didn't find a solution.
        else {
            return null;
        }
    }
}

Use CSS3 transitions with gradient backgrounds

As stated. Gradients aren't currently supported with CSS Transitions. But you could work around it in some cases by setting one of the colors to transparent, so that the background-color of some other wrapping element shines through, and transition that instead.

How to push a docker image to a private repository

If you docker registry is private and self hosted you should do the following :

docker login <REGISTRY_HOST>:<REGISTRY_PORT>
docker tag <IMAGE_ID> <REGISTRY_HOST>:<REGISTRY_PORT>/<APPNAME>:<APPVERSION>
docker push <REGISTRY_HOST>:<REGISTRY_PORT>/<APPNAME>:<APPVERSION>

Example :

docker login repo.company.com:3456
docker tag 19fcc4aa71ba repo.company.com:3456/myapp:0.1
docker push repo.company.com:3456/myapp:0.1

How to update MySql timestamp column to current timestamp on PHP?

Another option:

UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now().

How do you fix the "element not interactable" exception?

A possibility is that the element is currently unclickable because it is not visible. Reasons for this may be that another element is covering it up or it is not in view, i.e. it is outside the currently view-able area.

Try this

from selenium.webdriver.common.action_chains import ActionChains

button = driver.find_element_by_class_name(u"infoDismiss")
driver.implicitly_wait(10)
ActionChains(driver).move_to_element(button).click(button).perform()

How to add a new line of text to an existing file in Java?

Starting from Java 7:

Define a path and the String containing the line separator at the beginning:

Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";

and then you can use one of the following approaches:

  1. Using Files.write (small files):

    try {
        Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.err.println(e);
    }
    
  2. Using Files.newBufferedWriter(text files):

    try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
        writer.write(s);
    } catch (IOException ioe) {
        System.err.format("IOException: %s%n", ioe);
    }
    
  3. Using Files.newOutputStream (interoperable with java.io APIs):

    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
        out.write(s.getBytes());
    } catch (IOException e) {
        System.err.println(e);
    }
    
  4. Using Files.newByteChannel (random access files):

    try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    
  5. Using FileChannel.open (random access files):

    try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    

Details about these methods can be found in the Oracle's tutorial.

ADB error: cannot connect to daemon

I had a couple of things open that prevented ADB from properly running. Specifically, I had BlueStacks Tweaker (to kill BlueStacks which runs in the background) and another program. Both use their own bundled adb.exe version for issuing commands. I was then also using my system's adb.exe. I had to close the other two programs in order to solve the problem. Restarting my computer would've also solved the problem (by closing those programs for me lol).

Reference - What does this error mean in PHP?

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

First and foremost:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


This happens when you try to fetch data from the result of mysql_query but the query failed.

This is a warning and won't stop the script, but will make your program wrong.

You need to check the result returned by mysql_query by

$res = mysql_query($sql);
if (!$res) {
   die(mysql_error());
}
// after checking, do the fetch

Related Questions:

Related Errors:

Other mysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

@RequestParam vs @PathVariable

@PathVariable - must be placed in the endpoint uri and access the query parameter value from the request
@RequestParam - must be passed as method parameter (optional based on the required property)
 http://localhost:8080/employee/call/7865467

 @RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
 public List<Calls> getAgentCallById(
            @PathVariable(“callId") int callId,
            @RequestParam(value = “status", required = false) String callStatus) {

    }

http://localhost:8080/app/call/7865467?status=Cancelled

@RequestMapping(value=“/call/{callId}", method = RequestMethod.GET)
public List<Calls> getAgentCallById(
            @PathVariable(“callId") int callId,
            @RequestParam(value = “status", required = true) String callStatus) {

}

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

at the starting of the line,so the line looks like.

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

How to get my activity context?

Ok, I will give a small example on how to do what you ask

public class ClassB extends Activity
{

 ClassA A1 = new ClassA(this); // for activity context

 ClassA A2 = new ClassA(getApplicationContext());  // for application context. 

}

How do I add a newline to command output in PowerShell?

Ultimately, what you're trying to do with the EXTRA blank lines between each one is a little confusing :)

I think what you really want to do is use Get-ItemProperty. You'll get errors when values are missing, but you can suppress them with -ErrorAction 0 or just leave them as reminders. Because the Registry provider returns extra properties, you'll want to stick in a Select-Object that uses the same properties as the Get-Properties.

Then if you want each property on a line with a blank line between, use Format-List (otherwise, use Format-Table to get one per line).

gci -path hklm:\software\microsoft\windows\currentversion\uninstall |
gp -Name DisplayName, InstallDate | 
select DisplayName, InstallDate | 
fl | out-file addrem.txt

Command to escape a string in bash

It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.

I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n might need to be added. This list of characters is not authoritative, but I believe it covers everything else.

I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp commands.

It can likely be implemented as a shell function as well

I therefore present escapify.c. I use it like so:

scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c

PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
  char c='\0';
  int i=0;
  int j=1;
  /* do not care if no args passed; escaped nothing is still nothing. */
  if(argc < 2)
  {
    return 0;
  }
  while(j<argc)
  {
    while(i<strlen(argv[j]))
    {
      c=argv[j][i];
      /* this switch has no breaks on purpose. */
      switch(c)
      {
      case ';':
      case '\'':
      case ' ':
      case '!':
      case '"':
      case '#':
      case '$':
      case '&':
      case '(':
      case ')':
      case '|':
      case '*':
      case ',':
      case '<':
      case '>':
      case '[':
      case ']':
      case '\\':
      case '^':
      case '`':
      case '{':
      case '}':
        putchar('\\');
      default:
        putchar(c);
      }
      i++;
    }
    j++;
    if(j<argc) {
      putchar(' ');
    }
    i=0;
  }
  /* newline at end */
  putchar ('\n');
  return 0;
}

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

Typographically, the correct glyph to use in sentence punctuation is the quote mark, both single (including for apostrophes) and double quotes. The straight-looking mark that we often see on the web is called a prime, which also comes in single and double varieties and has limited uses, mostly for measurements.

This article explains how to use them correctly.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I had the same problem but was able to fix it by doing the following:

Right-click on the project -> Properties, then add the JAR (odjbc6 or 14) file in the deployment assembly.

Maven Install on Mac OS X

If you don't want to install Homebrew only for install Maven you could simply do this:

  1. Download the binary Maven and extract the zip

  2. Launch the Terminal and type this command:

    sudo ln -s /path_to_maven_folder/bin/mvn /usr/bin/mvn

You can find more details on this post.

Using external images for CSS custom cursors

I would put this as a comment, but I don't have the rep for it. What Josh Crozier answered is correct, but for IE .cur and .ani are the only supported formats for this. So you should probably have a fallback just in case:

.test {
    cursor:url("http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif"), url(foo.cur), auto;
}

What is the difference between Trap and Interrupt?

I think Traps are caused by the execution of current instruction and thus they are called as synchronous events. where as interrupts are caused by an independent instruction that is running in the processor which are related to external events and thus are known as asynchronous ones.

How do you auto format code in Visual Studio?

For Visual Studio 2010/2013/2015/2017/2019

  • Format Document (Ctrl+K,Ctrl+D) so type Ctrl+K, AND THEN Ctrl+D as it is a sequence
  • Format Selection (Ctrl+K,Ctrl+F)

Toolbar Edit -> Advanced (If you can't see Advanced, select a code file in solution explorer and try again)

Your shortcuts might display differently to mine as I am set up for C# coding but navigating via the toolbar will get you to your ones.

If it isn't working, look for errors in your code, like missing brackets which stop auto format from working

How to create a template function within a class? (C++)

The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.

class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}

Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.

// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}

// .cpp file
//...
template <typename T> void Foo::some_method(T t) 
{//...}
//...

template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);

Get day of week in SQL Server 2005/2008

With SQL Server 2012 and onward you can use the FORMAT function

SELECT FORMAT(GETDATE(), 'dddd')

HTML text input allow only numeric input

_x000D_
_x000D_
var userName = document.querySelector('#numberField');

userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {  
  var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
  this.value = newValue;
}
_x000D_
<input type="text" id="numberField">
_x000D_
_x000D_
_x000D_

How do you import an Eclipse project into Android Studio now?

Stop installing android studio 3.0.1 and go back 2.3.3 ( Stable version) . Check for the stable version and you can find them a lot

All you have to do uninstall and go back to the other version. Yes it asks to create gradle file seperately which is completely new to me!

Failure is the stepping stone for success..

Running stages in parallel with Jenkins workflow / pipeline

that syntax is now deprecated, you will get this error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
       parallel firstTask: {
       ^

WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
       parallel secondTask: {
       ^

2 errors

You should do something like:

stage("Parallel") {
    steps {
        parallel (
            "firstTask" : {
                //do some stuff
            },
            "secondTask" : {
                // Do some other stuff in parallel
            }
        )
    }
}

Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:

pipeline {
  stages {
    stage("Work 1"){
     steps{
      parallel ( "Build common Library":   
            {
              node('<Label>'){
                  /// your stuff
                  }
            },

        "Build Utilities" : {
            node('<Label>'){
               /// your stuff
              }
           }
         )
    }
}

All VMs should be labelled as to use as a pool.

How to remove application from app listings on Android Developer Console

The one exception worth noting is that while you can't delete apps, the folks over at Google Play Developer Support are able to on their end if the app is both unpublished and has 0 lifetime installs. So if your app has 0 lifetime installs, you might be in luck.

First you will need unpublish the app and wait 24 hours (to allow global stats to update and ensure that no last-minute installs happened). Assuming no last-minute installs happen over those 24 hours, you can contact Google Play Developer Support and check to see if they can delete it.

Please note that their requirement for 0 installs is a hard requirement. No exceptions can be made (not even if you installed the app yourself for testing purposes).

difference between System.out.println() and System.err.println()

It's worth noting that an OS has one queue for both System.err and System.out. Consider the following code:

public class PrintQueue {
    public static void main(String[] args) {
        for(int i = 0; i < 100; i++) {
            System.out.println("out");
            System.err.println("err");
        }
    }
}

If you compile and run the program, you will see that the order of outputs in console is mixed up.

An OS will remain right order if you work either with System.out or System.err only. But it can randomly choose what to print next to console, if you use both of these.

Even in this code snippet you can see that the order is mixed up sometimes:

public class PrintQueue {
    public static void main(String[] args) {
        System.out.println("out");
        System.err.println("err");
    }
}

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

fist get the certificate from the provider
create a file ends wirth .cer and pase the certificate

copy the text file or  past   it  somewhere you can access it 
then use the cmd prompt as an admin and cd to the bin of the jdk,
the cammand that will be used is the:  keytool 

change the  password of the keystore with :

keytool  -storepasswd -keystore "path of the key store from c\ and down"

the password is : changeit 
 then you will be asked to enter the new password twice 

then type the following :

keytool -importcert -file  "C:\Program Files\Java\jdk-13.0.2\lib\security\certificateFile.cer"   -alias chooseAname -keystore  "C:\Program Files\Java\jdk-13.0.2\lib\security\cacerts"

ant warning: "'includeantruntime' was not set"

i faced this same, i check in in program and feature. there was an update has install for jdk1.8 which is not compatible with my old setting(jdk1.6.0) for ant in eclipse. I install that update. right now, my ant project is build success.

Try it, hope this will be helpful.

Convert an ArrayList to an object array

Using these libraries:

  • gson-2.8.5.jar
  • json-20180813.jar

Using this code:

List<Object[]> testNovedads = crudService.createNativeQuery(
                "SELECT cantidad, id FROM NOVEDADES GROUP BY id ");

        Gson gson = new Gson();
        String json = gson.toJson(new TestNovedad());
        JSONObject jsonObject = new JSONObject(json);
        Collection<TestNovedad> novedads = new ArrayList<>();
        for (Object[] object : testNovedads) {
            Iterator<String> iterator = jsonObject.keys();
            int pos = 0;
            for (Iterator i = iterator; i.hasNext();) {
                jsonObject.put((String) i.next(), object[pos++]);
            }
            novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class));
        }
        for (TestNovedad testNovedad : novedads) {
            System.out.println(testNovedad.toString());
        }

/**
 * Autores: Chalo Mejia 
 * Fecha: 01/10/2020
 */
package org.main;

import java.io.Serializable;

public class TestNovedad implements Serializable {

    private static final long serialVersionUID = -6362794385792247263L;

    private int id;

    private int cantidad;

    public TestNovedad() {
        // TODO Auto-generated constructor stub
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getCantidad() {
        return cantidad;
    }

    public void setCantidad(int cantidad) {
        this.cantidad = cantidad;
    }

    @Override
    public String toString() {
        return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]";
    }

}

If list index exists, do X

Could it be more useful for you to use the length of the list len(n) to inform your decision rather than checking n[i] for each possible length?

How to diff a commit with its parent?

If you know how far back, you can try something like:

# Current branch vs. parent
git diff HEAD^ HEAD

# Current branch, diff between commits 2 and 3 times back
git diff HEAD~3 HEAD~2

Prior commits work something like this:

# Parent of HEAD
git show HEAD^1

# Grandparent
git show HEAD^2

There are a lot of ways you can specify commits:

# Great grandparent
git show HEAD~3

See this page for details.

Passing two command parameters using a WPF binding

About using Tuple in Converter, it would be better to use 'object' instead of 'string', so that it works for all types of objects without limitation of 'string' object.

public class YourConverter : IMultiValueConverter 
{      
    public object Convert(object[] values, ...)     
    {   
        Tuple<object, object> tuple = new Tuple<object, object>(values[0], values[1]);
        return tuple;
    }      
} 

Then execution logic in Command could be like this

public void OnExecute(object parameter) 
{
    var param = (Tuple<object, object>) parameter;

    // e.g. for two TextBox object
    var txtZip = (System.Windows.Controls.TextBox)param.Item1;
    var txtCity = (System.Windows.Controls.TextBox)param.Item2;
}

and multi-bind with converter to create the parameters (with two TextBox objects)

<Button Content="Zip/City paste" Command="{Binding PasteClick}" >
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource YourConvert}">
            <Binding ElementName="txtZip"/>
            <Binding ElementName="txtCity"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

How do I find all of the symlinks in a directory tree?

This will recursively traverse the /path/to/folder directory and list only the symbolic links:

ls -lR /path/to/folder | grep ^l

If your intention is to follow the symbolic links too, you should use your find command but you should include the -L option; in fact the find man page says:

   -L     Follow symbolic links.  When find examines or prints information
          about files, the information used shall be taken from the  prop-
          erties  of  the file to which the link points, not from the link
          itself (unless it is a broken symbolic link or find is unable to
          examine  the file to which the link points).  Use of this option
          implies -noleaf.  If you later use the -P option,  -noleaf  will
          still  be  in  effect.   If -L is in effect and find discovers a
          symbolic link to a subdirectory during its search, the subdirec-
          tory pointed to by the symbolic link will be searched.

          When the -L option is in effect, the -type predicate will always
          match against the type of the file that a symbolic  link  points
          to rather than the link itself (unless the symbolic link is bro-
          ken).  Using -L causes the -lname and -ilname predicates  always
          to return false.

Then try this:

find -L /var/www/ -type l

This will probably work: I found in the find man page this diamond: if you are using the -type option you have to change it to the -xtype option:

          l      symbolic link; this is never true if the -L option or the
                 -follow option is in effect, unless the symbolic link  is
                 broken.  If you want to search for symbolic links when -L
                 is in effect, use -xtype.

Then:

find -L /var/www/ -xtype l

How to get the last characters in a String in Java, regardless of String size

org.apache.commons.lang3.StringUtils.substring(s, -7) 

gives you the answer. It returns the input if it is shorter than 7, and null if s == null. It never throws an exception.

See https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substring-java.lang.String-int-int-

Singleton design pattern vs Singleton beans in Spring container

There is a very fundamental difference between the two. In case of Singleton design pattern, only one instance of a class will be created per classLoader while that is not the case with Spring singleton as in the later one shared bean instance for the given id per IoC container is created.

For example, if I have a class with the name "SpringTest" and my XML file looks something like this :-

<bean id="test1" class="com.SpringTest" scope="singleton">
        --some properties here
</bean>    
<bean id="test2" class="com.SpringTest" scope="singleton">
        --some properties here   
</bean>

So now in the main class if you will check the reference of the above two it will return false as according to Spring documentation:-

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container

So as in our case, the classes are the same but the id's that we have provided are different hence resulting in two different instances being created.

API Gateway CORS: no 'Access-Control-Allow-Origin' header

I got mine working after I realised that the lambda authoriser was failing and for some unknown reason that was being translated into a CORS error. A simple fix to my authoriser (and some authoriser tests that I should have added in the first place) and it worked. For me the API Gateway action 'Enable CORS' was required. This added all the headers and other settings I needed in my API.

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

In addition to REMOTE_ADDR and HTTP_X_FORWARDED_FOR there are some other headers that can be set such as:

  • HTTP_CLIENT_IP
  • HTTP_X_FORWARDED_FOR can be comma delimited list of IPs
  • HTTP_X_FORWARDED
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_FORWARDED_FOR
  • HTTP_FORWARDED

I found the code on the following site useful:
http://www.grantburton.com/?p=97

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.

PivotTable's Report Filter using "greater than"

I can't say how much this might help you, but just found a solution to something similar problem which I faced. In the Pivot-

  1. Right click and choose Pivot table options
  2. Choose the display option
  3. uncheck the first 'Show expand/Collapse buttons'
  4. check the 'Classic PivotTable Layout(enables dragging of fields in the grid)
  5. click ok.

This would refine the data. Then, I had just copy and pasted this data in a new tab wherein I had applied the filters to my Total column with values greater than certain percentage.

This did work in my case and hope it helps you too.

mailto using javascript

I don't know if it helps, but using jQuery, to hide an email address, I did :

    $(function() {
        // planque l'adresse mail
        var mailSplitted 
            = ['mai', 'to:mye', 'mail@', 'addre', 'ss.fr'];

        var link = mailSplitted.join('');
        link = '<a href="' + link + '"</a>';
        $('mytag').wrap(link);
    });

I hope it helps.

Easiest way to mask characters in HTML(5) text input

Use this JavaScript.

$(":input").inputmask();
$("#phone").inputmask({"mask": "(999) 999-9999"});

How to compare two files in Notepad++ v6.6.8

Update:

  • for Notepad++ 7.5 and above use Compare v2.0.0
  • for Notepad++ 7.7 and above use Compare v2.0.0 for Notepad++ 7.7, if you need to install manually follow the description below, otherwise use "Plugin Admin".

I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).

So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.

I wrote a guideline how to install it:

  1. Start your Notepad++ as administrator mode.
  2. Press F1 to find out if your Notepad++ is 64bit or 32bit (86x), hence you need to download the correct plugin version. Download Compare-plugin 2.
  3. Unzip Compare-plugin in temporary folder.
  4. Import plugin from the temporary folder.
  5. The plugin should appear under Plugins menu.

Note:
It is also possible to drag and drop the plugin .dll file directly in plugin folder.
64bit: %programfiles%\Notepad++\plugins
32bit: %programfiles(x86)%\Notepad++\plugins

Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.

Disclaimer: the link of this guideline refer to my personal web site.

Identifier not found error on function call

Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:

void swapCase(char *name);

or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.

DLL References in Visual C++

You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?

Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.

Explode string by one or more spaces or tabs

The answers provided by other folks (Ben James) are quite good and I have used them. As user889030 points out, the last array element may be empty. Actually, the first and last array elements can be empty. The code below addresses both issues.

# Split an input string into an array of substrings using any set
# whitespace characters
function explode_whitespace($str) {  
  # Split the input string into an array
  $parts = preg_split('/\s+/', $str);
  # Get the size of the array of substrings
  $sizeParts = sizeof($parts);
  # Check if the last element of the array is a zero-length string
  if ($sizeParts > 0) {
    $lastPart = $parts[$sizeParts-1];
    if ($lastPart == '') {
      array_pop($parts);
      $sizeParts--;
    }
    # Check if the first element of the array is a zero-length string
    if ($sizeParts > 0) {
      $firstPart = $parts[0];
      if ($firstPart == '') 
        array_shift($parts); 
    }
  }
  return $parts;   
}

Eclipse interface icons very small on high resolution screen in Windows 8.1

I have looked up solutions for this issue for the last month, but I have not found an ideal solution yet. It seems there should be a way around it, but I just can't find it.

I use a laptop with a 2560x1600 screen with the 200% magnification setting in Windows 8.1 (which makes it looking like a 1280x800 screen but clearer).

Applications that support such "HiDPI" mode look just gorgeous, but the ones that don't (e.g. Eclipse) show tiny icons that are almost unreadable.

I also use an outdated version of Visual Studio. That has not been updated for HiDPI (obviously MS wants me to use a newer version of VS), but it still works kind of ok with HiDPI screens since it just scales things up twice -- the sizes of icons and letters are normal but they look lower-resolution.

After I saw how VS works, I began looking up a way to launch Eclipse in the same mode since it would not be technically very hard to just scale things up like how VS does. I thought there would be an option I could set to launch Eclipse in that mode. I couldn't find it though.

After all, I ended up lowering the screen resolution to 1/4 (from 2560x1600 to 1280x800) with no magnification (from 200% to 100%) and not taking advantage of the high-resolution screen until Eclipse gets updated to support it since I had to do some work, but I am desparately waiting for an answer to this issue.

hibernate - get id after save object

By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity) method. There is no need to do it explicitly.

In case your primary key is int you can use below code:

int id=(Integer) session.save(entity);

In case of string use below code:

String str=(String)session.save(entity);

Wrapping a react-router Link in an html button

With styled components this can be easily achieved

First Design a styled button

import styled from "styled-components";
import {Link} from "react-router-dom";

const Button = styled.button`
  background: white;
  color:red;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid red;
  border-radius: 3px;
`
render(
    <Button as={Link} to="/home"> Text Goes Here </Button>
);

check styled component's home for more

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

Stateless vs Stateful

I suggest that you start from a question in StackOverflow that discusses the advantages of stateless programming. This is more in the context of functional programming, but what you will read also applies in other programming paradigms.

Stateless programming is related to the mathematical notion of a function, which when called with the same arguments, always return the same results. This is a key concept of the functional programming paradigm and I expect that you will be able to find many relevant articles in that area.

Another area that you could research in order to gain more understanding is RESTful web services. These are by design "stateless", in contrast to other web technologies that try to somehow keep state. (In fact what you say that ASP.NET is stateless isn't correct - ASP.NET tries hard to keep state using ViewState and are definitely to be characterized as stateful. ASP.NET MVC on the other hand is a stateless technology). There are many places that discuss "statelessness" of RESTful web services (like this blog spot), but you could again start from an SO question.

How to remove responsive features in Twitter Bootstrap 3?

If you want a fixed size website this should be fairly simple:

_x000D_
_x000D_
// Override container sizes_x000D_
@container-sm: 700px;_x000D_
@container-md: 700px;_x000D_
@container-lg: 700px;_x000D_
_x000D_
// Fixate media queries to tablet view only (lower viewports set to 0px, desired one to 1px, and the higher to ~9999px)_x000D_
_x000D_
@screen-xs-min: 0px;_x000D_
@screen-sm-min: 1px;_x000D_
@screen-md-min: 9999px;_x000D_
@screen-lg-min: 9999px;_x000D_
_x000D_
// Disable responsive features such as navbar-collapse_x000D_
@grid-float-breakpoint: 9999px;
_x000D_
_x000D_
_x000D_

Unless you are using .container-fluid, then also add:

.container-fluid {
    width: 700px;
}
body {
    width: 700px + @general-min-width;
}

Cannot import keras after installation

Firstly checked the list of installed Python packages by:

pip list | grep -i keras

If there is keras shown then install it by:

pip install keras --upgrade --log ./pip-keras.log

now check the log, if there is any pending dependencies are present, it will affect your installation. So remove dependencies and then again install it.

What are the aspect ratios for all Android phone and tablet devices?

I researched the same thing several months ago looking at dozens of the most popular Android devices. I found that every Android device had one of the following aspect ratios (from most square to most rectangular):

  • 4:3
  • 3:2
  • 8:5
  • 5:3
  • 16:9

And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)


More complete answer here: stackoverflow community spreadsheet of Android device resolutions and DPIs

Disable browser cache for entire ASP.NET website

Instead of rolling your own, simply use what's provided for you.

As mentioned previously, do not disable caching for everything. For instance, jQuery scripts used heavily in ASP.NET MVC should be cached. Actually ideally you should be using a CDN for those anyway, but my point is some content should be cached.

What I find works best here rather than sprinkling the [OutputCache] everywhere is to use a class:

[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class NoCacheController  : Controller
{
}

All of your controllers you want to disable caching for then inherit from this controller.

If you need to override the defaults in the NoCacheController class, simply specify the cache settings on your action method and the settings on your Action method will take precedence.

[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ViewResult Index()
{
  ...
}

Recursively look for files with a specific extension

Without using find:

du -a $directory | awk '{print $2}' | grep '\.in$'

Pass Model To Controller using Jquery/Ajax

Use the following JS:

$(document).ready(function () {
    $("#btnsubmit").click(function () {

             $.ajax({
                 type: "POST",
                 url: '/Plan/PlanManage',     //your action
                 data: $('#PlanForm').serialize(),   //your form name.it takes all the values of model               
                 dataType: 'json',
                 success: function (result) {
                     console.log(result);
                 }
             })
        return false;
    });
});

and the following code on your controller:

[HttpPost]
public string PlanManage(Plan objplan)  //model plan
{
}

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

This a hybrid of answers from SolutionYogi and Chris S. It maintains the console.log line numbers and file name. Example jsFiddle.

// Avoid global functions via a self calling anonymous one (uses jQuery)
(function(MYAPP, $, undefined) {
    // Prevent errors in browsers without console.log
    if (!window.console) window.console = {};
    if (!window.console.log) window.console.log = function(){};

    //Private var
    var console_log = console.log;  

    //Public methods
    MYAPP.enableLog = function enableLogger() { console.log = console_log; };   
    MYAPP.disableLog = function disableLogger() { console.log = function() {}; };

}(window.MYAPP = window.MYAPP || {}, jQuery));


// Example Usage:
$(function() {    
    MYAPP.disableLog();    
    console.log('this should not show');

    MYAPP.enableLog();
    console.log('This will show');
});

How to read line by line or a whole text file at once?

You can use std::getline :

#include <fstream>
#include <string>

int main() 
{ 
    std::ifstream file("Read.txt");
    std::string str; 
    while (std::getline(file, str))
    {
        // Process str
    }
}

Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).

Further documentation about std::string::getline() can be read at CPP Reference.

Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.

std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
  file_contents += str;
  file_contents.push_back('\n');
}  

Is there a "null coalescing" operator in JavaScript?

If || as a replacement of C#'s ?? isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');

Where does R store packages?

The install.packages command looks through the .libPaths variable. Here's what mine defaults to on OSX:

> .libPaths()
[1] "/Library/Frameworks/R.framework/Resources/library"

I don't install packages there by default, I prefer to have them installed in my home directory. In my .Rprofile, I have this line:

.libPaths( "/Users/tex/lib/R" )

This adds the directory "/Users/tex/lib/R" to the front of the .libPaths variable.

Assert that a WebElement is not present using Selenium WebDriver with java

For appium 1.6.0 and above

    WebElement button = (new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//XCUIElementTypeButton[@name='your button']"))));
    button.click();

    Assert.assertTrue(!button.isDisplayed());

Difference between `constexpr` and `const`

According to book of "The C++ Programming Language 4th Editon" by Bjarne Stroustrup
const: meaning roughly ‘‘I promise not to change this value’’ (§7.5). This is used primarily to specify interfaces, so that data can be passed to functions without fear of it being modified.
The compiler enforces the promise made by const.
constexpr: meaning roughly ‘‘to be evaluated at compile time’’ (§10.4). This is used primarily to specify constants, to allow
For example:

const int dmv = 17; // dmv is a named constant
int var = 17; // var is not a constant
constexpr double max1 = 1.4*square(dmv); // OK if square(17) is a constant expression
constexpr double max2 = 1.4*square(var); // error : var is not a constant expression
const double max3 = 1.4*square(var); //OK, may be evaluated at run time
double sum(const vector<double>&); // sum will not modify its argument (§2.2.5)
vector<double> v {1.2, 3.4, 4.5}; // v is not a constant
const double s1 = sum(v); // OK: evaluated at run time
constexpr double s2 = sum(v); // error : sum(v) not constant expression

For a function to be usable in a constant expression, that is, in an expression that will be evaluated by the compiler, it must be defined constexpr.
For example:

constexpr double square(double x) { return x*x; }


To be constexpr, a function must be rather simple: just a return-statement computing a value. A constexpr function can be used for non-constant arguments, but when that is done the result is not a constant expression. We allow a constexpr function to be called with non-constant-expression arguments in contexts that do not require constant expressions, so that we don’t hav e to define essentially the same function twice: once for constant expressions and once for variables.
In a few places, constant expressions are required by language rules (e.g., array bounds (§2.2.5, §7.3), case labels (§2.2.4, §9.4.2), some template arguments (§25.2), and constants declared using constexpr). In other cases, compile-time evaluation is important for performance. Independently of performance issues, the notion of immutability (of an object with an unchangeable state) is an important design concern (§10.4).

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

I faced similar issue. My controller name was documents. It manages uploaded documents. It was working fine and started showing this error after completion of code. The mistake I did is - Created a folder 'Documents' to save the uploaded files. So controller name and folder name were same - which made the issue.

how to access the command line for xampp on windows

XAMPP does not have a pre build console to run php or mysql commands, so, you have to add to windows PATH environment variables, these 2: ;C:\xampp\mysql\bin;C:\xampp\php;

Then you should be able to execute php and mysql commands from the CMD.

UPDATE

I tested it, and it works.

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just add remove_button_css as class to your button tag. You can verify the code for Link 1

.remove_button_css { 
  outline: none;
  padding: 5px; 
  border: 0px; 
  box-sizing: none; 
  background-color: transparent; 
}

enter image description here

Extra Styles Edit

Add color: #337ab7; and :hover and :focus to match OOTB (bootstrap3)

.remove_button_css:focus,
.remove_button_css:hover {
    color: #23527c;
    text-decoration: underline;
}

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

In my case I was modifying the request to append a header (using Fiddler) to an https request, but I did not configure it to decrypt https traffic. You can export a manually-created certificate from Fiddler, so you can trust/import the certificate by your browsers. See above link for details, some steps include:

  1. Click Tools > Fiddler Options.
  2. Click the HTTPS tab. Ensure the Decrypt HTTPS traffic checkbox is checked.
  3. Click the Export Fiddler Root Certificate to Desktop button.

Simple example of threading in C++

Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in c++0x, which was just nailed down and hasn't yet been implemented. The problem is somewhat systemic, technically the existing c++ memory model isn't strict enough to allow for well defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the c++0x standard on the topic.

http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html

That said there are several cross-platform thread C++ libraries that work just fine in practice. Intel thread building blocks contains a tbb::thread object that closely approximates the c++0x standard and Boost has a boost::thread library that does the same.

http://www.threadingbuildingblocks.org/

http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html

Using boost::thread you'd get something like:

#include <boost/thread.hpp>

void task1() { 
    // do stuff
}

void task2() { 
    // do stuff
}

int main (int argc, char ** argv) {
    using namespace boost; 
    thread thread_1 = thread(task1);
    thread thread_2 = thread(task2);

    // do other stuff
    thread_2.join();
    thread_1.join();
    return 0;
}

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Because you have used absolute positioning, and specified a top percentage, only margin-top will affect the location of your .item object. If instead you positioned it using bottom: 50%, then you'd need margin-bottom -8px to centre it, and margin-top would have no effect.

Margin affects the boundaries of an element in terms of positioning it, either absolutely as in your case, or relative to neighbouring elements. Imagine that margin is the foundations of your element on which it sits. They are typically the same size as it, but can be made larger or smaller on any or all of the four edges.

Your CSS tells the browser to position the top of your element the margin at a point 50% of the way down the page. However, as all elements are not a single pixel, the browser needs to know which part of it to line up 50% of the way down the page. For lining up the top of the element, it uses the top margin. By default this is in line with the top of the element, but you can alter it with CSS.

In your case, top 50% would result in the top of the element starting in the middle of the page. By applying a negative top margin, the browser uses the point 8px into the element from the top (ie the line across the middle of it) as the place to position at 50%.

If you apply a positive margin to the bottom, this extends the line the browser uses to position the bottom out away from the element itself, giving a gap between it and any adjacent element below, or affecting where it is placed absolutely if positioning based on the bottom.

Remove a file from a Git repository without deleting it from the local filesystem

Ignore the files, remove the files from git, update git (for the removal).

Note : this does not deal with history for sensitive information.

This process definitely takes some undertanding of what is going on with git. Over time, having gained that, I've learned to do processes such as:

1) Ignore the files

  • Add or update the project .gitignore to ignore them - in many cases such as yours, the parent directory, e.g. log/ will be the regex to use.
  • commit and push that .gitignore file change (not sure if push needed mind you, no harm if done).

2) Remove the files from git (only).

  • Now remove the files from git (only) with git remove --cached some_dir/
  • Check that they still remain locally (they should!).

3) Add and commit that change (essentially this is a change to "add" deleting stuff, despite the otherwise confusing "add" command!)

  • git add .
  • git commit -m"removal"

How can I scan barcodes on iOS?

Here is simple code:

func scanbarcode()
{
    view.backgroundColor = UIColor.blackColor()
    captureSession = AVCaptureSession()

    let videoCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    let videoInput: AVCaptureDeviceInput

    do {
        videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
    } catch {
        return
    }

    if (captureSession.canAddInput(videoInput)) {
        captureSession.addInput(videoInput)
    } else {
        failed();
        return;
    }

    let metadataOutput = AVCaptureMetadataOutput()

    if (captureSession.canAddOutput(metadataOutput)) {
        captureSession.addOutput(metadataOutput)

        metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypePDF417Code]
    } else {
        failed()
        return
    }

    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
    previewLayer.frame = view.layer.bounds;
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    view.layer.addSublayer(previewLayer);
    view.addSubview(closeBtn)
    view.addSubview(backimg)

    captureSession.startRunning();

}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func failed() {
    let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .Alert)
    ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
    presentViewController(ac, animated: true, completion: nil)
    captureSession = nil
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    if (captureSession?.running == false) {
        captureSession.startRunning();
    }
}

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    if (captureSession?.running == true) {
        captureSession.stopRunning();
    }
}

func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
    captureSession.stopRunning()

    if let metadataObject = metadataObjects.first {
        let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject;

        AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
        foundCode(readableObject.stringValue);
    }

   // dismissViewControllerAnimated(true, completion: nil)
}

func foundCode(code: String) {
    var createAccountErrorAlert: UIAlertView = UIAlertView()
    createAccountErrorAlert.delegate = self
    createAccountErrorAlert.title = "Alert"
    createAccountErrorAlert.message = code
    createAccountErrorAlert.addButtonWithTitle("ok")
    createAccountErrorAlert.addButtonWithTitle("Retry")
    createAccountErrorAlert.show()
    NSUserDefaults.standardUserDefaults().setObject(code, forKey: "barcode")
    NSUserDefaults.standardUserDefaults().synchronize()
    ItemBarcode = code
    print(code)
}

override func prefersStatusBarHidden() -> Bool {
    return true
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return .Portrait
}

How to convert a char array back to a string?

Try this

Arrays.toString(array)

Change a Django form field to a hidden field

Firstly, if you don't want the user to modify the data, then it seems cleaner to simply exclude the field. Including it as a hidden field just adds more data to send over the wire and invites a malicious user to modify it when you don't want them to. If you do have a good reason to include the field but hide it, you can pass a keyword arg to the modelform's constructor. Something like this perhaps:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
    def __init__(self, *args, **kwargs):
        from django.forms.widgets import HiddenInput
        hide_condition = kwargs.pop('hide_condition',None)
        super(MyModelForm, self).__init__(*args, **kwargs)
        if hide_condition:
            self.fields['fieldname'].widget = HiddenInput()
            # or alternately:  del self.fields['fieldname']  to remove it from the form altogether.

Then in your view:

form = MyModelForm(hide_condition=True)

I prefer this approach to modifying the modelform's internals in the view, but it's a matter of taste.

2D cross-platform game engine for Android and iOS?

I've worked with Marmalade and I found it satisfying. Although it's not free and the developer community is also not large enough, but still you can handle most of the task using it's tutorials. (I'll write my tutorials once I got some times too).
IwGame is a good engine, developed by one of the Marmalade user. It's good for a basic game, but if you are looking for some serious advanced gaming stuff, you can also use Cocos2D-x with Marmalade. I've never used Cocos2D-x, but there's an Extension on Marmalade's Github.
Another good thing about Marmalade is it's EDK (Extension Development Kit), which lets you make an extension for whatever functionality you need which is available in native code, but not in Marmalade. I've used it to develop my own Customized Admob extension and a Facebook extension too.

Edit:
Marmalade now has it's own RAD(Rapid Application Development) tool just for 2D development, named as Marmalade Quick. Although the coding will be in Lua not in C++, but since it's built on top of C++ Marmalade, you can easily include a C++ library, and all other EDK extensions. Also the Cocos-2Dx and Box2D extensions are preincluded in the Quick. They recently launched it's Release version (It was in beta for 3-4 months). I think we you're really looking for only 2D development, you should give it a try.

Update:
Unity3D recently launched support for 2D games, which seems better than any other 2D game engine, due to it's GUI and Editor. Physics, sprite etc support is inbuilt. You can have a look on it.

Update 2
Marmalade is going to discontinue their SDK in favor of their in-house game production soon. So it won't be a wise decision to rely on that.

Create a new object from type parameter in generic class

To create a new object within generic code, you need to refer to the type by its constructor function. So instead of writing this:

function activatorNotWorking<T extends IActivatable>(type: T): T {
    return new T(); // compile error could not find symbol T
}

You need to write this:

function activator<T extends IActivatable>(type: { new(): T ;} ): T {
    return new type();
}

var classA: ClassA = activator(ClassA);

See this question: Generic Type Inference with Class Argument

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

You can have multiple contexts for single database. It can be useful for example if your database contains multiple database schemas and you want to handle each of them as separate self contained area.

The problem is when you want to use code first to create your database - only single context in your application can do that. The trick for this is usually one additional context containing all your entities which is used only for database creation. Your real application contexts containing only subsets of your entities must have database initializer set to null.

There are other issues you will see when using multiple context types - for example shared entity types and their passing from one context to another, etc. Generally it is possible, it can make your design much cleaner and separate different functional areas but it has its costs in additional complexity.

Calling JavaScript Function From CodeBehind

This is how I've done it.

HTML markup showing a label and button control is as follows.

<body> 
  <form id="form1" runat="server"> 
  <div> 
    <asp:Label ID="lblJavaScript" runat="server" Text=""></asp:Label> 
    <asp:Button ID="btnShowDialogue" runat="server" Text="Show Dialogue" /> 
  </div> 
  </form> 
</body>

JavaScript function is here.

<head runat="server"> 
  <title>Calling javascript function from code behind example</title> 
  <script type="text/javascript"> 
    function showDialogue() { 
      alert("this dialogue has been invoked through codebehind."); 
    } 
  </script> 
</head>

Code behind to trigger the JavaScript function is here.

lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";

How to get access token from FB.login method in javascript SDK

response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.
Check this for details: SDKs & Tools › JavaScript SDK › FB.login

The I/O operation has been aborted because of either a thread exit or an application request

I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.

Double.TryParse or Convert.ToDouble - which is faster and safer?

Double.TryParse IMO.

It is easier for you to handle, You'll know exactly where the error occurred.

Then you can deal with it how you see fit if it returns false (i.e could not convert).

How to run travis-ci locally

tl;dr Use image specified at https://docs.travis-ci.com/user/common-build-problems/#troubleshooting-locally-in-a-docker-image in combination with https://github.com/travis-ci/travis-build#use-as-addon-for-travis-cli.


EDIT 2019-12-06

#troubleshooting-locally-in-a-docker-image section was replaced by #running-builds-in-debug-mode which also describes how to SSH to the job running in the debug mode.

EDIT 2019-07-26

#troubleshooting-locally-in-a-docker-image section is no longer part of the docs; here's why


Though, it's still in git history: https://github.com/travis-ci/docs-travis-ci-com/pull/2193.

Look for (quite old, couldn't find newer) image versions at: https://travis-ci.org/travis-ci/docs-travis-ci-com/builds/230889063#L661.



I wanted to inspect why one of the tests in my build failed with an error I din't get locally.

Worked.

What actually worked was using the image specified at Troubleshooting Locally in a Docker Image docs page. In my case it was travisci/ci-garnet:packer-1512502276-986baf0.

I was able to add travise compile following steps described at https://github.com/travis-ci/travis-build#use-as-addon-for-travis-cli.

dm@z580:~$ docker run --name travis-debug -dit travisci/ci-garnet:packer-1512502276-986baf0 /sbin/init
dm@z580:~$ docker images
REPOSITORY                       TAG                          IMAGE ID            CREATED             SIZE
travisci/ci-garnet               packer-1512502276-986baf0    6cbda6a950d3        11 months ago       10.2GB
dm@z580:~$ docker exec -it travis-debug bash -l
root@912e43dbfea4:/# su - travis
travis@912e43dbfea4:~$ cd builds/
travis@912e43dbfea4:~/builds$ git clone https://github.com/travis-ci/travis-build
travis@912e43dbfea4:~/builds$ cd travis-build
travis@912e43dbfea4:~/builds/travis-build$ mkdir -p ~/.travis
travis@912e43dbfea4:~/builds/travis-build$ ln -s $PWD ~/.travis/travis-build
travis@912e43dbfea4:~/builds/travis-build$ gem install bundler
travis@912e43dbfea4:~/builds/travis-build$ bundle install --gemfile ~/.travis/travis-build/Gemfile
travis@912e43dbfea4:~/builds/travis-build$ bundler binstubs travis
travis@912e43dbfea4:~/builds/travis-build$ cd ..
travis@912e43dbfea4:~/builds$ git clone --depth=50 --branch=master https://github.com/DusanMadar/PySyncDroid.git DusanMadar/PySyncDroid
travis@912e43dbfea4:~/builds$ cd DusanMadar/PySyncDroid/
travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$ ~/.travis/travis-build/bin/travis compile > ci.sh
travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$ sed -i 's,--branch\\=\\\x27\\\x27,--branch\\=master,g' ci.sh
travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$ bash ci.sh

Everything from .travis.yml was executed as expected (dependencies installed, tests ran, ...).

Note that before running bash ci.sh I had to change --branch\=\'\'\ to --branch\=master\ (see the second to last sed -i ... command) in ci.sh.

If that doesn't work the command bellow will help to identify the target line number and you can edit the line manually.

travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$ cat ci.sh | grep -in branch
840:    travis_cmd git\ clone\ --depth\=50\ --branch\=\'\'\ https://github.com/DusanMadar/PySyncDroid.git\ DusanMadar/PySyncDroid --echo --retry --timing
889:export TRAVIS_BRANCH=''
899:export TRAVIS_PULL_REQUEST_BRANCH=''
travis@912e43dbfea4:~/builds/DusanMadar/PySyncDroid$

Didn't work.

Followed the accepted answer for this question but didn't find the image (travis-ci-garnet-trusty-1512502259-986baf0) mentioned by instance at https://hub.docker.com/u/travisci/.

Build worker version points to travis-ci/worker commit and its travis-worker-install references quay.io/travisci/ as image registry. So I tried it.

dm@z580:~$ docker run -it -u travis quay.io/travisci/travis-python /bin/bash
travis@370c23a773c9:/$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 12.04.5 LTS
Release:    12.04
Codename:   precise
travis@370c23a773c9:/$
dm@z580:~$ docker images 
REPOSITORY                       TAG                          IMAGE ID            CREATED             SIZE
quay.io/travisci/travis-python   latest                       753a216d776c        3 years ago         5.36GB

Definitely not Trusty (Ubuntu 14.04) and not small either.

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

How can I plot data with confidence intervals?

Here is part of my program related to plotting confidence interval.

1. Generate the test data

ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)

Result

enter image description here

2. Fitting the raw data using B-spline smoother method

sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
    tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
    tmp <- 1.96*sqrt(tmp)
    y_e_minus[i] <- y_e[i] - tmp
    y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')

Result

enter image description here

How to get the current taxonomy term ID (not the slug) in WordPress?

Just copy paste below code!

This will print your current taxonomy name and description(optional)

<?php 
   $tax = $wp_query->get_queried_object();
   echo ''. $tax->name . '';
   echo "<br>";
   echo ''. $tax->description .''; 
?>

PostgreSQL - max number of parameters in "IN" clause?

If you have query like:

SELECT * FROM user WHERE id IN (1, 2, 3, 4 -- and thousands of another keys)

you may increase performace if rewrite your query like:

SELECT * FROM user WHERE id = ANY(VALUES (1), (2), (3), (4) -- and thousands of another keys)

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

How to update a single pod without touching other dependencies

Just a small notice.

pod update POD_NAME

will work only if this pod was already installed. Otherwise you will have to update all of them with

pod update

command

Have a div cling to top of screen if scrolled down past it

There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:

  1. Page loads and element is position: static
  2. On scroll, the position is measured, and if the element is position: static and it's off the page then the element is flipped to position: fixed.

I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.

HTML code for an apostrophe

Use &apos; for a straight apostrophe. This tends to be more readable than the numeric &#39; (if others are ever likely to read the HTML directly).

Edit: msanders points out that &apos; isn't valid HTML4, which I didn't know, so follow most other answers and use &#39;.

Real mouse position in canvas

The Simple 1:1 Scenario

For situations where the canvas element is 1:1 compared to the bitmap size, you can get the mouse positions by using this snippet:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
}

Just call it from your event with the event and canvas as arguments. It returns an object with x and y for the mouse positions.

As the mouse position you are getting is relative to the client window you'll have to subtract the position of the canvas element to convert it relative to the element itself.

Example of integration in your code:

//put this outside the event loop..
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

function draw(evt) {
    var pos = getMousePos(canvas, evt);

    context.fillStyle = "#000000";
    context.fillRect (pos.x, pos.y, 4, 4);
}

Note: borders and padding will affect position if applied directly to the canvas element so these needs to be considered via getComputedStyle() - or apply those styles to a parent div instead.

When Element and Bitmap are of different sizes

When there is the situation of having the element at a different size than the bitmap itself, for example, the element is scaled using CSS or there is pixel-aspect ratio etc. you will have to address this.

Example:

function  getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect(), // abs. size of element
      scaleX = canvas.width / rect.width,    // relationship bitmap vs. element for X
      scaleY = canvas.height / rect.height;  // relationship bitmap vs. element for Y

  return {
    x: (evt.clientX - rect.left) * scaleX,   // scale mouse coordinates after they have
    y: (evt.clientY - rect.top) * scaleY     // been adjusted to be relative to element
  }
}

With transformations applied to context (scale, rotation etc.)

Then there is the more complicated case where you have applied transformation to the context such as rotation, skew/shear, scale, translate etc. To deal with this you can calculate the inverse matrix of the current matrix.

Newer browsers let you read the current matrix via the currentTransform property and Firefox (current alpha) even provide a inverted matrix through the mozCurrentTransformInverted. Firefox however, via mozCurrentTransform, will return an Array and not DOMMatrix as it should. Neither Chrome, when enabled via experimental flags, will return a DOMMatrix but a SVGMatrix.

In most cases however you will have to implement a custom matrix solution of your own (such as my own solution here - free/MIT project) until this get full support.

When you eventually have obtained the matrix regardless of path you take to obtain one, you'll need to invert it and apply it to your mouse coordinates. The coordinates are then passed to the canvas which will use its matrix to convert it to back wherever it is at the moment.

This way the point will be in the correct position relative to the mouse. Also here you need to adjust the coordinates (before applying the inverse matrix to them) to be relative to the element.

An example just showing the matrix steps

function draw(evt) {
    var pos = getMousePos(canvas, evt);        // get adjusted coordinates as above
    var imatrix = matrix.inverse();            // get inverted matrix somehow
    pos = imatrix.applyToPoint(pos.x, pos.y);  // apply to adjusted coordinate

    context.fillStyle = "#000000";
    context.fillRect(pos.x-1, pos.y-1, 2, 2);
}

An example of using currentTransform when implemented would be:

    var pos = getMousePos(canvas, e);          // get adjusted coordinates as above
    var matrix = ctx.currentTransform;         // W3C (future)
    var imatrix = matrix.invertSelf();         // invert

    // apply to point:
    var x = pos.x * imatrix.a + pos.y * imatrix.c + imatrix.e;
    var y = pos.x * imatrix.b + pos.y * imatrix.d + imatrix.f;

Update I made a free solution (MIT) to embed all these steps into a single easy-to-use object that can be found here and also takes care of a few other nitty-gritty things most ignore.

SQL Server CASE .. WHEN .. IN statement

CASE AlarmEventTransactions.DeviceID should just be CASE.

You are mixing the 2 forms of the CASE expression.

QLabel: set color of text and background

You can use QPalette, however you must set setAutoFillBackground(true); to enable background color

QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);

sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");

It works fine on Windows and Ubuntu, I haven't played with any other OS.

Note: Please see QPalette, color role section for more details

Python - 'ascii' codec can't decode byte

In case you're dealing with Unicode, sometimes instead of encode('utf-8'), you can also try to ignore the special characters, e.g.

"??".encode('ascii','ignore')

or as something.decode('unicode_escape').encode('ascii','ignore') as suggested here.

Not particularly useful in this example, but can work better in other scenarios when it's not possible to convert some special characters.

Alternatively you can consider replacing particular character using replace().

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

Remove trailing zeros

You can just set as:

decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));

ModelState.IsValid == false, why?

The ModelState property on the controller is actually a ModelStateDictionary object. You can iterate through the keys on the dictionary and use the IsValidField method to check if that particular field is valid.

Selecting data frame rows based on partial string match in a column

I notice that you mention a function %like% in your current approach. I don't know if that's a reference to the %like% from "data.table", but if it is, you can definitely use it as follows.

Note that the object does not have to be a data.table (but also remember that subsetting approaches for data.frames and data.tables are not identical):

library(data.table)
mtcars[rownames(mtcars) %like% "Merc", ]
iris[iris$Species %like% "osa", ]

If that is what you had, then perhaps you had just mixed up row and column positions for subsetting data.


If you don't want to load a package, you can try using grep() to search for the string you're matching. Here's an example with the mtcars dataset, where we are matching all rows where the row names includes "Merc":

mtcars[grep("Merc", rownames(mtcars)), ]
             mpg cyl  disp  hp drat   wt qsec vs am gear carb
# Merc 240D   24.4   4 146.7  62 3.69 3.19 20.0  1  0    4    2
# Merc 230    22.8   4 140.8  95 3.92 3.15 22.9  1  0    4    2
# Merc 280    19.2   6 167.6 123 3.92 3.44 18.3  1  0    4    4
# Merc 280C   17.8   6 167.6 123 3.92 3.44 18.9  1  0    4    4
# Merc 450SE  16.4   8 275.8 180 3.07 4.07 17.4  0  0    3    3
# Merc 450SL  17.3   8 275.8 180 3.07 3.73 17.6  0  0    3    3
# Merc 450SLC 15.2   8 275.8 180 3.07 3.78 18.0  0  0    3    3

And, another example, using the iris dataset searching for the string osa:

irisSubset <- iris[grep("osa", iris$Species), ]
head(irisSubset)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

For your problem try:

selectedRows <- conservedData[grep("hsa-", conservedData$miRNA), ]

Refresh a page using PHP

Besides all the PHP ways to refresh a page, the page will also be refreshed with the following HTML meta tag:

<meta http-equiv="refresh" content="5">

See Meta refresh - "automatically refresh the current web page or frame after a given time interval"

You can set the time within the content value.

What is the difference between single-quoted and double-quoted strings in PHP?

' Single quoted

The simplest way to specify a string is to enclose it in single quotes. Single quote is generally faster, and everything quoted inside treated as plain string.

Example:

echo 'Start with a simple string';
echo 'String\'s apostrophe';
echo 'String with a php variable'.$name;

" Double quoted

Use double quotes in PHP to avoid having to use the period to separate code (Note: Use curly braces {} to include variables if you do not want to use concatenation (.) operator) in string.

Example:

echo "Start with a simple string";
echo "String's apostrophe";
echo "String with a php variable {$name}";

Is there a performance benefit single quote vs double quote in PHP?

Yes. It is slightly faster to use single quotes.

PHP won't use additional processing to interpret what is inside the single quote. when you use double quotes PHP has to parse to check if there are any variables within the string.

Convert pem key to ssh-rsa format

The following script would obtain the ci.jenkins-ci.org public key certificate in base64-encoded DER format and convert it to an OpenSSH public key file. This code assumes that a 2048-bit RSA key is used and draws a lot from this Ian Boyd's answer. I've explained a bit more how it works in comments to this article in Jenkins wiki.

echo -n "ssh-rsa " > jenkins.pub
curl -sfI https://ci.jenkins-ci.org/ | grep -i X-Instance-Identity | tr -d \\r | cut -d\  -f2 | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 >> jenkins.pub
echo >> jenkins.pub

Remove blank attributes from an Object in Javascript

ES10/ES2019 examples

A simple one-liner (returning a new object).

let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));

Same as above but written as a function.

function removeEmpty(obj) {
  return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
}

This function uses recursion to remove items from nested objects.

function removeEmpty(obj) {
  return Object.fromEntries(
    Object.entries(obj)
      .filter(([_, v]) => v != null)
      .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
  );
}

ES6/ES2015 examples

A simple one-liner. Warning: This mutates the given object instead of returning a new one.

Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);

A single declaration (not mutating the given object).

let o = Object.keys(obj)
  .filter((k) => obj[k] != null)
  .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});

Same as above but written as a function.

function removeEmpty(obj) {
  return Object.entries(obj)
    .filter(([_, v]) => v != null)
    .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});
}

This function uses recursion to remove items from nested objects.

function removeEmpty(obj) {
  return Object.entries(obj)
    .filter(([_, v]) => v != null)
    .reduce(
      (acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }),
      {}
    );
}

Same as the function above, but written in an imperative (non-functional) style.

function removeEmpty(obj) {
  const newObj = {};
  Object.entries(obj).forEach(([k, v]) => {
    if (v === Object(v)) {
      newObj[k] = removeEmpty(v);
    } else if (v != null) {
      newObj[k] = obj[k];
    }
  });
  return newObj;
}

ES5/ES2009 examples

In the old days things were a lot more verbose.

This is a non recursive version written in a functional style.

function removeEmpty(obj) {
  return Object.keys(obj)
    .filter(function (k) {
      return obj[k] != null;
    })
    .reduce(function (acc, k) {
      acc[k] = obj[k];
      return acc;
    }, {});
}

This is a non recursive version written in an imperative style.

function removeEmpty(obj) {
  const newObj = {};
  Object.keys(obj).forEach(function (k) {
    if (obj[k] && typeof obj[k] === "object") {
      newObj[k] = removeEmpty(obj[k]);
    } else if (obj[k] != null) {
      newObj[k] = obj[k];
    }
  });
  return newObj;
}

And a recursive version written in a functional style.

function removeEmpty(obj) {
  return Object.keys(obj)
    .filter(function (k) {
      return obj[k] != null;
    })
    .reduce(function (acc, k) {
      acc[k] = typeof obj[k] === "object" ? removeEmpty(obj[k]) : obj[k];
      return acc;
    }, {});
}

What are the advantages of Sublime Text over Notepad++ and vice-versa?

It's best if you judge on your own,

1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).

http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text

This Link is no more working so please watch this video for similar details Video

Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)

Some Variation: Some user find plugins useful for PHP coders on that

http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html

although, there are many plugins for Notepad Plus Plus ..

I am not sure of your requirements, nor I am promoter of either of these editors :)

So, judge on basis of your requirements, this should satisfy you query...

Yes we can add that both are evolving and changing fast..

How to get char from string by index?

In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45

Now, For positive index ranges for x is from 0 to 44 (i.e. length - 1)

In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

/home/<ipython console> in <module>()

IndexError: string index out of range

In [5]: x[44]
Out[5]: 's'

For Negative index, index ranges from -1 to -45

In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a

For negative index, negative [length -1] i.e. the last valid value of positive index will give second list element as the list is read in reverse order,

In [8]: x[-44]
Out[8]: 'n'

Other, index's examples,

In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

PHP Get all subdirectories of a given directory

Here is how you can retrieve only directories with GLOB:

$directories = glob($somePath . '/*' , GLOB_ONLYDIR);

Using Thymeleaf when the value is null

You can use 'th:if' together with 'th:text'

<span th:if="${someObject.someProperty != null}" th:text="${someObject.someProperty}">someValue</span>

Displaying better error message than "No JSON object could be decoded"

I had a similar problem this was my code:

    json_file=json.dumps(pyJson)
    file = open("list.json",'w')
    file.write(json_file)  

    json_file = open("list.json","r")
    json_decoded = json.load(json_file)
    print json_decoded

the problem was i had forgotten to file.close() I did it and fixed the problem.

Can you change a path without reloading the controller in AngularJS?

There is simple way to change path without reloading

URL is - http://localhost:9000/#/edit_draft_inbox/1457

Use this code to change URL, Page will not be redirect

Second parameter "false" is very important.

$location.path('/edit_draft_inbox/'+id, false);

Angular is automatically adding 'ng-invalid' class on 'required' fields

Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:

<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
    <label class="col-sm-2 control-label" for="username">Username*</label>
    <div class="col-sm-10 col-md-9">
        <input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
    </div>
</div>

It is also important, that your form has the ng-submit="" attribute:

<form name="myForm" ng-submit="checkSubmit()" novalidate>
 <!-- input fields here -->
 ....

  <button type="submit">Submit</button>
</form>

You can also add an optional function for validation to the form:

//within your controller (some extras...)

$scope.checkSubmit = function () {

   if ($scope.myForm.$valid) {
        alert('All good...'); //next step!

   }
   else {
        alert('Not all fields valid! Do something...');
    }

 }

Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched. Instead of:
!myForm.username.$pristine

You could also use:
myForm.username.$dirty

Difference between "while" loop and "do while" loop

The difference between do while (exit check) and while (entry check) is that while entering in do while it will not check but in while it will first check

The example is as such:

Program 1:

int a=10;
do{
System.out.println(a);
}
while(a<10);

//here the a is not less than 10 then also it will execute once as it will execute do while exiting it checks that a is not less than 10 so it will exit the loop

Program 2:

int b=0;
while(b<10)
{
System.out.println(b);
}
//here nothing will be printed as the value of b is not less than 10 and it will not let enter the loop and will exit

output Program 1:

10

output Program 2:

[nothing is printed]

note:

output of the program 1 and program 2 will be same if we assign a=0 and b=0 and also put a++; and b++; in the respective body of the program.

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

Is it possible to use global variables in Rust?

You can use static variables fairly easily as long as they are thread-local.

The downside is that the object will not be visible to other threads your program might spawn. The upside is that unlike truly global state, it is entirely safe and is not a pain to use - true global state is a massive pain in any language. Here's an example:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<sqlite::database::Database> = RefCell::new(sqlite::open("test.db"));

fn main() {
    ODB.with(|odb_cell| {
        let odb = odb_cell.borrow_mut();
        // code that uses odb goes here
    });
}

Here we create a thread-local static variable and then use it in a function. Note that it is static and immutable; this means that the address at which it resides is immutable, but thanks to RefCell the value itself will be mutable.

Unlike regular static, in thread-local!(static ...) you can create pretty much arbitrary objects, including those that require heap allocations for initialization such as Vec, HashMap and others.

If you cannot initialize the value right away, e.g. it depends on user input, you may also have to throw Option in there, in which case accessing it gets a bit unwieldy:

extern mod sqlite;

use std::cell::RefCell;

thread_local!(static ODB: RefCell<Option<sqlite::database::Database>> = RefCell::New(None));

fn main() {
    ODB.with(|odb_cell| {
        // assumes the value has already been initialized, panics otherwise
        let odb = odb_cell.borrow_mut().as_mut().unwrap();
        // code that uses odb goes here
    });
}

How to vertically align label and input in Bootstrap 3?

The problem is that your <label> is inside of an <h2> tag, and header tags have a margin set by the default stylesheet.

What is the difference between SAX and DOM?

You're comparing apples and pears. SAX is a parser that parses serialized DOM structures. There are many different parsers, and "event-based" refers to the parsing method.

Maybe a small recap is in order:

  • The document object model (DOM) is an abstract data model that describes a hierarchical, tree-based document structure; a document tree consists of nodes, namely element, attribute and text nodes (and some others). Nodes have parents, siblings and children and can be traversed, etc., all the stuff you're used to from doing JavaScript (which incidentally has nothing to do with the DOM).

  • A DOM structure may be serialized, i.e. written to a file, using a markup language like HTML or XML. An HTML or XML file thus contains a "written out" or "flattened out" version of an abstract document tree.

  • For a computer to manipulate, or even display, a DOM tree from a file, it has to deserialize, or parse, the file and reconstruct the abstract tree in memory. This is where parsing comes in.

Now we come to the nature of parsers. One way to parse would be to read in the entire document and recursively build up a tree structure in memory, and finally expose the entire result to the user. (I suppose you could call these parsers "DOM parsers".) That would be very handy for the user (I think that's what PHP's XML parser does), but it suffers from scalability problems and becomes very expensive for large documents.

On the other hand, event-based parsing, as done by SAX, looks at the file linearly and simply makes call-backs to the user whenever it encounters a structural piece of data, like "this element started", "that element ended", "some text here", etc. This has the benefit that it can go on forever without concern for the input file size, but it's a lot more low-level because it requires the user to do all the actual processing work (by providing call-backs). To return to your original question, the term "event-based" refers to those parsing events that the parser raises as it traverses the XML file.

The Wikipedia article has many details on the stages of SAX parsing.

How do I create an empty array/matrix in NumPy?

You have the wrong mental model for using NumPy efficiently. NumPy arrays are stored in contiguous blocks of memory. If you want to add rows or columns to an existing array, the entire array needs to be copied to a new block of memory, creating gaps for the new elements to be stored. This is very inefficient if done repeatedly to build an array.

In the case of adding rows, your best bet is to create an array that is as big as your data set will eventually be, and then assign data to it row-by-row:

>>> import numpy
>>> a = numpy.zeros(shape=(5,2))
>>> a
array([[ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.]])
>>> a[0] = [1,2]
>>> a[1] = [2,3]
>>> a
array([[ 1.,  2.],
   [ 2.,  3.],
   [ 0.,  0.],
   [ 0.,  0.],
   [ 0.,  0.]])

Random word generator- Python

There is a package random_word could implement this request very conveniently:

 $ pip install random-word

from random_word import RandomWords
r = RandomWords()

# Return a single random word
r.get_random_word()
# Return list of Random words
r.get_random_words()
# Return Word of the day
r.word_of_the_day()

What is the PHP syntax to check "is not null" or an empty string?

Null OR an empty string?

if (!empty($user)) {}

Use empty().


After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';

Git Commit Messages: 50/72 Formatting

Separation of presentation and data drives my commit messages here.

Your commit message should not be hard-wrapped at any character count and instead line breaks should be used to separate thoughts, paragraphs, etc. as part of the data, not the presentation. In this case, the "data" is the message you are trying to get across and the "presentation" is how the user sees that.

I use a single summary line at the top and I try to keep it short but I don't limit myself to an arbitrary number. It would be far better if Git actually provided a way to store summary messages as a separate entity from the message but since it doesn't I have to hack one in and I use the first line break as the delimiter (luckily, many tools support this means of breaking apart the data).

For the message itself newlines indicate something meaningful in the data. A single newline indicates a start/break in a list and a double newline indicates a new thought/idea.

This is a summary line, try to keep it short and end with a line break.
This is a thought, perhaps an explanation of what I have done in human readable format.  It may be complex and long consisting of several sentences that describe my work in essay format.  It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts.  The user may be reading this on a phone or a wide screen monitor.  Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across?  It is a truly painful experience.  Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph.  Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

Here's what it looks like in a viewer that soft wraps the text.

This is a summary line, try to keep it short and end with a line break.

This is a thought, perhaps an explanation of what I have done in human readable format. It may be complex and long consisting of several sentences that describe my work in essay format. It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts. The user may be reading this on a phone or a wide screen monitor. Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across? It is a truly painful experience. Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph. Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

My suspicion is that the author of Git commit message recommendation you linked has never written software that will be consumed by a wide array of end-users on different devices before (i.e., a website) since at this point in the evolution of software/computing it is well known that storing your data with hard-coded presentation information is a bad idea as far as user experience goes.

Simple PHP form: Attachment to email (code golf)

In order to add the file to the email as an attachment, it will need to be stored on the server briefly. It's trivial, though, to place it in a tmp location then delete it after you're done with it.

As for emailing, Zend Mail has a very easy to use interface for dealing with email attachments. We run with the whole Zend Framework installed, but I'm pretty sure you could just install the Zend_Mail library without needing any other modules for dependencies.

With Zend_Mail, sending an email with an attachment is as simple as:

$mail = new Zend_Mail();
$mail->setSubject("My Email with Attachment");
$mail->addTo("[email protected]");
$mail->setBodyText("Look at the attachment");
$attachment = $mail->createAttachment(file_get_contents('/path/to/file'));
$mail->send();

If you're looking for a one-file-package to do the whole form/email/attachment thing, I haven't seen one. But the individual components are certainly available and easy to assemble. Trickiest thing of the whole bunch is the email attachment, which the above recommendation makes very simple.

Query to check index on a table

If you just need the indexed columns EXEC sp_helpindex 'TABLE_NAME'

Best way to encode text data for XML

This might be the case where you could benefit from using the WriteCData method.

public override void WriteCData(string text)
    Member of System.Xml.XmlTextWriter

Summary:
Writes out a <![CDATA[...]]> block containing the specified text.

Parameters:
text: Text to place inside the CDATA block.

A simple example would look like the following:

writer.WriteStartElement("name");
writer.WriteCData("<unsafe characters>");
writer.WriteFullEndElement();

The result looks like:

<name><![CDATA[<unsafe characters>]]></name>

When reading the node values the XMLReader automatically strips out the CData part of the innertext so you don't have to worry about it. The only catch is that you have to store the data as an innerText value to an XML node. In other words, you can't insert CData content into an attribute value.

Launch Image does not show up in my iOS App

* (Xcode 7.2 / Deployment Target 7.0 / Landscape Orientation Only) *

I know is an old question but with Xcode 7.2 I'm still getting the message and I fixed with this:

1) Select PORTRAIT and both landscapes. Add "Launch Images Source" and "Launch Screen File"

enter image description here

2) In your Launch Image select iPhone "8.0 and Later" and "7.0 and Later".

enter image description here

3) Add this code in your appDelegate:

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
#else
- (UIInterfaceOrientationMask)application:(UIApplication *)application     supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return (UIInterfaceOrientationMaskLandscape);
}
#endif

4) Add this on your ViewController

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)supportedInterfaceOrientations
#else
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
#endif
{
     return UIInterfaceOrientationMaskLandscape;
}

I hope help to somebody else.

Correct way to synchronize ArrayList in java

Yes it is the correct way, but the synchronised block is required if you want all the removals together to be safe - unless the queue is empty no removals allowed. My guess is that you just want safe queue and dequeue operations, so you can remove the synchronised block.

However, there are far advanced concurrent queues in Java such as ConcurrentLinkedQueue

Resize Cross Domain Iframe Height

If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe container anytime the height of the framed content changes.

Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).

window.addEventListener("load", function(){
    if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe 
    send_height_to_parent_function = function(){
        var height = document.getElementsByTagName("html")[0].clientHeight;
        //console.log("Sending height as " + height + "px");
        parent.postMessage({"height" : height }, "*");
    }
    // send message to parent about height updates
    send_height_to_parent_function(); //whenever the page is loaded
    window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
    var observer = new MutationObserver(send_height_to_parent_function);           // whenever DOM changes PT1
    var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
    observer.observe(window.document, config);                                            // PT3 
});

Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.

<script>
window.addEventListener("message", function(e){
    var this_frame = document.getElementById("healthy_behavior_iframe");
    if (this_frame.contentWindow === e.source) {
        this_frame.height = e.data.height + "px";
        this_frame.style.height = e.data.height + "px";
    }
})
</script>

Put icon inside input element in a form

I achieved this with the code below.

First, you flex the container which makes the input and the icon be on the same line. Aligning items makes them be on the same level.

Then, make the input take up 100% of the width regardless. Give the icon absolute positioning which allows it to overlap with the input.

Then add right padding to the input so the text typed in doesn't get to the icon. And finally use the right css property to give the icon some space from the edge of the input.

Note: The Icon tag could be a real icon if you are working with ReactJs or a placeholder for any other way you work with icons in your project.

_x000D_
_x000D_
.inputContainer {
  display: flex;
  align-items: center;
  position: relative;
}

.input {
  width: 100%;
  padding-right: 40px;
}

.inputIcon {
  position: absolute;
  right: 10px;
}
_x000D_
<div class="inputContainer">
   <input class="input" />
   <Icon class="inputIcon" />
 </div>
_x000D_
_x000D_
_x000D_

How to parse XML using shellscript?

This really is beyond the capabilities of shell script. Shell script and the standard Unix tools are okay at parsing line oriented files, but things change when you talk about XML. Even simple tags can present a problem:

<MYTAG>Data</MYTAG>

<MYTAG>
     Data
</MYTAG>

<MYTAG param="value">Data</MYTAG>

<MYTAG><ANOTHER_TAG>Data
</ANOTHER_TAG><MYTAG>

Imagine trying to write a shell script that can read the data enclosed in . The three very, very simply XML examples all show different ways this can be an issue. The first two examples are the exact same syntax in XML. The third simply has an attribute attached to it. The fourth contains the data in another tag. Simple sed, awk, and grep commands cannot catch all possibilities.

You need to use a full blown scripting language like Perl, Python, or Ruby. Each of these have modules that can parse XML data and make the underlying structure easier to access. I've use XML::Simple in Perl. It took me a few tries to understand it, but it did what I needed, and made my programming much easier.

adb command for getting ip address assigned by operator

ip route | grep rmnet_data0 | cut -d" " -f1 | cut -d"/" -f1

Change rmnet_data0 to the desired nic, in my case, rmnet_data0 represents the data nic.

To get a list of the available nic's you can use ip route

Remove a git commit which has not been pushed

There are two branches to this question (Rolling back a commit does not mean I want to lose all my local changes):

1. To revert the latest commit and discard changes in the committed file do:

git reset --hard HEAD~1

2. To revert the latest commit but retain the local changes (on disk) do:

git reset --soft HEAD~1

This (the later command) will take you to the state you would have been if you did git add.

If you want to unstage the files after that, do

git reset

Now you can make more changes before adding and then committing again.

Center/Set Zoom of Map to cover all visible Markers?

There is this MarkerClusterer client side utility available for google Map as specified here on Google Map developer Articles, here is brief on what's it's usage:

There are many approaches for doing what you asked for:

  • Grid based clustering
  • Distance based clustering
  • Viewport Marker Management
  • Fusion Tables
  • Marker Clusterer
  • MarkerManager

You can read about them on the provided link above.

Marker Clusterer uses Grid Based Clustering to cluster all the marker wishing the grid. Grid-based clustering works by dividing the map into squares of a certain size (the size changes at each zoom) and then grouping the markers into each grid square.

Before Clustering Before Clustering

After Clustering After Clustering

I hope this is what you were looking for & this will solve your problem :)

Need to remove href values when printing in Chrome

Bootstrap does the same thing (... as the selected answer below).

@media print {
  a[href]:after {
    content: " (" attr(href) ")";
  }
}

Just remove it from there, or override it in your own print stylesheet:

@media print {
  a[href]:after {
    content: none !important;
  }
}

Getting only 1 decimal place

>>> "{:.1f}".format(45.34531)
'45.3'

Or use the builtin round:

>>> round(45.34531, 1)
45.299999999999997

Bringing a subview to be in front of all other views

As far as i experienced zposition is a best way.

self.view.layer.zPosition = 1;

replace all occurrences in a string

Brighams answer uses literal regexp.

Solution with a Regex object.

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

TRY IT HERE : JSFiddle Working Example

Adding a directory to the PATH environment variable in Windows

Checking the above suggestions on Windows 10 LTSB, and with a glimpse on the "help" outlines (that can be viewed when typing 'command /?' on the cmd), brought me to the conclusion that the PATH command changes the system environment variable Path values only for the current session, but after reboot all the values reset to their default- just as they were prior to using the PATH command.

On the other hand using the SETX command with administrative privileges is way more powerful. It changes those values for good (or at least until the next time this command is used or until next time those values are manually GUI manipulated... ).

The best SETX syntax usage that worked for me:

SETX PATH "%PATH%;C:\path\to\where\the\command\resides"

where any equal sign '=' should be avoided, and don't you worry about spaces! There isn't any need to insert any more quotation marks for a path that contains spaces inside it - the split sign ';' does the job.

The PATH keyword that follows the SETX defines which set of values should be changed among the System Environment Variables possible values, and the %PATH% (the word PATH surrounded by the percent sign) inside the quotation marks, tells the OS to leave the existing PATH values as they are and add the following path (the one that follows the split sign ';') to the existing values.

What is the best way to detect a mobile device?

Crude, but sufficient for restricting loading larger resources such as video files on phones vs tablet/desktop - simply look for small width or height to cover both orientations. Obviously, if the desktop browser has been resized the below could erroneously detect a phone, but that's fine / close enough for my use case.

Why 480, bcs that's what looks about right based on the info I've found re phone device dimensions.

if(document.body.clientWidth < 480 || document.body.clientHeight < 480) {
  //this is a mobile device
}

Convert Text to Uppercase while typing in Text box

Edit (for ASP.NET)

After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase() may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:

.upper-case
{
    text-transform: uppercase
}

And add upper-case class to your text-box:

<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>

General (Old) Answer

but it capitalize characters after pressing Enter key.

It depends where you put that code. If you put it in, for example, TextChanged event it'll make upper case as you type.

You have a property that do exactly what you need: CharacterCasing:

TextBox1.CharacterCasing = CharacterCasing.Upper;

It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.

You may mimic CharacterCasing property adding this code in KeyPress event handler:

e.KeyChar = Char.ToUpper(e.KeyChar);

Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ? and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:

However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.

There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.

Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.

If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.

What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:

abstract class Unicode
{
    public static string ToUpper(string text)
    {
        return GetConcreteClass().ToUpperCore(text);
    }

    protected virtual string ToUpperCore(string text)
    {
        // Default implementation, overridden in derived classes if needed
        return text.ToUpper();
    }

    private Dictionary<string, Unicode> _implementations;

    private Unicode GetConcreteClass()
    {
        string cultureName = Thread.Current.CurrentCulture.Name;

        // Check if concrete class has been loaded and put in dictionary
        ...

        return _implementations[cultureName];
    }
}

I'll then have an implementation specific for German language:

sealed class German : Unicode
{
    protected override string ToUpperCore(string text)
    {
        // Very naive implementation, just to provide an example
        return text.ToUpper().Replace("ß", "?");
    }
}

True implementation may be pretty more complicate (not all OSes supports upper case ?) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.

Using port number in Windows host file

The hosts file is for host name resolution only (on Windows as well as on Unix-like systems). You cannot put port numbers in there, and there is no way to do what you want with generic OS-level configuration - the browser is what selects the port to choose.

So use bookmarks or something like that.
(Some firewall/routing software might allow outbound port redirection, but that doesn't really sound like an appealing option for this.)

Sort an Array by keys based on another Array?

Without magic...

$array=array(28=>c,4=>b,5=>a);
$seq=array(5,4,28);    
SortByKeyList($array,$seq) result: array(5=>a,4=>b,28=>c);

function sortByKeyList($array,$seq){
    $ret=array();
    if(empty($array) || empty($seq)) return false;
    foreach($seq as $key){$ret[$key]=$dataset[$key];}
    return $ret;
}

Convert a python dict to a string and back

I use yaml for that if needs to be readable (neither JSON nor XML are that IMHO), or if reading is not necessary I use pickle.

Write

from pickle import dumps, loads
x = dict(a=1, b=2)
y = dict(c = x, z=3)
res = dumps(y)
open('/var/tmp/dump.txt', 'w').write(res)

Read back

from pickle import dumps, loads
rev = loads(open('/var/tmp/dump.txt').read())
print rev

In Perl, how to remove ^M from a file?

You found out you can also do this:

$line=~ tr/\015//d;

Split string in C every white space

you can scan the char array looking for the token if you found it just print new line else print the char.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int main()
    {
        char *s;
        s = malloc(1024 * sizeof(char));
        scanf("%[^\n]", s);
        s = realloc(s, strlen(s) + 1);
        int len = strlen(s);
        char delim =' ';
        for(int i = 0; i < len; i++) {
            if(s[i] == delim) {
                printf("\n");
            }
            else {
                printf("%c", s[i]);
            }
        }
        free(s);
        return 0;
    }

Django: How can I call a view function from template?

you can put the input inside a form like this:-

<script>
    $(document).ready(function(){
        $(document).on('click','#send', function(){
            $('#hid').val(data)
            document.forms["myForm"].submit();
        })
    })
</script>

<form id="myForm" action="/request_page url/" method="post">
    <input type="hidden" id="hid" name="hid"/>
</form>
<div id="send">Send Data</div>

Performance of FOR vs FOREACH in PHP

My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy... The time difference is going to be minimal in most cases.

The big thing to watch for is:

for ($i = 0; $i < count($array); $i++) {

That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...

As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...

As for the iterators, foreach is equivalent to:

$it->rewind();
while ($it->valid()) {
    $key = $it->key();     // If using the $key => $value syntax
    $value = $it->current();

    // Contents of loop in here

    $it->next();
}

As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil...

Edit: Based upon the comment, I decided to do a quick benchmark run...

$a = array();
for ($i = 0; $i < 10000; $i++) {
    $a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v) {
    $a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {
    $v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}    
echo "Completed in ", microtime(true) - $start, " Seconds\n";

And the results:

Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you're modifying the array in the loop, it's several times faster to use references...

And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...

Changing navigation title programmatically

Swift 5.1

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "What ever you want"
}

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

force Maven to copy dependencies into target/lib

You can use the the Shade Plugin to create an uber jar in which you can bundle all your 3rd party dependencies.

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

getFragmentManager()

just try this.it worked for my case

How to get the current date without the time?

DateTime.Now.ToString("dd/MM/yyyy");

How to trim a file extension from a String in JavaScript?

You can perhaps use the assumption that the last dot will be the extension delimiter.

var x = 'filename.jpg';
var f = x.substr(0, x.lastIndexOf('.'));

If file has no extension, it will return empty string. To fix that use this function

function removeExtension(filename){
    var lastDotPosition = filename.lastIndexOf(".");
    if (lastDotPosition === -1) return filename;
    else return filename.substr(0, lastDotPosition);
}

How to grep recursively, but only in files with certain extensions?

Should write "-exec grep " for each "-o -name "

find . -name '*.h' -exec grep -Hn "CP_Image" {} \; -o -name '*.cpp' -exec grep -Hn "CP_Image" {} \;

Or group them by ( )

find . \( -name '*.h' -o -name '*.cpp' \) -exec grep -Hn "CP_Image" {} \;

option '-Hn' show the file name and line.

Update React component every second

Owing to changes in React V16 where componentWillReceiveProps() has been deprecated, this is the methodology that I use for updating a component. Notice that the below example is in Typescript and uses the static getDerivedStateFromProps method to get the initial state and updated state whenever the Props are updated.

    class SomeClass extends React.Component<Props, State> {
  static getDerivedStateFromProps(nextProps: Readonly<Props>): Partial<State> | null {
    return {
      time: nextProps.time
    };
  }

  timerInterval: any;

  componentDidMount() {
    this.timerInterval = setInterval(this.tick.bind(this), 1000);
  }

  tick() {
    this.setState({ time: this.props.time });
  }

  componentWillUnmount() {
    clearInterval(this.timerInterval);
  }

  render() {
    return <div>{this.state.time}</div>;
  }
}

Removing a list of characters in string

simple way,

import re
str = 'this is string !    >><< (foo---> bar) @-tuna-#   sandwich-%-is-$-* good'

// condense multiple empty spaces into 1
str = ' '.join(str.split()

// replace empty space with dash
str = str.replace(" ","-")

// take out any char that matches regex
str = re.sub('[!@#$%^&*()_+<>]', '', str)

output:

this-is-string--foo----bar--tuna---sandwich--is---good

Why are elementwise additions much faster in separate loops than in a combined loop?

Imagine you are working on a machine where n was just the right value for it only to be possible to hold two of your arrays in memory at one time, but the total memory available, via disk caching, was still sufficient to hold all four.

Assuming a simple LIFO caching policy, this code:

for(int j=0;j<n;j++){
    a[j] += b[j];
}
for(int j=0;j<n;j++){
    c[j] += d[j];
}

would first cause a and b to be loaded into RAM and then be worked on entirely in RAM. When the second loop starts, c and d would then be loaded from disk into RAM and operated on.

the other loop

for(int j=0;j<n;j++){
    a[j] += b[j];
    c[j] += d[j];
}

will page out two arrays and page in the other two every time around the loop. This would obviously be much slower.

You are probably not seeing disk caching in your tests but you are probably seeing the side effects of some other form of caching.


There seems to be a little confusion/misunderstanding here so I will try to elaborate a little using an example.

Say n = 2 and we are working with bytes. In my scenario we thus have just 4 bytes of RAM and the rest of our memory is significantly slower (say 100 times longer access).

Assuming a fairly dumb caching policy of if the byte is not in the cache, put it there and get the following byte too while we are at it you will get a scenario something like this:

  • With

    for(int j=0;j<n;j++){
     a[j] += b[j];
    }
    for(int j=0;j<n;j++){
     c[j] += d[j];
    }
    
  • cache a[0] and a[1] then b[0] and b[1] and set a[0] = a[0] + b[0] in cache - there are now four bytes in cache, a[0], a[1] and b[0], b[1]. Cost = 100 + 100.

  • set a[1] = a[1] + b[1] in cache. Cost = 1 + 1.
  • Repeat for c and d.
  • Total cost = (100 + 100 + 1 + 1) * 2 = 404

  • With

    for(int j=0;j<n;j++){
     a[j] += b[j];
     c[j] += d[j];
    }
    
  • cache a[0] and a[1] then b[0] and b[1] and set a[0] = a[0] + b[0] in cache - there are now four bytes in cache, a[0], a[1] and b[0], b[1]. Cost = 100 + 100.

  • eject a[0], a[1], b[0], b[1] from cache and cache c[0] and c[1] then d[0] and d[1] and set c[0] = c[0] + d[0] in cache. Cost = 100 + 100.
  • I suspect you are beginning to see where I am going.
  • Total cost = (100 + 100 + 100 + 100) * 2 = 800

This is a classic cache thrash scenario.

When should we use intern method of String on String literals

I want to add my 2 cents on using == with interned strings.

The first thing String.equals does is this==object.

So although there is some miniscule performance gain ( you are not calling a method), from the maintainer point of view using == is a nightmare, because some interned strings have a tendency to become non-interned.

So I suggest not to rely on special case of == for interned strings, but always use equals as Gosling intended.

EDIT: interned becoming non-interned:

V1.0
public class MyClass
{
  private String reference_val;

  ...

  private boolean hasReferenceVal ( final String[] strings )
  {
    for ( String s : strings )
    {
      if ( s == reference_val )
      {
        return true;
      }
    }

    return false;
  }

  private void makeCall ( )
  {
     final String[] interned_strings =  { ... init with interned values ... };

     if ( hasReference( interned_strings ) )
     {
        ...
     }
  }
}

In version 2.0 maintainer decided to make hasReferenceVal public, without going into much detail that it expects an array of interned strings.

V2.0
public class MyClass
{
  private String reference_val;

  ...

  public boolean hasReferenceVal ( final String[] strings )
  {
    for ( String s : strings )
    {
      if ( s == reference_val )
      {
        return true;
      }
    }

    return false;
  }

  private void makeCall ( )
  {
     final String[] interned_strings =  { ... init with interned values ... };

     if ( hasReference( interned_strings ) )
     {
        ...
     }
  }
}

Now you have a bug, that may be very hard to find, because in majority of cases array contains literal values, and sometimes a non-literal string is used. If equals were used instead of == then hasReferenceVal would have still continue to work. Once again, performance gain is miniscule, but maintenance cost is high.

How to deal with missing src/test/java source folder in Android/Maven project?

I had the same issue, fixed it. Create the missing folder directly in your file system (Using windows explorer for example) . And then, refresh your project under eclipse.

Initialization of an ArrayList in one line

With and above, as suggested in JEP 269: Convenience Factory Methods for Collections, this could be achieved using collection literals now with -

List<String> list = List.of("A", "B", "C");

Set<String> set = Set.of("A", "B", "C");

A similar approach would apply to Map as well -

Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")

which is similar to Collection Literals proposal as stated by @coobird. Further clarified in the JEP as well -


Alternatives

Language changes have been considered several times, and rejected:

Project Coin Proposal, 29 March 2009

Project Coin Proposal, 30 March 2009

JEP 186 discussion on lambda-dev, January-March 2014

The language proposals were set aside in preference to a library-based proposal as summarized in this message.

Related: What is the point of overloaded Convenience Factory Methods for Collections in Java 9

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

In swift 5.3 and Inspired by @ravron answer:

extension UIButton {
    /// Fits the image and text content with a given spacing
    /// - Parameters:
    ///   - spacing: Spacing between the Image and the text
    ///   - contentXInset: The spacing between the view to the left image and the right text to the view
    func setHorizontalMargins(imageTextSpacing: CGFloat, contentXInset: CGFloat = 0) {
        let imageTextSpacing = imageTextSpacing / 2
        
        contentEdgeInsets = UIEdgeInsets(top: 0, left: (imageTextSpacing + contentXInset), bottom: 0, right: (imageTextSpacing + contentXInset))
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -imageTextSpacing, bottom: 0, right: imageTextSpacing)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: imageTextSpacing, bottom: 0, right: -imageTextSpacing)
    }
}

It adds an extra horizontal margin from the View to the Image and from the Label to the View

How to easily consume a web service from PHP

I've had great success with wsdl2php. It will automatically create wrapper classes for all objects and methods used in your web service.

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

Is there a regular expression to detect a valid regular expression?

You can submit the regex to preg_match which will return false if the regex is not valid. Don't forget to use the @ to suppress error messages:

@preg_match($regexToTest, '');
  • Will return 1 if the regex is //.
  • Will return 0 if the regex is okay.
  • Will return false otherwise.

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

What to put in a python module docstring?

Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

then:

>>> import x; help(x)

shows:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.

In c, in bool, true == 1 and false == 0?

More accurately anything that is not 0 is true.

So 1 is true, but so is 2, 3 ... etc.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

Minimal example

And just to make what Mizux said as a minimal example:

main_c.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

main_cpp.cpp

#include <iostream>

int main(void) {
    std::cout << "hello" << std::endl;
}

Then, without any Makefile:

make CFLAGS='-g -O3' \
     CXXFLAGS='-ggdb3 -O0' \
     CPPFLAGS='-DX=1 -DY=2' \
     CCFLAGS='--asdf' \
     main_c \
     main_cpp

runs:

cc -g -O3 -DX=1 -DY=2   main_c.c   -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2   main_cpp.cpp   -o main_cpp

So we understand that:

  • make had implicit rules to make main_c and main_cpp from main_c.c and main_cpp.cpp
  • CFLAGS and CPPFLAGS were used as part of the implicit rule for .c compilation
  • CXXFLAGS and CPPFLAGS were used as part of the implicit rule for .cpp compilation
  • CCFLAGS is not used

Those variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:

main_c: main_c.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<

main_cpp: main_c.c
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

to achieve a similar affect to the implicit rules.

We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.

Tested in Ubuntu 16.04, GNU Make 4.1.

What is href="#" and why is it used?

Unordered lists are often created with the intent of using them as a menu, but an li list item is text. Because the list li item is text, the mouse pointer will not be an arrow, but an "I cursor". Users are accustomed to seeing a pointing finger for a mouse pointer when something is clickable. Using an anchor tag a inside of the li tag causes the mouse pointer to change to a pointing finger. The pointing finger is a lot better for using the list as a menu.

<ul id="menu">
   <li><a href="#">Menu Item 1</a></li>
   <li><a href="#">Menu Item 2</a></li>
   <li><a href="#">Menu Item 3</a></li>
   <li><a href="#">Menu Item 4</a></li>
</ul>

If the list is being used for a menu, and doesn't need a link, then a URL doesn't need to be designated. But the problem is that if you leave out the href attribute, text in the <a> tag is seen as text, and therefore the mouse pointer is back to an I-cursor. The I-cursor might make the user think that the menu item is not clickable. Therefore, you still need an href, but you don't need a link to anywhere.

You could use lots of div or p tags for a menu list, but the mouse pointer would be an I-cursor for them also.

You could use lots of buttons stacked on top of each other for a menu list, but the list seems to be preferable. And that's probably why the href="#" that points to nowhere is used in anchor tags inside of list tags.

You can set the pointer style in CSS, so that is another option. The href="#" to nowhere might just be the lazy way to set some styling.