Programs & Examples On #Cpu time

Copy a file in a sane, safe and efficient way

Too many!

The "ANSI C" way buffer is redundant, since a FILE is already buffered. (The size of this internal buffer is what BUFSIZ actually defines.)

The "OWN-BUFFER-C++-WAY" will be slow as it goes through fstream, which does a lot of virtual dispatching, and again maintains internal buffers or each stream object. (The "COPY-ALGORITHM-C++-WAY" does not suffer this, as the streambuf_iterator class bypasses the stream layer.)

I prefer the "COPY-ALGORITHM-C++-WAY", but without constructing an fstream, just create bare std::filebuf instances when no actual formatting is needed.

For raw performance, you can't beat POSIX file descriptors. It's ugly but portable and fast on any platform.

The Linux way appears to be incredibly fast — perhaps the OS let the function return before I/O was finished? In any case, that's not portable enough for many applications.

EDIT: Ah, "native Linux" may be improving performance by interleaving reads and writes with asynchronous I/O. Letting commands pile up can help the disk driver decide when is best to seek. You might try Boost Asio or pthreads for comparison. As for "can't beat POSIX file descriptors"… well that's true if you're doing anything with the data, not just blindly copying.

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Use String.Format() or TextWriter.Format() (depending on how you actually write to the file) and specify the width of a field.

String.Format("{0,20}{1,15}{2,15}", "Sample Title One", "Element One", "Whatever Else");

You can specify the width of a field within interpolated strings as well:

$"{"Sample Title One",20}{"Element One",15}{"Whatever Else",15}"

And just so you know, you can create a string of repeated characters using the appropriate string contructor.

new String(' ', 20); // string of 20 spaces

How to remove array element in mongodb?

In Mongoose: from the document:

To remove a document from a subdocument array we may pass an object with a matching _id.

contact.phone.pull({ _id: itemId }) // remove
contact.phone.pull(itemId); // this also works

See Leonid Beschastny's answer for the correct answer.

How to get a reversed list view on a list in Java?

I use this:

public class ReversedView<E> extends AbstractList<E>{

    public static <E> List<E> of(List<E> list) {
        return new ReversedView<>(list);
    }

    private final List<E> backingList;

    private ReversedView(List<E> backingList){
        this.backingList = backingList;
    }

    @Override
    public E get(int i) {
        return backingList.get(backingList.size()-i-1);
    }

    @Override
    public int size() {
        return backingList.size();
    }

}

like this:

ReversedView.of(backingList) // is a fully-fledged generic (but read-only) list

How do I download the Android SDK without downloading Android Studio?

This tutorial is a just step by step for installing Android SDK (Software Development Kit) assuming the user is starting from scratch.

There are just a couple of prerequisites to note:

  • Java runtime environment (or JDK) at Oracle website (and download the correct version (32- or 64-bit) for your computer).
  • A good internet connection (needed for downloading system images etc)

I recommed using the offline SDK installer for installing the essential tools namely SDK and AVD manager: The last version of he installer is found here: SDK Installer_r24.4.1 (for windows), SDK Installer_r24.4.1 (for linux) or SDK Installer_r24.4.1 (for macos)

For this guide I was using windows:

Here is the workthrough:

  • Depending on your choice download the appropriate SDK package from above links (but for this example I will be using the manual method)
  • After downloading the package, begin installation (and choose the desired installation folder to proceed or just leave the default %USERPROFILE%\android-sdk):

enter image description here

  • When done leave the option to download system images "checked":

enter image description here

Now we're in business...

  • The SDK manager window will appear, now you need to update/download other sdk packages (i.e platform-tools, system-images, platforms etc according to API levels)

enter image description here

Note: I recommend downloading x86 images as they're much faster tham arm counterparts, also get intel HAXM (hardware accelerated execution manager) driver to significantly increase your emulator speed

  • All set, now you just need to create and configure an Android virtual device matching your target Android version and tweak desired settings.

  • To do this click on the Tools tab in SDK manager and select manage AVDs, then in the following window click Create you'll see a similar screen as below:

enter image description here

  • After that boot the newly created virtual device.

enter image description here

  • Install applications and test as you wish ..

Import regular CSS file in SCSS file?

Simple.

@import "path/to/file.css";

How to force file download with PHP

The following code is a correct way of implementing a download service in php as explained in the following tutorial

header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename=\"$file_name\"");
set_time_limit(0);
$file = @fopen($filePath, "rb");
while(!feof($file)) {
    print(@fread($file, 1024*8));
    ob_flush();
    flush();
}

jquery get all input from specific form

Use HTML Form "elements" attribute:

$.each($("form").elements, function(){ 
    console.log($(this));
    });

Now it's not necessary to provide such names as "input, textarea, select ..." etc.

Passing two command parameters using a WPF binding

If your values are static, you can use x:Array:

<Button Command="{Binding MyCommand}">10
  <Button.CommandParameter>
    <x:Array Type="system:Object">
       <system:String>Y</system:String>
       <system:Double>10</system:Double>
    </x:Array>
  </Button.CommandParameter>
</Button>

Inner Joining three tables

select *
from
    tableA a
        inner join
    tableB b
        on a.common = b.common
        inner join 
    TableC c
        on b.common = c.common

Found 'OR 1=1/* sql injection in my newsletter database

Its better if you use validation code to the users input for making it restricted to use symbols and part of code in your input form. If you embeed php in html code your php code have to become on the top to make sure that it is not ignored as comment if a hacker edit the page and add /* in your html code

Web colors in an Android color xml resource file

If you are just looking for the available colors that already exist with

@android:color/<color>

then you need to look in android.jar >> android >> R.class >> R >> color.

Here is the list that come with Android 4.4W I'm using:

background_dark
background_light
black
darker_gray
holo_blue_bright
holo_blue_dark
holo_blue_light
holo_green_dark
holo_green_light
holo_orange_dark
holo_orange_light
holo_purple
holo_red_dark
holo_red_light
primary_text_dark
primary_text_dark_nodisable
primary_text_light
primary_text_lignt_nodisable
secondary_text_dark
secondary_text_dark_nodisable
secondaryy_text_light
secondary_text_lignt_nodisable
tab_indicator_text
tertiary_text_dark
tertiary_text_light
transparent
white
widget_edittext_dark

Issue with background color and Google Chrome

Adam's chromeFix solution with Paul Alexander's pure-CSS modification solved the problem in Chrome, but not in Safari. A couple additional tweaks solved the problem in Safari, too: width: 100% and z-index:-1 (or some other appropriate negative value that puts this element behind all the other elements on the page).

The CSS:

body:after {display:block; position:absolute; width:100%; height:100%; top:0px; left:0px; z-index:-1; content: "";}

Conditional Logic on Pandas DataFrame

In [1]: df
Out[1]:
   data
0     1
1     2
2     3
3     4

You want to apply a function that conditionally returns a value based on the selected dataframe column.

In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
Out[2]:
0     true
1     true
2    false
3    false
Name: data

You can then assign that returned column to a new column in your dataframe:

In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')

In [4]: df
Out[4]:
   data desired_output
0     1           true
1     2           true
2     3          false
3     4          false

What is the error "Every derived table must have its own alias" in MySQL?

Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT).

Imagine a table called purchases that records purchases made by customers at stores, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
  GROUP BY customer_id HAVING 1 < SUM(1);

..will break with the error Every derived table must have its own alias. To fix:

SELECT DISTINCT customer_id, SUM(1)
  FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
  GROUP BY customer_id HAVING 1 < SUM(1);

( Note the AS custom alias).

Why doesn't margin:auto center an image?

open div then put

style="width:100% ; margin:0px auto;" 

image tag (or) content

close div

Accept server's self-signed ssl certificate in Java client

I had the issue that I was passing a URL into a library which was calling url.openConnection(); I adapted jon-daniel's answer,

public class TrustHostUrlStreamHandler extends URLStreamHandler {

    private static final Logger LOG = LoggerFactory.getLogger(TrustHostUrlStreamHandler.class);

    @Override
    protected URLConnection openConnection(final URL url) throws IOException {

        final URLConnection urlConnection = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).openConnection();

        // adapated from
        // https://stackoverflow.com/questions/2893819/accept-servers-self-signed-ssl-certificate-in-java-client
        if (urlConnection instanceof HttpsURLConnection) {
            final HttpsURLConnection conHttps = (HttpsURLConnection) urlConnection;

            try {
                // Set up a Trust all manager
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
                    }

                    @Override
                    public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {
                    }
                } };

                // Get a new SSL context
                final SSLContext sc = SSLContext.getInstance("TLSv1.2");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                // Set our connection to use this SSL context, with the "Trust all" manager in place.
                conHttps.setSSLSocketFactory(sc.getSocketFactory());
                // Also force it to trust all hosts
                final HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(final String hostname, final SSLSession session) {
                        return true;
                    }
                };

                // and set the hostname verifier.
                conHttps.setHostnameVerifier(allHostsValid);

            } catch (final NoSuchAlgorithmException e) {
                LOG.warn("Failed to override URLConnection.", e);
            } catch (final KeyManagementException e) {
                LOG.warn("Failed to override URLConnection.", e);
            }

        } else {
            LOG.warn("Failed to override URLConnection. Incorrect type: {}", urlConnection.getClass().getName());
        }

        return urlConnection;
    }

}

Using this class it is possible to create a new URL with:

trustedUrl = new URL(new URL(originalUrl), "", new TrustHostUrlStreamHandler());
trustedUrl.openConnection();

This has the advantage that it is localized and not replacing the default URL.openConnection.

How to import data from one sheet to another

Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.

NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)

Here is a link with the appropriate formulas.

The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))

  • IF(A2="","", means if A2 is blank, return a blank value
  • INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
  • Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
  • Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
  • ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.

More information on the Index/Match formula

Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.

I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.

Good luck! Hope this helps.

align right in a table cell with CSS

Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify

table tr td:nth-child(2) {
    text-align: right;
}

In cases with large tables this can save you a lot of extra markup!

here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/

How to use group by with union in t-sql

Identifying the column is easy:

SELECT  *
FROM    ( SELECT    id,
                    time
          FROM      dbo.a
          UNION
          SELECT    id,
                    time
          FROM      dbo.b
        )
GROUP BY id

But it doesn't solve the main problem of this query: what's to be done with the second column values upon grouping by the first? Since (peculiarly!) you're using UNION rather than UNION ALL, you won't have entirely duplicated rows between the two subtables in the union, but you may still very well have several values of time for one value of the id, and you give no hint of what you want to do - min, max, avg, sum, or what?! The SQL engine should give an error because of that (though some such as mysql just pick a random-ish value out of the several, I believe sql-server is better than that).

So, for example, change the first line to SELECT id, MAX(time) or the like!

MySQL Workbench not displaying query results

I had the same issue. Using MySQL 6.1 Workbench.

After a while (2 mins), it just crashed. Reported bug, saved files and reopened. It works now.

I guess I would suggest if that happens again, to immediately save the open scripts, close MySQL and restart it.

How can I pass a parameter to a setTimeout() callback?

My answer:

setTimeout((function(topicId) {
  return function() {
    postinsql(topicId);
  };
})(topicId), 4000);

Explanation:

The anonymous function created returns another anonymous function. This function has access to the originally passed topicId, so it will not make an error. The first anonymous function is immediately called, passing in topicId, so the registered function with a delay has access to topicId at the time of calling, through closures.

OR

This basically converts to:

setTimeout(function() {
  postinsql(topicId); // topicId inside higher scope (passed to returning function)
}, 4000);

EDIT: I saw the same answer, so look at his. But I didn't steal his answer! I just forgot to look. Read the explanation and see if it helps to understand the code.

Sort columns of a dataframe by column name

test = data.frame(C=c(0,2,4, 7, 8), A=c(4,2,4, 7, 8), B=c(1, 3, 8,3,2))

Using the simple following function replacement can be performed (but only if data frame does not have many columns):

test <- test[, c("A", "B", "C")]

for others:

test <- test[, c("B", "A", "C")]

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

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

:setvar dbname "TEST" 

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

EDIT:

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

MySQLi count(*) always returns 1

Always try to do an associative fetch, that way you can easy get what you want in multiple case result

Here's an example

$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";

No such keg: /usr/local/Cellar/git

Os X Mojave 10.14 has:

Error: The Command Line Tools header package must be installed on Mojave.

Solution. Go to

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

location and install the package manually. And brew will start working and we can run:

brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git

Display TIFF image in all web browser

This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:

http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support

Where are you getting the tiff images from? Is it possible for them to be generated in a different format?

If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.

If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.

Apply pandas function to column to create multiple new columns?

The accepted solution is going to be extremely slow for lots of data. The solution with the greatest number of upvotes is a little difficult to read and also slow with numeric data. If each new column can be calculated independently of the others, I would just assign each of them directly without using apply.

Example with fake character data

Create 100,000 strings in a DataFrame

df = pd.DataFrame(np.random.choice(['he jumped', 'she ran', 'they hiked'],
                                   size=100000, replace=True),
                  columns=['words'])
df.head()
        words
0     she ran
1     she ran
2  they hiked
3  they hiked
4  they hiked

Let's say we wanted to extract some text features as done in the original question. For instance, let's extract the first character, count the occurrence of the letter 'e' and capitalize the phrase.

df['first'] = df['words'].str[0]
df['count_e'] = df['words'].str.count('e')
df['cap'] = df['words'].str.capitalize()
df.head()
        words first  count_e         cap
0     she ran     s        1     She ran
1     she ran     s        1     She ran
2  they hiked     t        2  They hiked
3  they hiked     t        2  They hiked
4  they hiked     t        2  They hiked

Timings

%%timeit
df['first'] = df['words'].str[0]
df['count_e'] = df['words'].str.count('e')
df['cap'] = df['words'].str.capitalize()
127 ms ± 585 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

def extract_text_features(x):
    return x[0], x.count('e'), x.capitalize()

%timeit df['first'], df['count_e'], df['cap'] = zip(*df['words'].apply(extract_text_features))
101 ms ± 2.96 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Surprisingly, you can get better performance by looping through each value

%%timeit
a,b,c = [], [], []
for s in df['words']:
    a.append(s[0]), b.append(s.count('e')), c.append(s.capitalize())

df['first'] = a
df['count_e'] = b
df['cap'] = c
79.1 ms ± 294 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Another example with fake numeric data

Create 1 million random numbers and test the powers function from above.

df = pd.DataFrame(np.random.rand(1000000), columns=['num'])


def powers(x):
    return x, x**2, x**3, x**4, x**5, x**6

%%timeit
df['p1'], df['p2'], df['p3'], df['p4'], df['p5'], df['p6'] = \
       zip(*df['num'].map(powers))
1.35 s ± 83.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Assigning each column is 25x faster and very readable:

%%timeit 
df['p1'] = df['num'] ** 1
df['p2'] = df['num'] ** 2
df['p3'] = df['num'] ** 3
df['p4'] = df['num'] ** 4
df['p5'] = df['num'] ** 5
df['p6'] = df['num'] ** 6
51.6 ms ± 1.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

I made a similar response with more details here on why apply is typically not the way to go.

html button to send email

As David notes, his suggestion does not actually fulfill the OP's request, which was an email with subject and message. It doesn't work because most, maybe all, combinations of browsers plus e-mail clients do not accept the subject and body attributes of the mailto: URI when supplied as a <form>'s action.

But here's a working example:

HTML (with Bootstrap styles):

<p><input id="subject" type="text" placeholder="type your subject here" 
    class="form-control"></p>
<p><input id="message" type="text" placeholder="type your message here" 
    class="form-control"></p>
<p><a id="mail-link" class="btn btn-primary">Create email</a></p>

JavaScript (with jQuery):

<script type="text/javascript">
    function loadEvents() {
        var mailString;
        function updateMailString() {
            mailString = '?subject=' + encodeURIComponent($('#subject').val())
                + '&body=' + encodeURIComponent($('#message').val());
            $('#mail-link').attr('href',  'mailto:[email protected]' + mailString);
        }
        $( "#subject" ).focusout(function() { updateMailString(); });
        $( "#message" ).focusout(function() { updateMailString(); });
        updateMailString();
    }
</script>

Notes:

  • The <form> element with associated action attribute is not used.
  • The <input> element of type button is also not used.
    • <a> styled as a button (here using Bootstrap) replaces <input type="button">
    • focusout() with updateMailString() is necessary because the <a> tag's href attribute does not automatically update when the input fields' values change.
    • updateMailString() is also called when document is loaded in case the input fields are prepopulated.
  • Also encodeURIComponent() is used to get characters such as the quotation mark (") across to Outlook.

In this approach, the mailto: URI is supplied (with subject and body attributes) in an a element's href tag. This works in all combinations of browsers and e-mail clients I have tested, which are recent (2015) versions of:

  • Browsers: Firefox/Win&OSX, Chrome/Win&OSX, IE/Win, Safari/OSX&iOS, Opera/OSX
  • E-mail clients: Outlook/Win, Mail.app/OSX&iOS, Sparrow/OSX

Bonus tip: In my use cases, I add some contextual text to the e-mail body. More often than not, I want that text to contain line breaks. %0D%0A (carriage return and linefeed) works in my tests.

Java time-based map/cache with expiring keys

Yes. Google Collections, or Guava as it is named now has something called MapMaker which can do exactly that.

ConcurrentMap<Key, Graph> graphs = new MapMaker()
   .concurrencyLevel(4)
   .softKeys()
   .weakValues()
   .maximumSize(10000)
   .expiration(10, TimeUnit.MINUTES)
   .makeComputingMap(
       new Function<Key, Graph>() {
         public Graph apply(Key key) {
           return createExpensiveGraph(key);
         }
       });

Update:

As of guava 10.0 (released September 28, 2011) many of these MapMaker methods have been deprecated in favour of the new CacheBuilder:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
    .maximumSize(10000)
    .expireAfterWrite(10, TimeUnit.MINUTES)
    .build(
        new CacheLoader<Key, Graph>() {
          public Graph load(Key key) throws AnyException {
            return createExpensiveGraph(key);
          }
        });

Uppercase first letter of variable

var country= $('#country').val();

var con=country[0].toUpperCase();

ctr= country.replace(country[0], con);
   

no need to create any function just jugaaar

Inverse dictionary lookup in Python

This version is 26% shorter than yours but functions identically, even for redundant/ambiguous values (returns the first match, as yours does). However, it is probably twice as slow as yours, because it creates a list from the dict twice.

key = dict_obj.keys()[dict_obj.values().index(value)]

Or if you prefer brevity over readability you can save one more character with

key = list(dict_obj)[dict_obj.values().index(value)]

And if you prefer efficiency, @PaulMcGuire's approach is better. If there are lots of keys that share the same value it's more efficient not to instantiate that list of keys with a list comprehension and instead use use a generator:

key = (key for key, value in dict_obj.items() if value == 'value').next()

JQuery: How to get selected radio button value?

This Jquery method returns the default vale 0 when page loads...

$('input[type="radio"]:checked').val();

What is the use of ObservableCollection in .net?

Explanation without Code

For those wanting an answer without any code behind it (boom-tish) with a story (to help you remember):

Normal Collections - No Notifications

Every now and then I go to NYC and my wife asks me to buy stuff. So I take a shopping list with me. The list has a lot of things on there like:

  1. Louis Vuitton handbag ($5000)
  2. Clive Christian’s Imperial Majesty Perfume ($215,000 )
  3. Gucci Sunglasses ($2000)

hahaha well I"m not buying that stuff. So I cross them off and remove them from the list and I add instead:

  1. 12 dozen Titleist golf balls.
  2. 12 lb bowling ball.

So I usually come home without the goods and she's never pleased. The thing is that she doesn't know about what i take off the list and what I add onto it; she gets no notifications.

The ObservableCollection - notifications when changes made

Now, whenever I remove something from the list: she get's a notification on her phone (i.e. sms / email etc)!

The observable collection works just the same way. If you add or remove something to or from it: someone is notified. And when they are notified, well then they call you and you'll get a ear-full. Of course the consequences are customisable via the event handler.

That sums it all up!

How to use GROUP BY to concatenate strings in SQL Server?

I ran into a couple of problems when I tried converting Kevin Fairchild's suggestion to work with strings containing spaces and special XML characters (&, <, >) which were encoded.

The final version of my code (which doesn't answer the original question but may be useful to someone) looks like this:

CREATE TABLE #YourTable ([ID] INT, [Name] VARCHAR(MAX), [Value] INT)

INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'Oranges & Lemons',4)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'1 < 2',8)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)

SELECT  [ID],
  STUFF((
    SELECT ', ' + CAST([Name] AS VARCHAR(MAX))
    FROM #YourTable WHERE (ID = Results.ID) 
    FOR XML PATH(''),TYPE 
     /* Use .value to uncomment XML entities e.g. &gt; &lt; etc*/
    ).value('.','VARCHAR(MAX)') 
  ,1,2,'') as NameValues
FROM    #YourTable Results
GROUP BY ID

DROP TABLE #YourTable

Rather than using a space as a delimiter and replacing all the spaces with commas, it just pre-pends a comma and space to each value then uses STUFF to remove the first two characters.

The XML encoding is taken care of automatically by using the TYPE directive.

trace a particular IP and port

you can use tcpdump on the server to check if the client even reaches the server.

  tcpdump -i any tcp port 9100

also make sure your firewall is not blocking incoming connections.

EDIT: you can also write the dump into a file and view it with wireshark on your client if you don't want to read it on the console.

2nd Edit: you can check if you can reach the port via

 nc ip 9100 -z -v

from your local PC.

How to find all duplicate from a List<string>?

In .NET framework 3.5 and above you can use Enumerable.GroupBy which returns an enumerable of enumerables of duplicate keys, and then filter out any of the enumerables that have a Count of <=1, then select their keys to get back down to a single enumerable:

var duplicateKeys = list.GroupBy(x => x)
                        .Where(group => group.Count() > 1)
                        .Select(group => group.Key);

phpinfo() - is there an easy way for seeing it?

If you are using WAMP then type the following in the browser
http://localhost/?phpinfo=-1, you will get the phpinfo page.

phpinfo() from localhost

You can also click the localhost icon in the wamp menu from the systray and then find the phpinfo page. WAMP localhost from WAMP Menu

How can I set the default value for an HTML <select> element?

If you are using select with angular 1, then you need to use ng-init, otherwise, second option will not be selected since, ng-model overrides the defaul selected value

<select ng-model="sortVar" ng-init='sortVar="stargazers_count"'>
  <option value="name">Name</option>
  <option selected="selected" value="stargazers_count">Stars</option>
  <option value="language">Language</option>
</select>

Test if registry value exists

$regkeypath= "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" 
$value1 = (Get-ItemProperty $regkeypath -ErrorAction SilentlyContinue).Zoiper -eq $null 
If ($value1 -eq $False) {
Write-Host "Value Exist"
} Else {
Write-Host "The value does not exist"
}

Polygon Drawing and Getting Coordinates with Google Map API v3

If all you need is the coordinates here is a drawing tool I like to use - move the polygon or re-shape it and the coordinates will display right below the map: jsFiddle here.

Also, here is a Codepen

JS

var bermudaTriangle;
function initialize() {
    var myLatLng = new google.maps.LatLng(33.5190755, -111.9253654);
    var mapOptions = {
        zoom: 12,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.RoadMap
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'),
                                  mapOptions);


    var triangleCoords = [
        new google.maps.LatLng(33.5362475, -111.9267386),
        new google.maps.LatLng(33.5104882, -111.9627875),
        new google.maps.LatLng(33.5004686, -111.9027061)

    ];

    // Construct the polygon
    bermudaTriangle = new google.maps.Polygon({
        paths: triangleCoords,
        draggable: true,
        editable: true,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });

    bermudaTriangle.setMap(map);
    google.maps.event.addListener(bermudaTriangle, "dragend", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "insert_at", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "remove_at", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "set_at", getPolygonCoords);
}

function getPolygonCoords() {
    var len = bermudaTriangle.getPath().getLength();
    var htmlStr = "";
    for (var i = 0; i < len; i++) {
        htmlStr += bermudaTriangle.getPath().getAt(i).toUrlValue(5) + "<br>";
    }
    document.getElementById('info').innerHTML = htmlStr;
}

HTML

<body onload="initialize()">
    <h3>Drag or re-shape for coordinates to display below</h3>
    <div id="map-canvas">
    </div>
    <div id="info">
    </div>
</body>

CSS

#map-canvas {
    width: auto;
    height: 350px;
}
#info {
    position: absolute;
    font-family: arial, sans-serif;
    font-size: 18px;
    font-weight: bold;
}

How to delete projects in Intellij IDEA 14?

You will have to manually delete from the project explorer (your local machine hard drive), then delete the project in IntelliJ when it asks to re-open recent projects.

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

SQL Server FOR EACH Loop

This kind of depends on what you want to do with the results. If you're just after the numbers, a set-based option would be a numbers table - which comes in handy for all sorts of things.

For MSSQL 2005+, you can use a recursive CTE to generate a numbers table inline:

;WITH Numbers (N) AS (
    SELECT 1 UNION ALL
    SELECT 1 + N FROM Numbers WHERE N < 500 
)
SELECT N FROM Numbers
OPTION (MAXRECURSION 500)

AngularJS check if form is valid in controller

Here is another solution

Set a hidden scope variable in your html then you can use it from your controller:

<span style="display:none" >{{ formValid = myForm.$valid}}</span>

Here is the full working example:

_x000D_
_x000D_
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
  $scope.userType = 'guest';_x000D_
  $scope.formValid = false;_x000D_
  console.info('Ctrl init, no form.');_x000D_
  _x000D_
  $scope.$watch('myForm', function() {_x000D_
    console.info('myForm watch');_x000D_
    console.log($scope.formValid);_x000D_
  });_x000D_
  _x000D_
  $scope.isFormValid = function() {_x000D_
    //test the new scope variable_x000D_
    console.log('form valid?: ', $scope.formValid);_x000D_
  };_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
  userType: <input name="input" ng-model="userType" required>_x000D_
  <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
  <tt>userType = {{userType}}</tt><br>_x000D_
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
  _x000D_
  _x000D_
  /*-- Hidden Variable formValid to use in your controller --*/_x000D_
  <span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
  _x000D_
  _x000D_
  <br/>_x000D_
  <button ng-click="isFormValid()">Check Valid</button>_x000D_
 </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to prevent sticky hover effects for buttons on touch devices

I have nice solution that i would like to share. First you need to detect if user is on mobile like this:

var touchDevice = /ipad|iphone|android|windows phone|blackberry/i.test(navigator.userAgent.toLowerCase());

Then just add:

if (!touchDevice) {
    $(".navbar-ul").addClass("hoverable");
}

And in CSS:

.navbar-ul.hoverable li a:hover {
    color: #fff;
}

How do I clear the std::queue efficiently?

You could create a class that inherits from queue and clear the underlying container directly. This is very efficient.

template<class T>
class queue_clearable : public std::queue<T>
{
public:
    void clear()
    {
        c.clear();
    }
};

Maybe your a implementation also allows your Queue object (here JobQueue) to inherit std::queue<Job> instead of having the queue as a member variable. This way you would have direct access to c.clear() in your member functions.

How to split a string of space separated numbers into integers?

Use str.split():

>>> "42 0".split()  # or .split(" ")
['42', '0']

Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.

Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:

>>> map(int, "42 0".split())
[42, 0]

In Python 3, map will return a lazy object. You can get it into a list with list():

>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

How to update Ruby to 1.9.x on Mac?

I'll make a strong suggestion for rvm.

It's a great way to manage multiple Rubies and gems sets without colliding with the system version.


I'll add that now (4/2/2013), I use rbenv a lot, because my needs are simple. RVM is great, but it's got a lot of capability I never need, so I have it on some machines and rbenv on my desktop and laptop. It's worth checking out both and seeing which works best for your needs.

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

Either use:

pip install xlrd

And if you are using conda, use

conda install -c anaconda xlrd

That's it. good luck.

Remove Duplicates from range of cells in excel vba

You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.

Sub dedupe_abcd()
    Dim icol As Long

    With Sheets("Sheet1")   '<-set this worksheet reference properly!
        icol = Application.Match("abcd", .Rows(1), 0)
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=icol, Header:=xlYes
        End With
    End With
End Sub

Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.

Http Post With Body

You can try something like this using HttpClient and HttpPost:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mystring", "value_of_my_string"));
// etc...

// Post data to the server
HttpPost httppost = new HttpPost("http://...");
httppost.setEntity(new UrlEncodedFormEntity(params));

HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);

How to move certain commits to be based on another branch in git?

I believe it's:

git checkout master
git checkout -b good_quickfix2
git cherry-pick quickfix2^
git cherry-pick quickfix2

How to len(generator())

Generators have no length, they aren't collections after all.

Generators are functions with a internal state (and fancy syntax). You can repeatedly call them to get a sequence of values, so you can use them in loop. But they don't contain any elements, so asking for the length of a generator is like asking for the length of a function.

if functions in Python are objects, couldn't I assign the length to a variable of this object that would be accessible to the new generator?

Functions are objects, but you cannot assign new attributes to them. The reason is probably to keep such a basic object as efficient as possible.

You can however simply return (generator, length) pairs from your functions or wrap the generator in a simple object like this:

class GeneratorLen(object):
    def __init__(self, gen, length):
        self.gen = gen
        self.length = length

    def __len__(self): 
        return self.length

    def __iter__(self):
        return self.gen

g = some_generator()
h = GeneratorLen(g, 1)
print len(h), list(h)

PHP String to Float

If you need to handle values that cannot be converted separately, you can use this method:

try {
    $valueToUse = trim($stringThatMightBeNumeric) + 0;
} catch (\Throwable $th) {
    // bail here if you need to
}

jQuery autocomplete with callback ajax json

I used the construction of $.each (data [i], function (key, value) But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success

How do I fix the multiple-step OLE DB operation errors in SSIS?

Take a look at the fields's proprieties (type, length, default value, etc.), they should be the same.

I had this problem with SQL Server 2008 R2 because the fields's length are not equal.

Faster way to zero memory than with memset?

memset could be inlined by compiler as a series of efficient opcodes, unrolled for a few cycles. For very large memory blocks, like 4000x2000 64bit framebuffer, you can try optimizing it across several threads (which you prepare for that sole task), each setting its own part. Note that there is also bzero(), but it is more obscure, and less likely to be as optimized as memset, and the compiler will surely notice you pass 0.

What compiler usually assumes, is that you memset large blocks, so for smaller blocks it would likely be more efficient to just do *(uint64_t*)p = 0, if you init large number of small objects.

Generally, all x86 CPUs are different (unless you compile for some standardized platform), and something you optimize for Pentium 2 will behave differently on Core Duo or i486. So if you really into it and want to squeeze the last few bits of toothpaste, it makes sense to ship several versions your exe compiled and optimized for different popular CPU models. From personal experience Clang -march=native boosted my game's FPS from 60 to 65, compared to no -march.

How do you make strings "XML safe"?

By either escaping those characters with htmlspecialchars, or, perhaps more appropriately, using a library for building XML documents, such as DOMDocument or XMLWriter.

Another alternative would be to use CDATA sections, but then you'd have to look out for occurrences of ]]>.

Take also into consideration that that you must respect the encoding you define for the XML document (by default UTF-8).

How disable / remove android activity label and label bar?

There's also a drop down menu in the graphical layout window of eclipse. some of the themes in this menu will have ".NoTitleBar" at the end. any of these will do trick.

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

this is how I implement it .

let dictionary = self.convertStringToDictionary(responceString)            
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)

If two cells match, return value from third

All you have to do is write an IF condition in the column d like this:

=IF(A1=C1;B1;" ")

After that just apply this formula to all rows above that one.

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

Also happens when you forget to change the ConnectionString and ask a table that has no idea about the changes you're making locally.

How many parameters are too many?

In Clean Code, Robert C. Martin devoted four pages to the subject. Here's the gist:

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification -- and then shouldn't be used anyway.

Copy output of a JavaScript variable to the clipboard

OK, I found some time and followed the suggestion by Teemu and I was able to get exactly what I wanted.

So here is the final code for anyone that might be interested. For clarification, this code gets all checked checkboxes of a certain ID, outputs them in an array, named here checkbx, and then copies their unique name to the clipboard.

JavaScript function:

function getSelectedCheckboxes(chkboxName) {
  var checkbx = [];
  var chkboxes = document.getElementsByName(chkboxName);
  var nr_chkboxes = chkboxes.length;
  for(var i=0; i<nr_chkboxes; i++) {
    if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
  }
  checkbx.toString();

  // Create a dummy input to copy the string array inside it
  var dummy = document.createElement("input");

  // Add it to the document
  document.body.appendChild(dummy);

  // Set its ID
  dummy.setAttribute("id", "dummy_id");

  // Output the array into it
  document.getElementById("dummy_id").value=checkbx;

  // Select it
  dummy.select();

  // Copy its contents
  document.execCommand("copy");

  // Remove it as its not needed anymore
  document.body.removeChild(dummy);
}

And its HTML call:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('ID_of_chkbxs_selected')">Copy</button>

Convert string to JSON array

Using json lib:-

String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";
Object object=null;
JSONArray arrayObj=null;
JSONParser jsonParser=new JSONParser();
object=jsonParser.parse(data);
arrayObj=(JSONArray) object;
System.out.println("Json object :: "+arrayObj);

Using GSON lib:-

Gson gson = new Gson();
String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(data);

How to filter empty or NULL names in a QuerySet?

From Django 1.8,

from django.db.models.functions import Length

Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

Remove all the children DOM elements in div

If you are looking for a modern >1.7 Dojo way of destroying all node's children this is the way:

// Destroys all domNode's children nodes
// domNode can be a node or its id:
domConstruct.empty(domNode);

Safely empty the contents of a DOM element. empty() deletes all children but keeps the node there.

Check "dom-construct" documentation for more details.

// Destroys domNode and all it's children
domConstruct.destroy(domNode);

Destroys a DOM element. destroy() deletes all children and the node itself.

How do I check particular attributes exist or not in XML?

You can use LINQ to XML,

XDocument doc = XDocument.Load(file);

var result = (from ele in doc.Descendants("section")
              select ele).ToList();

foreach (var t in result)
{
    if (t.Attributes("split").Count() != 0)
    {
        // Exist
    }

    // Suggestion from @UrbanEsc
    if(t.Attributes("split").Any())
    {

    }
}

OR

 XDocument doc = XDocument.Load(file);

 var result = (from ele in doc.Descendants("section").Attributes("split")
               select ele).ToList();

 foreach (var t in result)
 {
     // Response.Write("<br/>" +  t.Value);
 }

Read Excel File in Python

A somewhat late answer, but with pandas, it is possible to get directly a column of an excel file:

import pandas

df = pandas.read_excel('sample.xls')
#print the column names
print df.columns
#get the values for a given column
values = df['Arm_id'].values
#get a data frame with selected columns
FORMAT = ['Arm_id', 'DSPName', 'Pincode']
df_selected = df[FORMAT]

Make sure you have installed xlrd and pandas:

pip install pandas xlrd

GridView Hide Column by code

Here i am binding the gridview with dataset like this-

GVAnswer.DataSource = DS.Tables[0];
GVAnswer.DataBind();

Then after

Then we count the number of rows like this in the for loop

for (int i = 0; i < GVAnswer.Rows.Count; i++)
{

}

Then after we find the header we want make visible false

GVAnswer.HeaderRow.Cells[2].Visible = false;

then after we make the visibility false of that particular cell.

The complete code is give like this

public void FillGVAnswer(int QuestionID) { try { OBJClsQuestionAnswer = new ClsQuestionAnswer(); DS = new DataSet(); DS = OBJClsQuestionAnswer.GetAnswers(QuestionID); GVAnswer.DataSource = DS.Tables[0]; GVAnswer.DataBind(); if (DS.Tables[0].Rows.Count > 0) { for (int i = 0; i < GVAnswer.Rows.Count; i++) { GVAnswer.HeaderRow.Cells[2].Visible = false; GVAnswer.HeaderRow.Cells[3].Visible = false; GVAnswer.HeaderRow.Cells[6].Visible = false; GVAnswer.HeaderRow.Cells[8].Visible = false; GVAnswer.HeaderRow.Cells[10].Visible = false; GVAnswer.HeaderRow.Cells[11].Visible = false; //GVAnswer.Rows[i].Cells[1].Visible = false; if (GVAnswer.Rows[i].Cells[4].Text == "T") { GVAnswer.Rows[i].Cells[4].Text = "Text"; } else { GVAnswer.Rows[i].Cells[4].Text = "Image"; } if (GVAnswer.Rows[i].Cells[5].Text == "View Image") { HtmlAnchor a = new HtmlAnchor(); a.HRef = "~/ImageHandler.aspx?ACT=AIMG&AID=" + GVAnswer.Rows[i].Cells[2].Text; a.Attributes.Add("rel", "lightbox"); a.InnerText = GVAnswer.Rows[i].Cells[5].Text; GVAnswer.Rows[i].Cells[5].Controls.Add(a); } if (GVAnswer.Rows[i].Cells[7].Text == "Yes") { j++; ViewState["CheckHasMulAns"] = j;// To Chek How Many answer Of a particulaer Question Is Right } GVAnswer.Rows[i].Cells[8].Visible = false; GVAnswer.Rows[i].Cells[3].Visible = false; GVAnswer.Rows[i].Cells[10].Visible = false; GVAnswer.Rows[i].Cells[6].Visible = false; GVAnswer.Rows[i].Cells[11].Visible = false; GVAnswer.Rows[i].Cells[2].Visible = false; } } } catch (Exception ex) { string err = ex.Message; if (ex.InnerException != null) { err = err + " :: Inner Exception :- " + ex.InnerException.Message; } string addInfo = "Error in getting Answers :: -> "; ClsExceptionPublisher objPub = new ClsExceptionPublisher(); objPub.Publish(err, addInfo); } }

How to get screen width without (minus) scrollbar?

The safest place to get the correct width and height without the scrollbars is from the HTML element. Try this:

var width = document.documentElement.clientWidth
var height = document.documentElement.clientHeight

Browser support is pretty decent, with IE 9 and up supporting this. For OLD IE, use one of the many fallbacks mentioned here.

Submit a form using jQuery

The solutions so far require you to know the ID of the form.

Use this code to submit the form without needing to know the ID:

function handleForm(field) {
    $(field).closest("form").submit();
}

For example if you were wanting to handle the click event for a button, you could use

$("#buttonID").click(function() {
    handleForm(this);    
});

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

libxml install error using pip

The only thing helped for me was

sudo apt-get install python3.5-dev

Convert date from String to Date format in Dataframes

You can also pass date format

df.withColumn("Date",to_date(unix_timestamp(df.col("your_date_column"), "your_date_format").cast("timestamp")))

For Example

import org.apache.spark.sql.functions._
val df = sc.parallelize(Seq("06 Jul 2018")).toDF("dateCol")
df.withColumn("Date",to_date(unix_timestamp(df.col("dateCol"), "dd MMM yyyy").cast("timestamp")))

PDO's query vs execute

Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.

In one case, I found that query worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.

I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query could be faster than prepare & execute because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.

Given a couple rare conditions:

  1. If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.

  2. If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.

  3. PDO::lastInsertId is not supported by the Microsoft ODBC driver.

Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:

To start, I've created a basic table in Microsoft SQL Server

CREATE TABLE performancetest (
    sid INT IDENTITY PRIMARY KEY,
    id INT,
    val VARCHAR(100)
);

And now a basic timed test for performance metrics.

$logs = [];

$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
    $start = microtime(true);
    $i = 0;
    while ($i < $count) {
        $sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
        if ($type === 'query') {
            $smt = $pdo->query($sql);
        } else {
            $smt = $pdo->prepare($sql);
            $smt ->execute();
        }
        $sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
        $i++;
    }
    $total = (microtime(true) - $start);
    $logs[$type] []= $total;
    echo "$total $type\n";
};

$trials = 15;
$i = 0;
while ($i < $trials) {
    if (random_int(0,1) === 0) {
        $test('query');
    } else {
        $test('prepare');
    }
    $i++;
}

foreach ($logs as $type => $log) {
    $total = 0;
    foreach ($log as $record) {
        $total += $record;
    }
    $count = count($log);
    echo "($count) $type Average: ".$total/$count.PHP_EOL;
}

I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query than prepare/execute

5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769

I'm curious to see how this test compares in other environments, like MySQL.

Access a JavaScript variable from PHP

try adding this to your js function:

    var outputvar = document.getElementById("your_div_id_inside_html_form");
    outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';

Later in html:

    <div id="id_you_choosed_for_outputvar"></div>

this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!. This solution is working fine for me.

In your specific geolocation case you can try adding the following to function showPosition(position):

    var outputlon = document.getElementById("lon1");
    outputlon.innerHTML = '<input id=lon value='+lon+'>';
    var outputlat = document.getElementById("lat1");
    outputlat.innerHTML = '<input id=lat value='+lat+'>';  

later add these div to your html form:

<div id=lat1></div>
<div id=lon1></div>

In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.

Hope this will help.

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

Android Studio - Failed to notify project evaluation listener error

I had this issue because I was using Charles proxy on my computer and the SSL was enabled for all hosts. And since AS didn't trust my proxy, the network request failed. So I had to disable SSL for all hosts and restart my Android Studio.

String.Replace(char, char) method in C#

I know this is an old post but I'd like to add my method.

public static string Replace(string text, string[] toReplace, string replaceWith)
    {
        foreach (string str in toReplace)
           text = text.Replace(str, replaceWith);

        return text;
    }

Example usage:

string newText = Replace("This is an \r\n \n an example.", new string[] { "\r\n", "\n" }, "");

Error: Cannot pull with rebase: You have unstaged changes

Do git status, this will show you what files have changed. Since you stated that you don't want to keep the changes you can do git checkout -- <file name> or git reset --hard to get rid of the changes.

For the most part, git will tell you what to do about changes. For example, your error message said to git stash your changes. This would be if you wanted to keep them. After pulling, you would then do git stash pop and your changes would be reapplied.

git status also has how to get rid of changes depending on if the file is staged for commit or not.

How to download the latest artifact from Artifactory repository?

Using shell/unix tools

  1. curl 'http://$artiserver/artifactory/api/storage/$repokey/$path/$version/?lastModified'

The above command responds with a JSON with two elements - "uri" and "lastModified"

  1. Fetching the link in the uri returns another JSON which has the "downloadUri" of the artifact.

  2. Fetch the link in the "downloadUri" and you have the latest artefact.

Using Jenkins Artifactory plugin

(Requires Pro) to resolve and download latest artifact, if Jenkins Artifactory plugin was used to publish to artifactory in another job:

  1. Select Generic Artifactory Integration
  2. Use Resolved Artifacts as ${repokey}:**/${component}*.jar;status=${STATUS}@${PUBLISH_BUILDJOB}#LATEST=>${targetDir}

How to retrieve the LoaderException property?

Using Quick Watch in Visual Studio you can access the LoaderExceptions from ViewDetails of the thrown exception like this:

($exception).LoaderExceptions

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

An error has occured. Please see log file - eclipse juno

In my case I didn't want to remove eclipse because in corporate world we can't control everything. Also deleting some files from workspace .matadata could not help. So below hack that I found with trial and error worked for me perfectly :

Go to this path: C:\....\eclipse-Luna\configuration\org.eclipse.core.runtime\

now delete .manager completely.

Start eclipse again and woilaa.. it will run normally.

[In my case, I use eclipse luna. I once abruptly closed the PC when eclipse was open. Then eclipse was not able to start on the next system restart. So keep in mind to close eclipse properly. :) ]

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables directly. You need to use the set of "non standard" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

Some products like Ant or Tomcat might come with a batch script that looks for the JAVA_OPTS environment variable, but it's not part of the Java runtime. If you are using one of those products, you may be able to set the variable like:

set JAVA_OPTS="-Xms128m -Xmx256m"  

You can also take this approach with your own command line like:

set JAVA_OPTS="-Xms128m -Xmx256m"  
java ${JAVA_OPTS} MyClass

Use CSS to make a span not clickable

Using CSS you cannot, CSS will only change the appearance of the span. However you can do it without changing the structure of the div by adding an onclick handler to the span:

<html>
<head>
</head>
<body>
<div>
<a href="http://www.google.com">
  <span>title<br></span>
  <span onclick='return false;'>description<br></span>
  <span>some url</span>
</a>
</div>
</body>
</html>

You can then style it so that it looks un-clickable too:

<html>
<head>
     <style type='text/css'>
     a span.unclickable  { text-decoration: none; }
     a span.unclickable:hover { cursor: default; }
     </style>
</head>
<body>
<div>
<a href="http://www.google.com">
  <span>title<br></span>
  <span class='unclickable' onclick='return false;'>description<br></span>
  <span>some url</span>
</a>
</div>
</body>
</html>

Using jQuery to compare two arrays of Javascript objects

Try this

function check(c,d){
  var a = c, b = d,flg = 0;
  if(a.length == b.length) 
  { 
     for(var i=0;i<a.length;i++) 
           a[i] != b[i] ? flg++ : 0; 
  } 
  else  
  { 
     flg = 1; 
  } 
  return flg = 0;
}

AngularJS passing data to $http.get request

You can even simply add the parameters to the end of the url:

$http.get('path/to/script.php?param=hello').success(function(data) {
    alert(data);
});

Paired with script.php:

<? var_dump($_GET); ?>

Resulting in the following javascript alert:

array(1) {  
    ["param"]=>  
    string(4) "hello"
}

pandas: filter rows of DataFrame with operator chaining

This solution is more hackish in terms of implementation, but I find it much cleaner in terms of usage, and it is certainly more general than the others proposed.

https://github.com/toobaz/generic_utils/blob/master/generic_utils/pandas/where.py

You don't need to download the entire repo: saving the file and doing

from where import where as W

should suffice. Then you use it like this:

df = pd.DataFrame([[1, 2, True],
                   [3, 4, False], 
                   [5, 7, True]],
                  index=range(3), columns=['a', 'b', 'c'])
# On specific column:
print(df.loc[W['a'] > 2])
print(df.loc[-W['a'] == W['b']])
print(df.loc[~W['c']])
# On entire - or subset of a - DataFrame:
print(df.loc[W.sum(axis=1) > 3])
print(df.loc[W[['a', 'b']].diff(axis=1)['b'] > 1])

A slightly less stupid usage example:

data = pd.read_csv('ugly_db.csv').loc[~(W == '$null$').any(axis=1)]

By the way: even in the case in which you are just using boolean cols,

df.loc[W['cond1']].loc[W['cond2']]

can be much more efficient than

df.loc[W['cond1'] & W['cond2']]

because it evaluates cond2 only where cond1 is True.

DISCLAIMER: I first gave this answer elsewhere because I hadn't seen this.

How do I change the hover over color for a hover over table in Bootstrap?

.table-hover tbody tr:hover td {
    background: #ffffff;
}

Java ResultSet how to check if there are any results

Best to use ResultSet.next() along with the do {...} while() syntax for this.

The "check for any results" call ResultSet.next() moves the cursor to the first row, so use the do {...} while() syntax to process that row while continuing to process remaining rows returned by the loop.

This way you get to check for any results, while at the same time also processing any results returned.

if(resultSet.next()) { // Checks for any results and moves cursor to first row,
    do { // Use 'do...while' to process the first row, while continuing to process remaining rows

    } while (resultSet.next());
}

REST API using POST instead of GET

POST is valid to use instead of GET if you have specific reasons for doing so and process it properly. I understand it's not specifically RESTy, but if you have a bunch of spaces and ampersands and slashes and so on in your data [eg a product model like Amazon] then trying to encode and decode this can be more trouble than it's worth instead of just pre-jsonifying it. Make sure though that you return the proper response codes and heavily comment what you're doing because it's not a typical use case of POST.

Why is lock(this) {...} bad?

There's also some good discussion about this here: Is this the proper use of a mutex?

What is the equivalent of Java's final in C#?

As mentioned, sealed is an equivalent of final for methods and classes.

As for the rest, it is complicated.

  • For static final fields, static readonly is the closest thing possible. It allows you to initialize the static field in a static constructor, which is fairly similar to static initializer in Java. This applies both to constants (primitives and immutable objects) and constant references to mutable objects.

    The const modifier is fairly similar for constants, but you can't set them in a static constructor.

  • On a field that shouldn't be reassigned once it leaves the constructor, readonly can be used. It is not equal though - final requires exactly one assignment even in constructor or initializer.

  • There is no C# equivalent for a final local variable that I know of. If you are wondering why would anyone need it: You can declare a variable prior to an if-else, switch-case or so. By declaring it final, you enforce that it is assigned at most once.

    Java local variables in general are required to be assigned at least once before they are read. Unless the branch jumps out before value read, a final variable is assigned exactly once. All of this is checked compile-time. This requires well behaved code with less margin for an error.

Summed up, C# has no direct equivalent of final. While Java lacks some nice features of C#, it is refreshing for me as mostly a Java programmer to see where C# fails to deliver an equivalent.

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

How to do select from where x is equal to multiple values?

You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)

Switch case in C# - a constant value is expected

You can only match to constants in switch statements.


Example:

switch (variable1)
{
    case 1: // A hard-coded value
        // Code
        break;
    default:
        // Code
        break;
}

Successful!


switch (variable1)
{
    case variable2:
        // Code
        break;
    default:
        // Code
        break;
}

CS0150 A constant value is expected.

What is the difference between `Enum.name()` and `Enum.toString()`?

The main difference between name() and toString() is that name() is a final method, so it cannot be overridden. The toString() method returns the same value that name() does by default, but toString() can be overridden by subclasses of Enum.

Therefore, if you need the name of the field itself, use name(). If you need a string representation of the value of the field, use toString().

For instance:

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;

    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }
}

In this example, WeekDay.MONDAY.name() returns "MONDAY", and WeekDay.MONDAY.toString() returns "Monday".

WeekDay.valueOf(WeekDay.MONDAY.name()) returns WeekDay.MONDAY, but WeekDay.valueOf(WeekDay.MONDAY.toString()) throws an IllegalArgumentException.

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

Can anyone explain what JSONP is, in layman terms?

JSONP is a way of getting around the browser's same-origin policy. How? Like this:

enter image description here

The goal here is to make a request to otherdomain.com and alert the name in the response. Normally we'd make an AJAX request:

$.get('otherdomain.com', function (response) {
  var name = response.name;
  alert(name);
});

However, since the request is going out to a different domain, it won't work.

We can make the request using a <script> tag though. Both <script src="otherdomain.com"></script> and $.get('otherdomain.com') will result in the same request being made:

GET otherdomain.com

Q: But if we use the <script> tag, how could we access the response? We need to access it if we want to alert it.

A: Uh, we can't. But here's what we could do - define a function that uses the response, and then tell the server to respond with JavaScript that calls our function with the response as its argument.

Q: But what if the server won't do this for us, and is only willing to return JSON to us?

A: Then we won't be able to use it. JSONP requires the server to cooperate.

Q: Having to use a <script> tag is ugly.

A: Libraries like jQuery make it nicer. Ex:

$.ajax({
    url: "http://otherdomain.com",
    jsonp: "callback",
    dataType: "jsonp",
    success: function( response ) {
        console.log( response );
    }
});

It works by dynamically creating the <script> tag DOM element.

Q: <script> tags only make GET requests - what if we want to make a POST request?

A: Then JSONP won't work for us.

Q: That's ok, I just want to make a GET request. JSONP is awesome and I'm going to go use it - thanks!

A: Actually, it isn't that awesome. It's really just a hack. And it isn't the safest thing to use. Now that CORS is available, you should use it whenever possible.

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

Returning from a void function

The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.

I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?

I would be severly annoyed by such a pointless extra return statement at the end of a void function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

Disabled href tag

You can use:

<a href="/" onclick="return false;">123n</a>

Reading a key from the Web.Config using ConfigurationManager

There will be two Web.config files. I think you may have confused with those two files.

Check this image:

click this link and check this image

In this image you can see two Web.config files. You should add your constants to the one which is in the project folder not in the views folder

Hope this may help you

Python: TypeError: object of type 'NoneType' has no len()

I was faces this issue but after change object into str, problem solved. str(fname).isalpha():

javascript /jQuery - For Loop

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

HTTP status code for update and delete?

RFC 2616 describes which status codes to use.

And no, it's not always 200.

How can I remove a style added with .css() function?

Try

document.body.style=''

_x000D_
_x000D_
$("body").css("background-color", 'red');

function clean() {
  document.body.style=''
}
_x000D_
body { background-color: yellow; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="clean()">Remove style</button>
_x000D_
_x000D_
_x000D_

No tests found with test runner 'JUnit 4'

Very late but what solved the problem for me was that my test method names all started with captial letters: "public void Test". Making the t lower case worked.

Send a base64 image in HTML email

An alternative approach may be to embed images in the email using the cid method. (Basically including the image as an attachment, and then embedding it). In my experience, this approach seems to be well supported these days.

enter image description here

Source: https://www.campaignmonitor.com/blog/how-to/2008/08/embedding-images-revisited/

What is the difference between background and background-color

background is shorthand property for the following:

 - background-color
 - background-image
 - background-repeat
 - background-attachment
 - background-position

You can detailed info on every property here

Properties order

In most of browser implementation (i think maybe older browser could present issues) the order of the properties does not matter, except for:

  • background-origin and background-clip: when both of this properties are present, the first one refer to -origin and the second to -clip.

    Example:

    background: content-box green padding-box;
    

    Is equivalent to:

    background-origin: content-box;
    background-color: green;
    background-clip: padding-box;
    
  • background-size must always follow background-position and the properties must be separated by /

  • if background-position is composed by two numbers, the first one is the horizontal value and the second the vertical value.

Responsive design with media query : screen size?

Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience

When you design your responsive website you should consider the size of the screen and not the device type. The media queries helps you do that.

If you want to style your site per device, you can use the user agent value, but this is not recommended since you'll have to work hard to maintain your code for new devices, new browsers, browsers versions etc while when using the screen size, all of this does not matter.

You can see some standard resolutions in this link.

BUT, in my opinion, you should first design your website layout, and only then adjust it with media queries to fit possible screen sizes.

Why? As I said before, the screen resolutions variety is big and if you'll design a mobile version that is targeted to 320px your site won't be optimized to 350px screens or 400px screens.

TIPS

  1. When designing a responsive page, open it in your desktop browser and change the width of the browser to see how the width of the screen affects your layout and style.
  2. Use percentage instead of pixels, it will make your work easier.

Example

I have a table with 5 columns. The data looks good when the screen size is bigger than 600px so I add a breakpoint at 600px and hides 1 less important column when the screen size is smaller. Devices with big screens such as desktops and tablets will display all the data, while mobile phones with small screens will display part of the data.


State of mind

Not directly related to the question but important aspect in responsive design. Responsive design also relate to the fact that the user have a different state of mind when using a mobile phone or a desktop. For example, when you open your bank's site in the evening and check your stocks you want as much data on the screen. When you open the same page in the your lunch break your probably want to see few important details and not all the graphs of last year.

How do you display a Toast from a background thread on Android?

This is similar to other answers, however updated for new available apis and much cleaner. Also, does not assume you're in an Activity Context.

public class MyService extends AnyContextSubclass {

    public void postToastMessage(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

On postback, how can I check which control cause postback in Page_Init event

If you need to check which control caused the postback, then you could just directly compare ["__EVENTTARGET"] to the control you are interested in:

if (specialControl.UniqueID == Page.Request.Params["__EVENTTARGET"])
{
    /*do special stuff*/
}

This assumes you're just going to be comparing the result from any GetPostBackControl(...) extension method anyway. It may not handle EVERY situation, but if it works it is simpler. Plus, you won't scour the page looking for a control you didn't care about to begin with.

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

For me it was a problem with firebase package.

Only add "@firebase/database": "0.2.1", for your package.json, reinstall node_modules and works.

MySQL 'create schema' and 'create database' - Is there any difference

Database is a collection of schemas and schema is a collection of tables. But in MySQL they use it the same way.

How can you profile a Python script?

A nice profiling module is the line_profiler (called using the script kernprof.py). It can be downloaded here.

My understanding is that cProfile only gives information about total time spent in each function. So individual lines of code are not timed. This is an issue in scientific computing since often one single line can take a lot of time. Also, as I remember, cProfile didn't catch the time I was spending in say numpy.dot.

In Bash, how do I add a string after each line in a file?

I prefer echo. using pure bash:

cat file | while read line; do echo ${line}$string; done

Fixed size div?

You can set the height and width of your divs with css.

<style type="text/css">
.box {
     height: 150px;
     width: 150px;
}
</style> 

Is this what you're looking for?

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

I faced this issue once and was able to resolve it by fixing of my /etc/hosts. It just was unable to resolve localhost name... Details are here: http://itvictories.com/node/6

In fact, there is 99% that error related to /etc/hosts file

X server just unable to resolve localhost and all consequent actions just fails.

Please be sure that you have a record like

127.0.0.1 localhost

in your /etc/hosts file.

How to redirect to a different domain using NGINX?

server_name supports suffix matches using .mydomain.com syntax:

server {
  server_name .mydomain.com;
  rewrite ^ http://www.adifferentdomain.com$request_uri? permanent;
}

or on any version 0.9.1 or higher:

server {
  server_name .mydomain.com;
  return 301 http://www.adifferentdomain.com$request_uri;
}

Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

enter image description here

Bigger Glyphicons

The .btn-lg class has the following CSS in Bootstrap 3 (link):

.btn-lg {
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 6px;
}

If you apply the same font-size and line-height to your span (either .glyphicon-link or a newly created .glyphicons-lg if you're going to use this effect in more than one instance), you'll get a Glyphicon the same size as the large button.

How do I check if a string is valid JSON in Python?

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

Eclipse reports rendering library more recent than ADT plug-in

Am i change API version 17, 19, 21, & 23 in xml layoutside

&&

Updated Android Development Tools 23.0.7 but still can't render layout proper so am i updated Android DDMS 23.0.7 it's works perfect..!!!

Check if certain value is contained in a dataframe column in pandas

I think you need str.contains, if you need rows where values of column date contains string 07311954:

print df[df['date'].astype(str).str.contains('07311954')]

Or if type of date column is string:

print df[df['date'].str.contains('07311954')]

If you want check last 4 digits for string 1954 in column date:

print df[df['date'].astype(str).str[-4:].str.contains('1954')]

Sample:

print df['date']
0    8152007
1    9262007
2    7311954
3    2252011
4    2012011
5    2012011
6    2222011
7    2282011
Name: date, dtype: int64

print df['date'].astype(str).str[-4:].str.contains('1954')
0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
Name: date, dtype: bool

print df[df['date'].astype(str).str[-4:].str.contains('1954')]
     cmte_id trans_typ entity_typ state  employer  occupation     date  \
2  C00119040       24K        CCM    MD       NaN         NaN  7311954   

   amount     fec_id    cand_id  
2    1000  C00140715  H2MD05155  

Find mouse position relative to element

Original answer said to put it in an iframe. The better solution is to use the events offsetX and offsetY on a canvas that has the padding set to 0px.

<html>
<body>
<script>

var main=document.createElement('canvas');
main.width="200";
main.height="300";
main.style="padding:0px;margin:30px;border:thick dashed red";
document.body.appendChild(main);

// adding event listener

main.addEventListener('mousemove',function(e){
    var ctx=e.target.getContext('2d');
    var c=Math.floor(Math.random()*0xFFFFFF);
    c=c.toString(16); for(;c.length<6;) c='0'+c;
    ctx.strokeStyle='#'+c;
    ctx.beginPath();
    ctx.arc(e.offsetX,e.offsetY,3,0,2*Math.PI);
    ctx.stroke();
    e.target.title=e.offsetX+' '+e.offsetY;
    });

// it worked! move mouse over window

</script>
</body>
</html>

ListView with OnItemClickListener

1) Check if you are using OnItemClickListener or OnClickListener (which is not supported for ListView)
Documentation Android Developers ListView

2) Check if you added Listener to your ListView properly. It's hooked on ListView not on ListAdapter!

ListView.setOnItemClickListener(listener);

3) If you need to use OnClickListener, check if you do use DialogInterface.OnClickListener or View.OnClickListener (they can be easily exchanged if not validated or if using both of them)

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

This happens when your result is not a result (but a "false" instead). You should change this line

$sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';

to this:

$sql = "SELECT * FROM $usertable WHERE PartNumber = $partid";

because the " can interprete $variables while ' cannot.

Works fine with integers (numbers), for strings you need to put the $variable in single quotes, like

$sql = "SELECT * FROM $usertable WHERE PartNumber = '$partid' ";

If you want / have to work with single quotes, then php CAN NOT interprete the variables, you will have to do it like this:

 $sql = 'SELECT * FROM '.$usertable.' WHERE string_column = "'.$string.'" AND integer_column = '.$number.';

Perform commands over ssh with Python

Have a look at spurplus, a wrapper we developed around spur that provides type annotations and some minor gimmicks (reconnecting SFTP, md5 etc.): https://pypi.org/project/spurplus/

Bind class toggle to window scroll event

Directives are not "inside the angular world" as they say. So you have to use apply to get back into it when changing stuff

JS regex: replace all digits in string

You need to add the "global" flag to your regex:

s.replace(new RegExp("[0-9]", "g"), "X")

or, perhaps prettier, using the built-in literal regexp syntax:

.replace(/[0-9]/g, "X")

Create a folder if it doesn't already exist

Faster way to create folder:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

What's the maximum value for an int in PHP?

It depends on your OS, but 2147483647 is the usual value, according to the manual.

Does Go have "if x in" construct similar to Python?

There is no built-in operator to do it in Go. You need to iterate over the array. You can write your own function to do it, like this:

func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}

If you want to be able to check for membership without iterating over the whole list, you need to use a map instead of an array or slice, like this:

visitedURL := map[string]bool {
    "http://www.google.com": true,
    "https://paypal.com": true,
}
if visitedURL[thisSite] {
    fmt.Println("Already been here.")
}

Allow only pdf, doc, docx format for file upload?

Below code worked for me:

<input #fileInput type="file" id="avatar" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />

application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx

Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

I am just adding this answer for an awkward situation from DB provider.

what happened in our case is the primary and secondary db shifted reversely (primary to secondary and vice versa) and we are getting the same error.

so please check in the configuration settings for database status which may help you.

How is length implemented in Java Arrays?

If you have an array of a known type or is a subclass of Object[] you can cast the array first.

Object array = new ????[n];
Object[] array2 = (Object[]) array;
System.out.println(array2.length);

or

Object array = new char[n];
char[] array2 = (char[]) array;
System.out.println(array2.length);

However if you have no idea what type of array it is you can use Array.getLength(Object);

System.out.println(Array.getLength(new boolean[4]);
System.out.println(Array.getLength(new int[5]);
System.out.println(Array.getLength(new String[6]);

Plotting a 2D heatmap with Matplotlib

The imshow() function with parameters interpolation='nearest' and cmap='hot' should do what you want.

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()

enter image description here

Email address validation using ASP.NET MVC data type attributes

You need to use RegularExpression Attribute, something like this:

[RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail is not valid")]

And don't delete [Required] because [RegularExpression] doesn't affect empty fields.

Operation Not Permitted when on root - El Capitan (rootless disabled)

Nvm. For anyone else having this problem you need to reboot your mac and press ?+R when booting up. Then go into Utilities > Terminal and type the following commands:

csrutil disable
reboot 

This is a result of System Integrity Protection. More info here.

EDIT

If you know what you are doing and are used to running Linux, you should use the above solution as many of the SIP restrictions are a complete pain in the ass.

However, if you are a tinkerer/noob/"poweruser" and don't know what you are doing, this can be very dangerous and you are better off using the answer below.

How to check queue length in Python

len(queue) should give you the result, 3 in this case.

Specifically, len(object) function will call object.__len__ method [reference link]. And the object in this case is deque, which implements __len__ method (you can see it by dir(deque)).


queue= deque([])   #is this length 0 queue?

Yes it will be 0 for empty deque.

No == operator found while comparing structs in C++

By default structs do not have a == operator. You'll have to write your own implementation:

bool MyStruct1::operator==(const MyStruct1 &other) const {
    ...  // Compare the values, and return a bool result.
  }

How to pass password to scp?

Here is an example of how you do it with expect tool:

sub copyover {
    $scp = Expect->spawn("/usr/bin/scp ${srcpath}/$file $who:${destpath}/$file");
    $scp->expect(30,"ssword: ") || die "Never got password prompt from $dest:$!\n";
    print $scp 'password' . "\n";
    $scp->expect(30,"-re",'$\s') || die "Never got prompt from parent system:$!\n";
    $scp->soft_close();
    return;
}

Mockito, JUnit and Spring

Your question seems to be asking about which of the three examples you have given is the preferred approach.

Example 1 using the Reflection TestUtils is not a good approach for Unit testing. You really don't want to be loading the spring context at all for a unit test. Just mock and inject what is required as shown by your other examples.

You do want to load the spring context if you want to do some Integration testing, however I would prefer using @RunWith(SpringJUnit4ClassRunner.class) to perform the loading of the context along with @Autowired if you need access to its' beans explicitly.

Example 2 is a valid approach and the use of @RunWith(MockitoJUnitRunner.class) will remove the need to specify a @Before method and an explicit call to MockitoAnnotations.initMocks(this);

Example 3 is another valid approach that doesn't use @RunWith(...). You haven't instantiated your class under test HelloFacadeImpl explicitly, but you could have done the same with Example 2.

My suggestion is to use Example 2 for your unit testing as it reduces the code clutter. You can fall back to the more verbose configuration if and when you're forced to do so.

SSH library for Java

There is a brand new version of Jsch up on github: https://github.com/vngx/vngx-jsch Some of the improvements include: comprehensive javadoc, enhanced performance, improved exception handling, and better RFC spec adherence. If you wish to contribute in any way please open an issue or send a pull request.

How to write and read java serialized objects into a file

As others suggested, you can serialize and deserialize the whole list at once, which is simpler and seems to comply perfectly with what you intend to do.

In that case the serialization code becomes

ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
    fout = new FileOutputStream("G:\\address.ser", true);
    oos = new ObjectOutputStream(fout);
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    if(oos != null){
        oos.close();
    } 
}

And deserialization becomes (assuming that myClassList is a list and hoping you will use generics):

ObjectInputStream objectinputstream = null;
try {
    FileInputStream streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    List<MyClass> readCase = (List<MyClass>) objectinputstream.readObject();
    recordList.add(readCase);
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

You can also deserialize several objects from a file, as you intended to:

ObjectInputStream objectinputstream = null;
try {
    streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    MyClass readCase = null;
    do {
        readCase = (MyClass) objectinputstream.readObject();
        if(readCase != null){
            recordList.add(readCase);
        } 
    } while (readCase != null)        
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

Please do not forget to close stream objects in a finally clause (note: it can throw exception).

EDIT

As suggested in the comments, it should be preferable to use try with resources and the code should get quite simpler.

Here is the list serialization :

try(
    FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
){
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
}

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

Thanks for John Doe's solution that helped a lot. Mine is very similar with some difference, using TempVars

Instead of :

      strSQL = "SELECT * FROM Table1 WHERE Name = Forms!Table!Control;"

I used:

      strSQL = "SELECT * FROM Query1"  , Query1 being common for other usage

Query1 as:

 "Select Field1, Field2 from Table1 where Id= [TempVars]![MyVar]

And similarly, removing [TempVars]![MyVar] from view solved the problem.

<SELECT multiple> - how to allow only one item selected?

You want only one option by default, but the user can select multiple options by pressing the CTRL key. This is (already) exactly how the SELECT multiple is meant to behave.

See this: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple

Can you please clarify your question?

ReferenceError: fetch is not defined

The fetch API is not implemented in Node.

You need to use an external module for that, like node-fetch.

Install it in your Node application like this

npm i node-fetch --save

then put the line below at the top of the files where you are using the fetch API:

const fetch = require("node-fetch");

How to use `subprocess` command with pipes

To use a pipe with the subprocess module, you have to pass shell=True.

However, this isn't really advisable for various reasons, not least of which is security. Instead, create the ps and grep processes separately, and pipe the output from one into the other, like so:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

In your particular case, however, the simple solution is to call subprocess.check_output(('ps', '-A')) and then str.find on the output.

Converting HTML files to PDF

Is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a PDF-Printer tool automatically?

This is how ActivePDF works, which is good means that you know what you'll get, and it actually has reasonable styling support.

It is also one of the few packages I found (when looking a few years back) that actually supports the various page-break CSS commands.


Unfortunately, the ActivePDF software is very frustrating - since it has to launch the IE browser in the background for conversions it can be quite slow, and it is not particularly stable either.

There is a new version currently in Beta which is supposed to be much better, but I've not actually had a chance to try it out, so don't know how much of an improvement it is.

How can I get the browser's scrollbar sizes?

This life-hack decision will give you opportunity to find browser scrollY width (vanilla JavaScript). Using this example you can get scrollY width on any element including those elements that shouldn't have to have scroll according to your current design conception,:

getComputedScrollYWidth     (el)  {

  let displayCSSValue  ; // CSS value
  let overflowYCSSValue; // CSS value

  // SAVE current original STYLES values
  {
    displayCSSValue   = el.style.display;
    overflowYCSSValue = el.style.overflowY;
  }

  // SET TEMPORALLY styles values
  {
    el.style.display   = 'block';
    el.style.overflowY = 'scroll';
  }

  // SAVE SCROLL WIDTH of the current browser.
  const scrollWidth = el.offsetWidth - el.clientWidth;

  // REPLACE temporally STYLES values by original
  {
    el.style.display   = displayCSSValue;
    el.style.overflowY = overflowYCSSValue;
  }

  return scrollWidth;
}

Detecting IE11 using CSS Capability/Feature Detection

Use the following properties:

  • !!window.MSInputMethodContext
  • !!document.msFullscreenEnabled

How do I execute external program within C code in linux with arguments?

In C

#include <stdlib.h>

system("./foo 1 2 3");

In C++

#include <cstdlib>

std::system("./foo 1 2 3");

Then open and read the file as usual.

Python/Json:Expecting property name enclosed in double quotes

import ast

inpt = {'http://example.org/about': {'http://purl.org/dc/terms/title':
                                     [{'type': 'literal', 'value': "Anna's Homepage"}]}}

json_data = ast.literal_eval(json.dumps(inpt))

print(json_data)

this will solve the problem.

Visual Studio Code Tab Key does not insert a tab

Not sure what operating system you're on, but there was a known issue with the tab key on one of the more recent releases of VS Code for Mac OS X. The bug has been fixed in the latest release (0.10.9).

On Mac OS X, you can check for the latest update by opening VS Code and then going to [Code > Check for Updates].

Sources and more information:

How can I edit a view using phpMyAdmin 3.2.4?

try running SHOW CREATE VIEW my_view_name in the sql portion of phpmyadmin and you will have a better idea of what is inside the view

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

If you're running Windows 10 Creators Update (1703) and are comfortable navigating around a Unix terminal, you could potentially achieve this using the native Feature Bash on Ubuntu on Windows (aka Bash/WSL)

This was originally introduced on the launch of Build 2016 but many additions and bug fixes were addressed at the Creators update but please be warned this is still in Beta.

To enable simply navigate to Control Panel\All Control Panel Items\Programs and Features\Turn Windows features on or off

Then select the Windows Subsystem for Linux (Beta) as below Bash on Windows Feature

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

It appears that my max ports weren't configured correctly. I ran the following code and it worked...

echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

What this command does is to increase the number of watches allowed for a single user. By the default the number can be low (8192 for example). When nodemon tries to watch large numbers of directories for changes it has to create several watches, which can surpass that limit.

You could also solve this problem by:

sudo sysctl fs.inotify.max_user_watches=582222 && sudo sysctl -p

But the way it was written first will make this change permanent.

How to print like printf in Python3?

Simple printf() function from O'Reilly's Python Cookbook.

import sys
def printf(format, *args):
    sys.stdout.write(format % args)

Example output:

i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

How do I sort strings alphabetically while accounting for value when a string is numeric?

public class Test
{
    public void TestMethod()
    {
        List<string> buyersList = new List<string>() { "5", "10", "1", "str", "3", "string" };
        List<string> soretedBuyersList = null;

        soretedBuyersList = new List<string>(SortedList(buyersList));
    }

    public List<string> SortedList(List<string> unsoredList)
    {
        return unsoredList.OrderBy(o => o, new SortNumericComparer()).ToList();
    }
}

   public class SortNumericComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        int xInt = 0;
        int yInt = 0;
        int result = -1;

        if (!int.TryParse(x, out xInt))
        {
            result = 1;
        }

        if(int.TryParse(y, out yInt))
        {
            if(result == -1)
            {
                result = xInt - yInt;
            }
        }
        else if(result == 1)
        {
             result = string.Compare(x, y, true);
        }

        return result;
    }
}

Find all packages installed with easy_install/pip?

For those who don't have pip installed, I found this quick script on github (works with Python 2.7.13):

import pkg_resources
distros = pkg_resources.AvailableDistributions()
for key in distros:
  print distros[key]

Uncaught TypeError: Cannot read property 'value' of null

HTML : Pass the whole body inside on click

div class="calculate" id="calculate">
            <div class="button" id="button" onclick="myCode(this.body)"> CALCULATE ! </div>
        </div>

Then write the JavaScript code inside the function "myCode()"

function myCode()
{
    var bill = document.getElementById("currency").value ;

    var people_count = document.getElementById("number1").value;
    var select_value = document.getElementById("select").value;

    var calculate = document.getElementById("calculate");

    calculate.addEventListener("click" ,function()
    {
        console.log(bill);
        console.log(people_count);
        console.log(select_value);
    });
}

you will get your values I am using visual studio code editor

Set equal width of columns in table layout in Android

Try this.

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

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

How can I generate Unix timestamps?

in Haskell

import Data.Time.Clock.POSIX

main :: IO ()
main = print . floor =<< getPOSIXTime

in Go

import "time"
t := time.Unix()

in C

time(); // in time.h POSIX

// for Windows time.h
#define UNIXTIME(result)   time_t localtime; time(&localtime); struct tm* utctime = gmtime(&localtime); result = mktime(utctime);

in Swift

NSDate().timeIntervalSince1970 // or Date().timeIntervalSince1970

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

Change

die (mysqli_error()); 

to

die('Error: ' . mysqli_error($myConnection));

in the query

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

Modulo operator in Python

you should use fmod(a,b)

While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff.

For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100.

Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.

where x = a%b is used for integer modulo

How to save S3 object to a file using boto3

boto3 now has a nicer interface than the client:

resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)

This by itself isn't tremendously better than the client in the accepted answer (although the docs say that it does a better job retrying uploads and downloads on failure) but considering that resources are generally more ergonomic (for example, the s3 bucket and object resources are nicer than the client methods) this does allow you to stay at the resource layer without having to drop down.

Resources generally can be created in the same way as clients, and they take all or most of the same arguments and just forward them to their internal clients.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

You will get the following error message too when you provide undefined or so to an operator which expects an Observable, eg. takeUntil.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable 

Resize image proportionally with CSS?

img{
    max-width:100%;
    object-fit: scale-down;
}

works for me. It scales down larger images to fit in the box, but leaves smaller images their original size.

How do I uniquely identify computers visiting my web site?

There is only a small amount of information that you can get via an HTTP connection.

  1. IP - But as others have said, this is not fixed for many, if not most Internet users due to their ISP's dynamic allocation policies.

  2. Useragent String - Nearly all browsers send what kind of browser they are with every request. However, this can be set by the user in many browsers today.

  3. Collection of request fields - There are other fields sent with each request, such as supported encodings, etc. These, if used in the aggregate can help to ID a user's machine, but again are browser dependent and can be changed.

  4. Cookies - Setting a cookie is another way to identify a machine, or more specifically a browser on a machine, but as others have said, these can be deleted, or turned off by the users, and are only applicable on a browser, not a machine.

So, the correct response is that you cannot achieve what you would live via the HTTP over IP protocols alone. However, using a combination of cookies, as well as IP, and the fields in the HTTP request, you have a good chance at guessing, sort of, what machine it is. Users tend to use only one browser, and often from one machine, so this may be fairly relieable, but this will vary depending on the audience...techies are more likely to mess with this stuff, and use more machines/browsers. Additionally, this could even be coupled with some attempt to geo-locate the IP, and use that data as well. But in any case, there is no solution that will be correct all of the time.

Content-Disposition:What are the differences between "inline" and "attachment"?

Because when I use one or another I get a window prompt asking me to download the file for both of them.

This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.

If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.

Why call super() in a constructor?

A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.

When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.

Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.

As a side note, some say that it's generally best to make that call manually for reasons of clarity.

File uploading with Express 4.0: req.files undefined

Please use below code

app.use(fileUpload());

How to convert DataTable to class Object?

It is Vb.Net version:

Public Class Test
Public Property id As Integer
Public Property name As String
Public Property address As String
Public Property createdDate As Date

End Class

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim x As Date = Now

    Debug.WriteLine("Begin: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)

    Dim dt As New DataTable
    dt.Columns.Add("id")
    dt.Columns.Add("name")
    dt.Columns.Add("address")
    dt.Columns.Add("createdDate")

    For i As Integer = 0 To 100000
        dt.Rows.Add(i, "name - " & i, "address - " & i, DateAdd(DateInterval.Second, i, Now))
    Next

    Debug.WriteLine("Datatable created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)


    Dim items As IList(Of Test) = dt.AsEnumerable().[Select](Function(row) New _
            Test With {
                        .id = row.Field(Of String)("id"),
                        .name = row.Field(Of String)("name"),
                        .address = row.Field(Of String)("address"),
                        .createdDate = row.Field(Of String)("createdDate")
                       }).ToList()

    Debug.WriteLine("List created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)

    Debug.WriteLine("Complated")

End Sub

Can't import org.apache.http.HttpResponse in Android Studio

HttpClient is deprecated in sdk 23.

You have to move on URLConnection or down sdk to 22

Still you need HttpClient with update gradle sdk 23

You have to add the dependencies of HttpClient in app/gradle as

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.0.1'

    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    ...
}

How to include !important in jquery

Apparently it's possible to do this in jQuery:

$("#tabs").css("cssText", "height: 650px !important;");

Src: http://bugs.jquery.com/ticket/2066

Unresolved Import Issues with PyDev and Eclipse

project-->properties-->pydev-pythonpath-->external libraries --> add source folder, add the PARENT FOLDER of the project. Then restart eclipse.

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

What is the difference between properties and attributes in HTML?

When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.

For instance, this HTML element:

<input type="text" value="Name:">

has 2 attributes (type and value).

Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.

For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes property of that object.

When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:

<input id="the-input" type="text" value="Name:">

the corresponding DOM node will have id,type, and value properties (among others):

  • The id property is a reflected property for the id attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. id is a pure reflected property, it doesn't modify or limit the value.

  • The type property is a reflected property for the type attribute: Getting the property reads the attribute value, and setting the property writes the attribute value. type isn't a pure reflected property because it's limited to known values (e.g., the valid types of an input). If you had <input type="foo">, then theInput.getAttribute("type") gives you "foo" but theInput.type gives you "text".

  • In contrast, the value property doesn't reflect the value attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs "John" into the input box, then:

    theInput.value // returns "John"
    

    whereas:

    theInput.getAttribute('value') // returns "Name:"
    

    The value property reflects the current text-content inside the input box, whereas the value attribute contains the initial text-content of the value attribute from the HTML source code.

    So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the defaultValue property, which is a pure reflection of the value attribute:

    theInput.value                 // returns "John"
    theInput.getAttribute('value') // returns "Name:"
    theInput.defaultValue          // returns "Name:"
    

There are several properties that directly reflect their attribute (rel, id), some are direct reflections with slightly-different names (htmlFor reflects the for attribute, className reflects the class attribute), many that reflect their attribute but with restrictions/modifications (src, href, disabled, multiple), and so on. The spec covers the various kinds of reflection.

How to list AD group membership for AD users using input list?

First: As it currently stands, the $User variable does not have a .Users property. In your code, $User simply represents one line (the "current" line in the foreach loop) from the text file.

$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof

Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:

  1. Query forest for list of domains
  2. Call Get-ADUser for each domain (you may have to specify alternate credentials via the -Credential parameter

Thirdly, to get a list of groups that a user is a member of:

$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';

# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins

Fourthly: To get the final, desired string format, simply add the $User.Name, a semicolon, and the $GroupMembership string together:

$User.SamAccountName + ';' + $GroupMembership;

How to remove all callbacks from a Handler?

Define a new handler and runnable:

private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Do what ever you want
        }
    };

Call post delayed:

handler.postDelayed(runnable, sleep_time);

Remove your callback from your handler:

handler.removeCallbacks(runnable);

File tree view in Notepad++

If you want treeview like explorer, you can go with LightExplorer

Light Explorer in Notepad++

Download dll from here and paste it inside plugins folder in notepad++ installed directory. Restart notepad++ and then in menubar goto Plugins ->Light Explorer -> Light Explorer

Double value to round up in Java

If you do not want to use DecimalFormat (e.g. due to its efficiency) and you want a general solution, you could also try this method that uses scaled rounding:

public static double roundToDigits(double value, int digitCount) {
    if (digitCount < 0)
        throw new IllegalArgumentException("Digit count must be positive for rounding!");

    double factor = Math.pow(10, digitCount);
    return (double)(Math.round(value * factor)) / factor;
}

Difference between abstract class and interface in Python

For completeness, we should mention PEP3119 where ABC was introduced and compared with interfaces, and original Talin's comment.

The abstract class is not perfect interface:

  • belongs to the inheritance hierarchy
  • is mutable

But if you consider writing it your own way:

def some_function(self):
     raise NotImplementedError()

interface = type(
    'your_interface', (object,),
    {'extra_func': some_function,
     '__slots__': ['extra_func', ...]
     ...
     '__instancecheck__': your_instance_checker,
     '__subclasscheck__': your_subclass_checker
     ...
    }
)

ok, rather as a class
or as a metaclass
and fighting with python to achieve the immutable object
and doing refactoring
...

you'll quite fast realize that you're inventing the wheel to eventually achieve abc.ABCMeta

abc.ABCMeta was proposed as a useful addition of the missing interface functionality, and that's fair enough in a language like python.

Certainly, it was able to be enhanced better whilst writing version 3, and adding new syntax and immutable interface concept ...

Conclusion:

The abc.ABCMeta IS "pythonic" interface in python

How to _really_ programmatically change primary and accent color in Android Lollipop?

You cannot change the color of colorPrimary, but you can change the theme of your application by adding a new style with a different colorPrimary color

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>

<style name="AppTheme.NewTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorOne</item>
    <item name="colorPrimaryDark">@color/colorOneDark</item>
</style>

and inside the activity set theme

 setTheme(R.style.AppTheme_NewTheme);
 setContentView(R.layout.activity_main);

Failure [INSTALL_FAILED_INVALID_APK]

Uninstall the previous version if installed already and try again.It might help