Programs & Examples On #Gettext

Gettext is an internationalization and localization (i18n) library which is commonly used for writing multilingual programs. Its most popular implementation is that of the GNU project.

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

How to programmatically set style attribute in a view

First of all, you don't need to use a layout inflater to create a simple Button. You can just use:

button = new Button(context);

If you want to style the button you have 2 choices: the simplest one is to just specify all the elements in code, like many of the other answers suggest:

button.setTextColor(Color.RED);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

The other option is to define the style in XML, and apply it to the button. In the general case, you can use a ContextThemeWrapper for this:

ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
button = new Button(newContext);

To change the text-related attributes on a TextView (or its subclasses like Button) there is a special method:

button.setTextAppearance(R.style.MyTextStyle);

Or, if you need to support devices pre API-23 (Android 6.0)

button.setTextAppearance(context, R.style.MyTextStyle);

This method cannot be used to change all attributes; for example to change padding you need to use a ContextThemeWrapper. But for text color, size, etc. you can use setTextAppearance.

Defining a percentage width for a LinearLayout?

Google introduced new API called PercentRelativeLayout

Add compile dependency like

compile 'com.android.support:percent:22.2.0'

in that PercentRelativeLayout is what we can do percentagewise layout

Spring boot Security Disable security

You need to add this entry to application.properties to bypass Springboot Default Security

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

Then there won't be any authentication box. otrws, credentials are:- user and 99b962fa-1848-4201-ae67-580bdeae87e9 (password randomly generated)

Note: my springBootVersion = '1.5.14.RELEASE'

Differences between Ant and Maven

Maven also houses a large repository of commonly used open source projects. During the build Maven can download these dependencies for you (as well as your dependencies dependencies :)) to make this part of building a project a little more manageable.

jQuery check if Cookie exists, if not create it

I think the bulletproof way is:

if (typeof $.cookie('token') === 'undefined'){
 //no cookie
} else {
 //have cookie
}

Checking the type of a null, empty or undefined var always returns 'undefined'

Edit: You can get there even easier:

if (!!$.cookie('token')) {
 // have cookie
} else {
 // no cookie
}

!! will turn the falsy values to false. Bear in mind that this will turn 0 to false!

Execute JavaScript using Selenium WebDriver in C#

The shortest code

ChromeDriver drv = new ChromeDriver();

drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");

drv.ExecuteScript("return alert(document.title);");


Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

The below code may help you.

protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
    final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    numberFormat.setGroupingUsed(true);
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    return numberFormat.format(input);
}

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

Bootstrap 3: Text overlay on image

Is this what you're after?

http://jsfiddle.net/dCNXU/1/

I added :text-align:center to the div and image

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

Possible reasons for timeout when trying to access EC2 instance

This answer is for the silly folks (like me). Your EC2's public DNS might (will) change when it's restarted. If you don't realize this and attempt to SSH into your old public DNS, the connection will stall and time out. This may lead you to assume something is wrong with your EC2 or security group or... Nope, just SSH into the new DNS. And update your ~/.ssh/config file if you have to!

ORA-01652 Unable to extend temp segment by in tablespace

I encountered the same error message but don't have any access to the table like "dba_free_space" because I am not a dba. I use some previous answers to check available space and I still have a lot of space. However, after reducing the full table scan as many as possible. The problem is solved. My guess is that Oracle uses temp table to store the full table scan data. It the data size exceeds the limit, it will show the error. Hope this helps someone with the same issue

How do you change the text in the Titlebar in Windows Forms?

this.Text = "Your Text Here"

Place this under Initialize Component and it should change on form load.

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

The verified solution doesn't work for me, since my notebook is not in my sys.path. This works however;

import os,sys
sys.path.insert(1, os.path.join(os.getcwd()  , '..'))

How do I compare two hashes?

Rails is deprecating the diff method.

For a quick one-liner:

hash1.to_s == hash2.to_s

Full width layout with twitter bootstrap

*{
   margin:0
   padding:0
}

make sure your container's width:%100

How do I speed up the gwt compiler?

Although this entry is quite old and most of you probably already know, I think it's worth mention that GWT 2.x includes a new compile flag which speeds up compiles by skipping optimizations. You definitely shouldn't deploy JavaScript compiled that way, but it can be a time saver during non-production continuous builds.

Just include the flag: -draftCompile to your GWT compiler line.

Get connection string from App.config

string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;

What does on_delete do on Django models?

Here is answer for your question that says: why we use on_delete?

When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. This behavior can be overridden by specifying the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:

user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

The possible values for on_delete are found in django.db.models:

CASCADE: Cascade deletes; the default.

PROTECT: Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

SET_NULL: Set the ForeignKey null; this is only possible if null is True.

SET_DEFAULT: Set the ForeignKey to its default value; a default for the ForeignKey must be set.

Java code for getting current time

try this:

final String currentTime    = String.valueOf(System.currentTimeMillis());

Selenium Webdriver submit() vs click()

.Click() - Perform only click operation as like mouse click.

.Submit() - Perform Enter operation as like keyboard Enter event.

For Example. Consider a login page where it contains username and password and submit button.

On filling password if we want to login without clicking login button. we need to user .submit button on password where .click() operation does not work.[to login into application]

Brif.

driver.get("https:// anyURL"); 
driver.manage().window().maximize(); 
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
driver.findElement(By.id("txtUserId")).sendKeys("[email protected]"); 
WebElement text = driver.findElement(By.id("txtPassword")); text.sendKeys("password"); 
Thread.sleep(1000); 
text.click();   //This will not work - it will on perform click operation not submit operation
text.submit(); //This will perform submit operation has enter key 

When should I use a table variable vs temporary table in sql server?

Your question shows you have succumbed to some of the common misconceptions surrounding table variables and temporary tables.

I have written quite an extensive answer on the DBA site looking at the differences between the two object types. This also addresses your question about disk vs memory (I didn't see any significant difference in behaviour between the two).

Regarding the question in the title though as to when to use a table variable vs a local temporary table you don't always have a choice. In functions, for example, it is only possible to use a table variable and if you need to write to the table in a child scope then only a #temp table will do (table-valued parameters allow readonly access).

Where you do have a choice some suggestions are below (though the most reliable method is to simply test both with your specific workload).

  1. If you need an index that cannot be created on a table variable then you will of course need a #temporary table. The details of this are version dependant however. For SQL Server 2012 and below the only indexes that could be created on table variables were those implicitly created through a UNIQUE or PRIMARY KEY constraint. SQL Server 2014 introduced inline index syntax for a subset of the options available in CREATE INDEX. This has been extended since to allow filtered index conditions. Indexes with INCLUDE-d columns or columnstore indexes are still not possible to create on table variables however.

  2. If you will be repeatedly adding and deleting large numbers of rows from the table then use a #temporary table. That supports TRUNCATE (which is more efficient than DELETE for large tables) and additionally subsequent inserts following a TRUNCATE can have better performance than those following a DELETE as illustrated here.

  3. If you will be deleting or updating a large number of rows then the temp table may well perform much better than a table variable - if it is able to use rowset sharing (see "Effects of rowset sharing" below for an example).
  4. If the optimal plan using the table will vary dependent on data then use a #temporary table. That supports creation of statistics which allows the plan to be dynamically recompiled according to the data (though for cached temporary tables in stored procedures the recompilation behaviour needs to be understood separately).
  5. If the optimal plan for the query using the table is unlikely to ever change then you may consider a table variable to skip the overhead of statistics creation and recompiles (would possibly require hints to fix the plan you want).
  6. If the source for the data inserted to the table is from a potentially expensive SELECT statement then consider that using a table variable will block the possibility of this using a parallel plan.
  7. If you need the data in the table to survive a rollback of an outer user transaction then use a table variable. A possible use case for this might be logging the progress of different steps in a long SQL batch.
  8. When using a #temp table within a user transaction locks can be held longer than for table variables (potentially until the end of transaction vs end of statement dependent on the type of lock and isolation level) and also it can prevent truncation of the tempdb transaction log until the user transaction ends. So this might favour the use of table variables.
  9. Within stored routines, both table variables and temporary tables can be cached. The metadata maintenance for cached table variables is less than that for #temporary tables. Bob Ward points out in his tempdb presentation that this can cause additional contention on system tables under conditions of high concurrency. Additionally, when dealing with small quantities of data this can make a measurable difference to performance.

Effects of rowset sharing

DECLARE @T TABLE(id INT PRIMARY KEY, Flag BIT);

CREATE TABLE #T (id INT PRIMARY KEY, Flag BIT);

INSERT INTO @T 
output inserted.* into #T
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), 0
FROM master..spt_values v1, master..spt_values v2

SET STATISTICS TIME ON

/*CPU time = 7016 ms,  elapsed time = 7860 ms.*/
UPDATE @T SET Flag=1;

/*CPU time = 6234 ms,  elapsed time = 7236 ms.*/
DELETE FROM @T

/* CPU time = 828 ms,  elapsed time = 1120 ms.*/
UPDATE #T SET Flag=1;

/*CPU time = 672 ms,  elapsed time = 980 ms.*/
DELETE FROM #T

DROP TABLE #T

How to convert a string of bytes into an int?

I use the following function to convert data between int, hex and bytes.

def bytes2int(str):
 return int(str.encode('hex'), 16)

def bytes2hex(str):
 return '0x'+str.encode('hex')

def int2bytes(i):
 h = int2hex(i)
 return hex2bytes(h)

def int2hex(i):
 return hex(i)

def hex2int(h):
 if len(h) > 1 and h[0:2] == '0x':
  h = h[2:]

 if len(h) % 2:
  h = "0" + h

 return int(h, 16)

def hex2bytes(h):
 if len(h) > 1 and h[0:2] == '0x':
  h = h[2:]

 if len(h) % 2:
  h = "0" + h

 return h.decode('hex')

Source: http://opentechnotes.blogspot.com.au/2014/04/convert-values-to-from-integer-hex.html

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

How to cherry-pick multiple commits

Actually, the simplest way to do it could be to:

  1. record the merge-base between the two branches: MERGE_BASE=$(git merge-base branch-a branch-b)
  2. fast-forward or rebase the older branch onto the newer branch
  3. rebase the resulting branch onto itself, starting at the merge base from step 1, and manually remove commits that are not desired:

    git rebase ${SAVED_MERGE_BASE} -i
    

    Alternatively, if there are only a few new commits, skip step 1, and simply use

    git rebase HEAD^^^^^^^ -i
    

    in the first step, using enough ^ to move past the merge-base.

You will see something like this in the interactive rebase:

pick 3139276 commit a
pick c1b421d commit b
pick 7204ee5 commit c
pick 6ae9419 commit d
pick 0152077 commit e
pick 2656623 commit f

Then remove lines b (and any others you want)

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

How do I pipe a subprocess call to a text file?

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

Can I pass a JavaScript variable to another browser window?

Provided the windows are from the same security domain, and you have a reference to the other window, yes.

Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to the window which created it.

Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

The variable names should be descriptive:

var date = new Date;
date.setTime(result_from_Date_getTime);

var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours();

var year = date.getFullYear();
var month = date.getMonth(); // beware: January = 0; February = 1, etc.
var day = date.getDate();

var dayOfWeek = date.getDay(); // Sunday = 0, Monday = 1, etc.
var milliSeconds = date.getMilliseconds();

The days of a given month do not change. In a leap year, February has 29 days. Inspired by http://www.javascriptkata.com/2007/05/24/how-to-know-if-its-a-leap-year/ (thanks Peter Bailey!)

Continued from the previous code:

var days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// for leap years, February has 29 days. Check whether
// February, the 29th exists for the given year
if( (new Date(year, 1, 29)).getDate() == 29 ) days_in_month[1] = 29;

There is no straightforward way to get the week of a year. For the answer on that question, see Is there a way in javascript to create a date object using year & ISO week number?

Clip/Crop background-image with CSS

may be you can write like this:

#graphic { 
 background-image: url(image.jpg); 
 background-position: 0 -50px; 
 width: 200px; 
 height: 100px;
}

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

The same thing happened to me and i found that i forgot to put the " at the end of the

#import "CPDConstants.h

so instead

#import "CPDConstants.h"

Checking length of dictionary object

Count and show keys in a dictionary (run in console):

o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")

Sample output:

"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"

Simple count function:

function size_dict(d){c=0; for (i in d) ++c; return c}

How to send email using simple SMTP commands via Gmail?

Based on the existing answers, here's a step-by-step guide to sending automated e-mails over SMTP, using a GMail account, from the command line, without disclosing the password.

Requirements

First, install the following software packages:

These instructions assume a Linux operating system, but should be reasonably easy to port to Windows (via Cygwin or native equivalents), or other operating system.

Authentication

Save the following shell script as authentication.sh:

#!/bin/bash

# Asks for a username and password, then spits out the encoded value for
# use with authentication against SMTP servers.

echo -n "Email (shown): "
read email
echo -n "Password (hidden): "
read -s password
echo

TEXT="\0$email\0$password"

echo -ne $TEXT | base64

Make it executable and run it as follows:

chmod +x authentication.sh
./authentication.sh

When prompted, provide your e-mail address and password. This will look something like:

Email (shown): [email protected]
Password (hidden): 
AGJvYkBnbWFpbC5jb20AYm9iaXN0aGViZXN0cGVyc29uZXZlcg==

Copy the last line (AGJ...==), as this will be used for authentication.

Notification

Save the following expect script as notify.sh (note the first line refers to the expect program):

#!/usr/bin/expect

set address "[lindex $argv 0]"
set subject "[lindex $argv 1]"
set ts_date "[lindex $argv 2]"
set ts_time "[lindex $argv 3]"

set timeout 10
spawn openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof 

expect "220" {
  send "EHLO localhost\n"

  expect "250" {
    send "AUTH PLAIN YOUR_AUTHENTICATION_CODE\n"

    expect "235" {
      send "MAIL FROM: <YOUR_EMAIL_ADDRESS>\n"

      expect "250" {
        send "RCPT TO: <$address>\n"

        expect "250" {
          send "DATA\n"

          expect "354" {
            send "Subject: $subject\n\n"
            send "Email sent on $ts_date at $ts_time.\n"
            send "\n.\n"

            expect "250" {
                send "quit\n"
            }
          }
        }
      }
    }
  }
}

Make the following changes:

  1. Paste over YOUR_AUTHENTICATION_CODE with the authentication code generated by the authentication script.
  2. Change YOUR_EMAIL_ADDRESS with the e-mail address used to generate the authentication code.
  3. Save the file.

For example (note the angle brackets are retained for the e-mail address):

send "AUTH PLAIN AGJvYkBnbWFpbC5jb20AYm9iaXN0aGViZXN0cGVyc29uZXZlcg==\n"
send "MAIL FROM: <[email protected]>\n"

Lastly, make the notify script executable as follows:

chmod +x notify.sh

Send E-mail

Send an e-mail from the command line as follows:

./notify.sh [email protected] "Command Line" "March 14" "15:52"

When should I use the new keyword in C++?

The short answer is yes the "new" keyword is incredibly important as when you use it the object data is stored on the heap as opposed to the stack, which is most important!

get everything between <tag> and </tag> with php

$regex = '#<code>(.*?)</code>#';

Using # as the delimiter instead of / because then we don't need to escape the / in </code>

As Phoenix posted below, .*? is used to make the .* ("anything") match as few characters as possible before it comes across a </code> (known as a "non-greedy quantifier"). That way, if your string is

<code>hello</code> something <code>again</code>

you'll match hello and again instead of just matching hello</code> something <code>again.

Where does pip install its packages?

pip show <package name> will provide the location for Windows and macOS, and I'm guessing any system. :)

For example:

> pip show cvxopt
Name: cvxopt
Version: 1.2.0
...
Location: /usr/local/lib/python2.7/site-packages

In Python, how do I create a string of n characters in one line of code?

If you can use repeated letters, you can use the * operator:

>>> 'a'*5

'aaaaa'

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Below can be 2 reasons for this issue:

  1. Backup taken on SQL 2012 and Restore Headeronly was done in SQL 2008 R2

  2. Backup media is corrupted.

If we run below command, we can find actual error always:

restore headeronly
from disk = 'C:\Users\Public\Database.bak'

Give complete location of your database file in the quot

Hope it helps

Disabling user input for UITextfield in swift

In storyboard you have two choise:

  1. set the control's 'enable' to false.

enter image description here

  1. set the view's 'user interaction enable' false

enter image description here

The diffierence between these choise is:

the appearance of UITextfild to display in the screen.

enter image description here

  1. First is set the control's enable. You can see the backgroud color is changed.
  2. Second is set the view's 'User interaction enable'. The backgroud color is NOT changed.

Within code:

  1. textfield.enable = false
  2. textfield.userInteractionEnabled = NO

    Updated for Swift 3

    1. textField.isEnabled = false
    2. textfield.isUserInteractionEnabled = false

How to call a Python function from Node.js

You could take your python, transpile it, and then call it as if it were javascript. I have done this succesfully for screeps and even got it to run in the browser a la brython.

How to use icons and symbols from "Font Awesome" on Native Android Application

In case you only need a few font awesome icons, you can also use http://fa2png.io to generate normal pixel images. But if you add new icons/buttons regularly I'd recommend the .ttf version as its more flexible.

Percentage width in a RelativeLayout

You can accomplish this via layout weights. A weight dictates how the unclaimed portions of the screen are divided up. Give each EditText a layout_width of 0, and some proportional weight. I.e., give one a weight of 2, and the other a weight of 1 if you want the first to take up twice as much space.

Can I use tcpdump to get HTTP requests, response header and response body?

There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):

  • Run man tcpdump | less -Ip examples to see some examples

  • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20):

    sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
    
  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54):

    sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
    
  • Monitor HTTP traffic including request and response headers and message body (source):

    tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    

For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).

HTML5 Canvas Resize (Downscale) Image High Quality?

Why use the canvas to resize images? Modern browsers all use bicubic interpolation — the same process used by Photoshop (if you're doing it right) — and they do it faster than the canvas process. Just specify the image size you want (use only one dimension, height or width, to resize proportionally).

This is supported by most browsers, including later versions of IE. Earlier versions may require browser-specific CSS.

A simple function (using jQuery) to resize an image would be like this:

function resizeImage(img, percentage) {
    var coeff = percentage/100,
        width = $(img).width(),
        height = $(img).height();

    return {"width": width*coeff, "height": height*coeff}           
}

Then just use the returned value to resize the image in one or both dimensions.

Obviously there are different refinements you could make, but this gets the job done.

Paste the following code into the console of this page and watch what happens to the gravatars:

function resizeImage(img, percentage) {
    var coeff = percentage/100,
        width = $(img).width(),
        height = $(img).height();

    return {"width": width*coeff, "height": height*coeff}           
}

$('.user-gravatar32 img').each(function(){
  var newDimensions = resizeImage( this, 150);
  this.style.width = newDimensions.width + "px";
  this.style.height = newDimensions.height + "px";
});

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

HintPath vs ReferencePath in Visual Studio

My own experience has been that it's best to stick to one of two kinds of assembly references:

  • A 'local' assembly in the current build directory
  • An assembly in the GAC

I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.

Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).

This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D

Hope that helps!

How do I clone a generic List in Java?

Why would you want to clone? Creating a new list usually makes more sense.

List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);

Job done.

Intellij Cannot resolve symbol on import

What did it for me is to edit the package file in the .idea folder as I accidentally added sources to this jar library and android couldn't resolve it by deleting the sources line as marked in the b/m picture library error.

Then rebuild the gradle and bam problem solved.

When to use dynamic vs. static libraries

A lib is a unit of code that is bundled within your application executable.

A dll is a standalone unit of executable code. It is loaded in the process only when a call is made into that code. A dll can be used by multiple applications and loaded in multiple processes, while still having only one copy of the code on the hard drive.

Dll pros: can be used to reuse/share code between several products; load in the process memory on demand and can be unloaded when not needed; can be upgraded independently of the rest of the program.

Dll cons: performance impact of the dll loading and code rebasing; versioning problems ("dll hell")

Lib pros: no performance impact as code is always loaded in the process and is not rebased; no versioning problems.

Lib cons: executable/process "bloat" - all the code is in your executable and is loaded upon process start; no reuse/sharing - each product has its own copy of the code.

npm can't find package.json

Use the command in win7/win8/win10 (CD) for moving folders:

  1. Enter your projects folder

  2. Run: npm install -d

Setting Java heap space under Maven 2 on Windows

If you are running out of heap space during the surefire (or failsafe) JUnit testing run, changing MAVEN_OPTS may not help you. I kept trying different configurations in MAVEN_OPTS with no luck until I found this post that fixed the problem.

Basically the JUnits fork off into their own environment and ignore the settings in MAVEN_OPTS. You need to configure surefire in your pom to add more memory for the JUnits.

Hopefully this can save someone else some time!


Edit: Copying solution from Keith Chapman's blog just in case the link breaks some day:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <forkMode>pertest</forkMode> 
    <argLine>-Xms256m -Xmx512m</argLine>
    <testFailureIgnore>false</testFailureIgnore> 
    <skip>false</skip> 
    <includes> 
      <include>**/*IntegrationTestSuite.java</include>
    </includes>
  </configuration>
</plugin>

Update (5/31/2017): Thanks to @johnstosh for pointing this out - surefire has evolved a bit since I put this answer out there. Here is a link to their documentation and an updated code sample (arg line is still the important part for this question):

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20</version>
    <configuration>
        <forkCount>3</forkCount>
        <reuseForks>true</reuseForks>
        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
        <systemPropertyVariables>
            <databaseSchema>MY_TEST_SCHEMA_${surefire.forkNumber}</databaseSchema>
        </systemPropertyVariables>
        <workingDirectory>FORK_DIRECTORY_${surefire.forkNumber}</workingDirectory>
    </configuration>
  </plugin>

How to handle invalid SSL certificates with Apache HttpClient?

https://mms.nw.ru uses a self-signed certificate that's not in the default trust manager set. To resolve the issue, do one of the following:

  • Configure SSLContext with a TrustManager that accepts any certificate (see below).
  • Configure SSLContext with an appropriate trust store that includes your certificate.
  • Add the certificate for that site to the default Java trust store.

Here's a program that creates a (mostly worthless) SSL Context that accepts any certificate:

import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SSLTest {
    
    public static void main(String [] args) throws Exception {
        // configure the SSLContext with a TrustManager
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
        SSLContext.setDefault(ctx);

        URL url = new URL("https://mms.nw.ru");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        System.out.println(conn.getResponseCode());
        conn.disconnect();
    }
    
    private static class DefaultTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
}

How do I send a file as an email attachment using Linux command line?

From source machine

mysqldump --defaults-extra-file=sql.cnf database | gzip | base64 | mail [email protected]

On Destination machine. Save the received mail body as db.sql.gz.b64; then..

base64 -D -i db.sql.gz.b64 | gzip -d | mysql --defaults-extra-file=sql.cnf

Jquery change background color

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

How to select date without time in SQL

The fastest is datediff, e.g.

select dateadd(d, datediff(d,0, [datecolumn]), 0), other..
from tbl

But if you only need to use the value, then you can skip the dateadd, e.g.

select ...
WHERE somedate <= datediff(d, 0, getdate())

where the expression datediff(d, 0, getdate()) is sufficient to return today's date without time portion.

Send a ping to each IP on a subnet

for i in $(seq 1 254); do ping -c1 -t 1 192.168.11.$i; done

Adding a -t 1 waits only one second before exiting. This improves the speed a lot if you just have a few devices connected to that subnet.

How to set DialogFragment's width and height?

Working on Android 6.0, ran into the same issue. AlertDialog would default to predefined width set in the theme regardless of the actual width set in the custom view's root Layout. I was able to get it to set properly adjusting the width of the loading_message TextView. Without investigating further, it seems that sizing the actual elements and having the root Layout wrap around them makes it work as expected. Below is an XML layout of a loading dialog which sets width of the the dialog correctly. Using the this library for the animation.

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/custom_color"
    android:padding="@dimen/custom_dimen">
    <com.github.rahatarmanahmed.cpv.CircularProgressView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/progress_view"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_centerHorizontal="true"
        app:cpv_color="@color/white"
        app:cpv_animAutostart="true"
        app:cpv_indeterminate="true" />
    <TextView
        android:id="@+id/loading_message"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progress_view"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:textSize="18dp"
        android:layout_marginTop="@dimen/custom_dimen"
        android:textColor="@color/white"
        android:text="@string/custom_string"/>
</RelativeLayout>

Python Pandas merge only certain columns

If you want to drop column(s) from the target data frame, but the column(s) are required for the join, you can do the following:

df1 = df1.merge(df2[['a', 'b', 'key1']], how = 'left',
                left_on = 'key2', right_on = 'key1').drop('key1')

The .drop('key1') part will prevent 'key1' from being kept in the resulting data frame, despite it being required to join in the first place.

How to update json file with python

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile:
    data = json.load(jsonFile)

data["location"] = "NewPath"

with open("replayScript.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile:
    data = json.load(jsonFile)

    data["location"] = "NewPath"

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile)
    jsonFile.truncate()

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Made a couple of additions to the above answers so that you get returned a type instead of string value.

I figured that this is primarily going to be used for UI adjustments so I didn't think it relevant to include all the sub models i.e. iPhone 5s but this could be easily extended by adding in model tests to the isDevice Array

Tested working in Swift 3.1 Xcode 8.3.2 with physical and simulator devices

Implementation:

UIDevice.whichDevice()

public enum SVNDevice {
  case isiPhone4, isIphone5, isIphone6or7, isIphone6por7p, isIphone, isIpad, isIpadPro
}

extension UIDevice {
  class func whichDevice() -> SVNDevice? {
    let isDevice = { (comparision: Array<(Bool, SVNDevice)>) -> SVNDevice? in
      var device: SVNDevice?
      comparision.forEach({
        device = $0.0 ? $0.1 : device
      })
      return device
    }

    return isDevice([
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0, SVNDevice.isiPhone4),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0, SVNDevice.isIphone5),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0, SVNDevice.isIphone6or7),
      (UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0, SVNDevice.isIphone6por7p),
      (UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0, SVNDevice.isIpad),
      (UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0, SVNDevice.isIpadPro)])
  }
}



private struct ScreenSize {
  static let SCREEN_WIDTH         = UIScreen.main.bounds.size.width
  static let SCREEN_HEIGHT        = UIScreen.main.bounds.size.height
  static let SCREEN_MAX_LENGTH    = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
  static let SCREEN_MIN_LENGTH    = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}

I've created a framework called SVNBootstaper which includes this and some other helper protocols, it's public and available through Carthage.

Add Items to ListView - Android

public OnClickListener moreListener = new OnClickListener() {

    @Override
      public void onClick(View v) {
          adapter.add("aaaa")
      }
}

How to get dictionary values as a generic list

Off course, myDico.Values is List<List<MyType>>.

Use Linq if you want to flattern your lists

var items = myDico.SelectMany (d => d.Value).ToList();

How to get the root dir of the Symfony2 application?

UPDATE 2018-10-21:

As of this week, getRootDir() was deprecated. Please use getProjectDir() instead, as suggested in the comment section by Muzaraf Ali.

—-

Use this:

$this->get('kernel')->getRootDir();

And if you want the web root:

$this->get('kernel')->getRootDir() . '/../web' . $this->getRequest()->getBasePath();

this will work from controller action method...

EDIT: As for the services, I think the way you did it is as clean as possible, although I would pass complete kernel service as an argument... but this will also do the trick...

Use tab to indent in textarea

There is a library on Github for tab support in your textareas by wjbryant: Tab Override

This is how it works:

// get all the textarea elements on the page
var textareas = document.getElementsByTagName('textarea');

// enable Tab Override for all textareas
tabOverride.set(textareas);

How to refresh or show immediately in datagridview after inserting?

You can set the datagridview DataSource to null and rebind it again.

private void button1_Click(object sender, EventArgs e)
{
    myAccesscon.ConnectionString = connectionString;

    dataGridView.DataSource = null;
    dataGridView.Update();
    dataGridView.Refresh();
    OleDbCommand cmd = new OleDbCommand(sql, myAccesscon);
    myAccesscon.Open();
    cmd.CommandType = CommandType.Text;
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable bookings = new DataTable();
    da.Fill(bookings);
    dataGridView.DataSource = bookings;
    myAccesscon.Close();
}

How to Apply Corner Radius to LinearLayout

You can create an XML file in the drawable folder. Call it, for example, shape.xml

In shape.xml:

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

    <solid
        android:color="#888888" >
    </solid>

    <stroke
        android:width="2dp"
        android:color="#C4CDE0" >
    </stroke>

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"    >
    </padding>

    <corners
        android:radius="11dp"   >
    </corners>

</shape>

The <corner> tag is for your specific question.

Make changes as required.

And in your whatever_layout_name.xml:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="5dp"
    android:background="@drawable/shape"    >
</LinearLayout>

This is what I usually do in my apps. Hope this helps....

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

The mainly problem are corrupted jars.

To find the corrupted one, you need to add a Java Exception Breakpoint in the Breakpoints View of Eclipse, or your preferred IDE, select the java.util.zip.ZipException class, and restart Tomcat instance.

When the JVM suspends at ZipException breakpoint you must go to JarFile.getManifestFromReference() in the stack trace, and check attribute name to see the filename.

After that, you should delete the file from file system and then right click your project, select Maven, Update Project, check on Force Update of Snapshots/Releases.

What is the Swift equivalent of isEqualToString in Objective-C?

Use == operator instead of isEqual

Comparing Strings

Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.

String Equality

Two String values are considered equal if they contain exactly the same characters in the same order:

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.

For more read official documentation of Swift (search Comparing Strings).

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Similar to what Luke Puplett is saying, the problem can be caused by not properly disposing or creating your context.

In my case, I had a class which accepted a context called ContextService:

public class ContextService : IDisposable
{
    private Context _context;

    public void Dispose()
    {
        _context.Dispose();
    }
    public ContextService(Context context)
    {
        _context = context;
    }
//... do stuff with the context

My context service had a function which updates an entity using an instantiated entity object:

        public void UpdateEntity(MyEntity myEntity, ICollection<int> ids)
        {
            var item = _context.Entry(myEntity);
            item.State = EntityState.Modified;
            item.Collection(x => x.RelatedEntities).Load();
            myEntity.RelatedEntities.Clear();
            foreach (var id in ids)
            {
                myEntity.RelatedEntities.Add(_context.RelatedEntities.Find(id));
            }
            _context.SaveChanges();
        }

All of this was fine, my controller where I initialized the service was the problem. My controller originally looked like this:

    private static NotificationService _service = 
        new NotificationService(new NotificationContext());
    public void Dispose()
    {
    }

I changed it to this and the error went away:

    private static NotificationService _service;
    public TemplateController()
    {
        _service = new NotificationService(new NotificationContext());
    }
    public void Dispose()
    {
        _service.Dispose();
    }

RuntimeWarning: DateTimeField received a naive datetime

Use django.utils.timezone.make_aware function to make your naive datetime objects timezone aware and avoid those warnings.

It converts naive datetime object (without timezone info) to the one that has timezone info (using timezone specified in your django settings if you don't specify it explicitly as a second argument):

import datetime
from django.conf import settings
from django.utils.timezone import make_aware

naive_datetime = datetime.datetime.now()
naive_datetime.tzinfo  # None

settings.TIME_ZONE  # 'UTC'
aware_datetime = make_aware(naive_datetime)
aware_datetime.tzinfo  # <UTC>

SQL Update Multiple Fields FROM via a SELECT Statement

You can use:

UPDATE s SET
  s.Field1 = q.Field1,
  s.Field2 = q.Field2,
  (list of fields...)
FROM (
  SELECT Field1, Field2, (list of fields...)
  FROM ProfilerTest.dbo.BookingDetails 
  WHERE MyID=@MyID
) q
WHERE s.MyID2=@ MyID2

How to update column with null value

NULL is a special value in SQL. So to null a property, do this:

UPDATE table SET column = NULL;

Get DOM content of cross-domain iframe

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Change x axes scale in matplotlib

I find the simple solution

pylab.ticklabel_format(axis='y',style='sci',scilimits=(1,4))

Enter key press behaves like a Tab in Javascript

This worked for me:

$(document).on('keydown', ':tabbable', function(e) {

    if (e.key === "Enter") {
        e.preventDefault();

        var $canfocus = $(':tabbable:visible');
        var index = $canfocus.index(document.activeElement) + 1;

        if (index >= $canfocus.length) index = 0;
        $canfocus.eq(index).focus();
    }

});

HTML Mobile -forcing the soft keyboard to hide

I am fighting the soft keyboard on the Honeywell Dolphin 70e with Android 4.0.3. I don't need the keyboard because the input comes from the builtin barcode reader through the 'scanwedge', set to generate key events.

What I found was that the trick described in the earlier answers of:

input.blur();
input.focus();

works, but only once, right at page initialization. It puts the focus in the input element without showing the soft keyboard. It does NOT work later, e.g. after a TAB character in the suffix of the barcode causes the onblur or oninput event on the input element.

To read and process lots of barcodes, you may use a different postfix than TAB (9), e.g. 8, which is not interpreted by the browser. In the input.keydown event, use e.keyCode == 8 to detect a complete barcode to be processed.

This way, you initialize the page with focus in the input element, with keyboard hidden, all barcodes go to the input element, and the focus never leaves that element. Of course, the page cannot have other input elements (like buttons), because then you will not be able to return to the barcode input element with the soft keyboard hidden.

Perhaps reloading the page after a button click may be able to hide the keyboard. So use ajax for fast processing of barcodes, and use a regular asp.net button with PostBack to process a button click and reload the page to return focus to the barcode input with the keyboard hidden.

RSA: Get exponent and modulus given a public key

Beware the leading 00 that can appear in the modulus when using:

openssl rsa -pubin -inform PEM -text -noout < public.key

The example modulus contains 257 bytes rather than 256 bytes because of that 00, which is included because the 9 in 98 looks like a negative signed number.

Axios having CORS issue

May help to someone:

I'm sending data from react application to golang server.

Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*"). Error has fixed.

React form submit function:

async handleSubmit(e) {
    e.preventDefault();

    const headers = {
        'Content-Type': 'text/plain'
    };

    await axios.post(
        'http://localhost:3001/login',
        {
            user_name: this.state.user_name,
            password: this.state.password,
        },
        {headers}
        ).then(response => {
            console.log("Success ========>", response);
        })
        .catch(error => {
            console.log("Error ========>", error);
        }
    )
}

Go server got Router,

func main()  {
    router := mux.NewRouter()

    router.HandleFunc("/login", Login.Login).Methods("POST")

    log.Fatal(http.ListenAndServe(":3001", router))
}

Login.go,

func Login(w http.ResponseWriter, r *http.Request)  {

    var user = Models.User{}
    data, err := ioutil.ReadAll(r.Body)

    if err == nil {
        err := json.Unmarshal(data, &user)
        if err == nil {
            user = Postgres.GetUser(user.UserName, user.Password)
            w.Header().Set("Access-Control-Allow-Origin", "*")
            json.NewEncoder(w).Encode(user)
        }
    }
}

Remove shadow below actionbar

What is the style item to make it disappear?

In order to remove the shadow add this to your app theme:

<style name="MyAppTheme" parent="android:Theme.Holo.Light">
    <item name="android:windowContentOverlay">@null</item>
</style>

UPDATE: As @Quinny898 stated, on Android 5.0 this has changed, you have to call setElevation(0) on your action bar. Note that if you're using the support library you must call it to that like so:

getSupportActionBar().setElevation(0);

How to read a line from the console in C?

This function should do what you want:

char* readLine( FILE* file )
 {
 char buffer[1024];
 char* result = 0;
 int length = 0;

 while( !feof(file) )
  {
  fgets( buffer, sizeof(buffer), file );
  int len = strlen(buffer);
  buffer[len] = 0;

  length += len;
  char* tmp = (char*)malloc(length+1);
  tmp[0] = 0;

  if( result )
   {
   strcpy( tmp, result );
   free( result );
   result = tmp;
   }

  strcat( result, buffer );

  if( strstr( buffer, "\n" ) break;
  }

 return result;
 }

char* line = readLine( stdin );
/* Use it */
free( line );

I hope this helps.

How do you tell if a string contains another string in POSIX sh?

See the manpage for the 'test' program. If you're just testing for the existence of a directory you would normally do something like so:

if test -d "String1"; then
  echo "String1 present"
end

If you're actually trying to match a string you can use bash expansion rules & wildcards as well:

if test -d "String*"; then
  echo "A directory starting with 'String' is present"
end

If you need to do something more complex you'll need to use another program like expr.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

I dont know what is the exact reason but I solved the problem running:

   app/console cache:clear --env=prod

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

How to get my project path?

Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../.. to get your project's path.

What are the options for (keyup) in Angular2?

I was searching for a way to bind to multiple key events - specifically, Shift+Enter - but couldn't find any good resources online. But after logging the keydown binding

<textarea (keydown)=onKeydownEvent($event)></textarea>

I discovered that the keyboard event provided all of the information I needed to detect Shift+Enter. Turns out that $event returns a fairly detailed KeyboardEvent.

onKeydownEvent(event: KeyboardEvent): void {
   if (event.keyCode === 13 && event.shiftKey) {
       // On 'Shift+Enter' do this...
   }
}

There also flags for the CtrlKey, AltKey, and MetaKey (i.e. Command key on Mac).

No need for the KeyEventsPlugin, JQuery, or a pure JS binding.

Easiest way to ignore blank lines when reading a file in Python

What about LineSentence module, it will ignore such lines:

Bases: object

Simple format: one sentence = one line; words already preprocessed and separated by whitespace.

source can be either a string or a file object. Clip the file to the first limit lines (or not clipped if limit is None, the default).

from gensim.models.word2vec import LineSentence
text = LineSentence('text.txt')

Microsoft SQL Server 2005 service fails to start

It looks like not all of your prerequisites are really working as they should be. Also, you'll want to make sure that you are installing from the console itself and not through any kind of remote session at all. (I know, this is a pain in the a@@, but sometimes it makes a difference.)

You can acess the SQL Server 2005 Books Online on the Web at: http://msdn.microsoft.com/en-us/library/ms130214(SQL.90).aspx. This documentation should help you decipher the logs.

Bonus tidbit: Once you get that far, if you plan on installing SP2 without getting an installation that fails and rolls back, another little pearl of wisdom is described here: http://blog.andreloker.de/post/2008/07/17/SQL-Server-hotfix-KB948109-fails-with-error-1920.aspx. (My issue was that the "SQL Server VSS Writer" (Service) was not even installed.) Good luck!

Sql Query to list all views in an SQL Server 2005 database

Necromancing.

Since you said ALL views, technically, all answers to date are WRONG.
Here is how to get ALL views:

SELECT 
     sch.name AS view_schema 
    ,sysv.name AS view_name 
    ,ISNULL(sysm.definition, syssm.definition) AS view_definition 
    ,create_date 
    ,modify_date 
FROM sys.all_views AS sysv 

INNER JOIN sys.schemas AS sch 
    ON sch.schema_id = sysv.schema_id 

LEFT JOIN sys.sql_modules AS sysm 
    ON sysm.object_id = sysv.object_id 

LEFT JOIN sys.system_sql_modules AS syssm 
    ON syssm.object_id = sysv.object_id 

-- INNER JOIN sys.objects AS syso ON syso.object_id = sysv.object_id 

WHERE (1=1) 
AND (sysv.type = 'V') -- seems unnecessary, but who knows
-- AND sch.name = 'INFORMATION_SCHEMA' 
/*
AND sysv.is_ms_shipped = 0  
AND NOT EXISTS 
(
    SELECT * FROM sys.extended_properties AS syscrap
    WHERE syscrap.major_id = sysv.object_id
    AND syscrap.minor_id = 0 
    AND syscrap.class = 1 
    AND syscrap.name = N'microsoft_database_tools_support' 
)  
*/

ORDER BY 
     view_schema 
    ,view_name 

Add a duration to a moment (moment.js)

I think you missed a key point in the documentation for .add()

Mutates the original moment by adding time.

You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)

If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.

You can work around this behavior by cloning the moment, as described here.

Also, you cannot just use == to test. You could format each moment to the same output and compare those, or you could just use the .isSame() method.

Your code is now:

var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours');  // see the cloning?
returned_endate.isSame(expected_enddate)  // true

Get text of the selected option with jQuery

Close, you can use

$('#select_2 option:selected').html()

WPF button click in C# code

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}

How to prevent a dialog from closing when a button is clicked

The answer at this link is a simple solution, and which is compatible right back to API 3. It is very similiar to Tom Bollwitt's solution, but without using the less compatible OnShowListener.

Yes, you can. You basically need to:

  1. Create the dialog with DialogBuilder
  2. show() the dialog
  3. Find the buttons in the dialog shown and override their onClickListener

I made minor adaptions to Kamen's code since I was extending an EditTextPreference.

@Override
protected void showDialog(Bundle state) {
  super.showDialog(state);

  class mocl implements OnClickListener{
    private final AlertDialog dialog;
    public mocl(AlertDialog dialog) {
          this.dialog = dialog;
      }
    @Override
    public void onClick(View v) {

        //checks if EditText is empty, and if so tells the user via Toast
        //otherwise it closes dialog and calls the EditTextPreference's onClick
        //method to let it know that the button has been pressed

        if (!IntPreference.this.getEditText().getText().toString().equals("")){
        dialog.dismiss();
        IntPreference.this.onClick(dialog,DialogInterface.BUTTON_POSITIVE);
        }
        else {
            Toast t = Toast.makeText(getContext(), "Enter a number!", Toast.LENGTH_SHORT);
            t.show();
        }

    }
  }

  AlertDialog d = (AlertDialog) getDialog();
  Button b = d.getButton(DialogInterface.BUTTON_POSITIVE);
  b.setOnClickListener(new mocl((d)));
}

Such fun!

Only read selected columns

Say the data are in file data.txt, you can use the colClasses argument of read.table() to skip columns. Here the data in the first 7 columns are "integer" and we set the remaining 6 columns to "NULL" indicating they should be skipped

> read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)), 
+            header = TRUE)
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

Change "integer" to one of the accepted types as detailed in ?read.table depending on the real type of data.

data.txt looks like this:

$ cat data.txt 
"Year" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29

and was created by using

write.table(dat, file = "data.txt", row.names = FALSE)

where dat is

dat <- structure(list(Year = 2009:2011, Jan = c(-41L, -41L, -21L), Feb = c(-27L, 
-27L, -27L), Mar = c(-25L, -25L, -2L), Apr = c(-31L, -31L, -6L
), May = c(-31L, -31L, -10L), Jun = c(-39L, -39L, -32L), Jul = c(-25L, 
-25L, -13L), Aug = c(-15L, -15L, -12L), Sep = c(-30L, -30L, -27L
), Oct = c(-27L, -27L, -30L), Nov = c(-21L, -21L, -38L), Dec = c(-25L, 
-25L, -29L)), .Names = c("Year", "Jan", "Feb", "Mar", "Apr", 
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame",
row.names = c(NA, -3L))

If the number of columns is not known beforehand, the utility function count.fields will read through the file and count the number of fields in each line.

## returns a vector equal to the number of lines in the file
count.fields("data.txt", sep = "\t")
## returns the maximum to set colClasses
max(count.fields("data.txt", sep = "\t"))

Multidimensional arrays in Swift

Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:

column: 0 row: 0 value:1.0
column: 0 row: 1 value:4.0
column: 0 row: 2 value:7.0
column: 1 row: 0 value:2.0
column: 1 row: 1 value:5.0
column: 1 row: 2 value:8.0
column: 2 row: 0 value:3.0
column: 2 row: 1 value:6.0
column: 2 row: 2 value:9.0

I just copied and pasted your code into a Swift playground and defined two constants:

let NumColumns = 3, NumRows = 3

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);

VBA Excel Provide current Date in Text box

I know this is extremely old post, but I've used this before

You can always adjust to activate. Now method is another way. Just an option

Private Sub UserForm_Initialize()

Textbox1.Text = Format(Now(), "mmddyyyhhmmss")

End Sub

The ResourceConfig instance does not contain any root resource classes

I am new to Jersey - I had the same issue, But when I removed the "/" and just used the @path("admin") it worked.

@Path("admin")
public class AdminUiResource { ... }

What's the best way to store a group of constants that my program uses?

If these Constants are service references or switches that effect the application behavior I would set them up as Application user settings. That way if they need to be changed you do not have to recompile and you can still reference them through the static properties class.

Properties.Settings.Default.ServiceRef

Get all dates between two dates in SQL Server

You can use SQL Server recursive CTE

DECLARE 
    @MinDate DATE = '2020-01-01',
    @MaxDate DATE = '2020-02-01';

WITH Dates(day) AS 
(
    SELECT CAST(@MinDate as Date) as day
    UNION ALL
    SELECT CAST(DATEADD(day, 1, day) as Date) as day
    FROM Dates
    WHERE CAST(DATEADD(day, 1, day) as Date) < @MaxDate
)
SELECT* FROM dates;

show more/Less text with just HTML and JavaScript

With some HTML changes, you can absolutely achieve this with CSS:

Lorem ipsum dolor sit amet
<p id="textarea">
    <!-- This is where I want to additional text-->
    All that delicious text is in here!
</p>
<!-- the show/hide controls inside of the following
     list, for ease of selecting with CSS -->
<ul class="controls">
    <li class="show"><a href="#textarea">Show</a></li>
    <li class="hide"><a href="#">Hide</a></li>
</ul>

<p>Here is some more text</p>

Coupled with the CSS:

#textarea {
    display: none; /* hidden by default */
}

#textarea:target {
    display: block; /* shown when a link targeting this id is clicked */
}

#textarea + ul.controls {
    list-style-type: none; /* aesthetics only, adjust to taste, irrelevant to demo */
}

/* hiding the hide link when the #textarea is not targeted,
   hiding the show link when it is selected: */
#textarea + ul.controls .hide,
#textarea:target + ul.controls .show {
    display: none;
}

/* Showing the hide link when the #textarea is targeted,
   showing the show link when it's not: */
#textarea:target + ul.controls .hide,
#textarea + ul.controls .show {
    display: inline-block;
}

JS Fiddle demo.

Or, you could use a label and an input of type="checkbox":

Lorem ipsum dolor sit amet
<input id="textAreaToggle" type="checkbox" />
<p id="textarea">
    <!-- This is where I want to additional text-->
    All that delicious text is in here!
</p>
<label for="textAreaToggle">textarea</label>

<p>Here is some more text</p>

With the CSS:

#textarea {
    /* hide by default: */
    display: none;
}

/* when the checkbox is checked, show the neighbouring #textarea element: */
#textAreaToggle:checked + #textarea {
    display: block;
}

/* position the checkbox off-screen: */
input[type="checkbox"] {
    position: absolute;
    left: -1000px;
}

/* Aesthetics only, adjust to taste: */
label {
    display: block;
}

/* when the checkbox is unchecked (its default state) show the text
   'Show ' in the label element: */
#textAreaToggle + #textarea + label::before {
    content: 'Show ';
}

/* when the checkbox is checked 'Hide ' in the label element; the
   general-sibling combinator '~' is required for a bug in Chrome: */
#textAreaToggle:checked ~ #textarea + label::before {
    content: 'Hide ';
}

JS Fiddle demo.

MySQL FULL JOIN?

Try This:

(SELECT p.LastName, p.FirstName, o.OrderNo
 FROM   Persons p
   LEFT JOIN Orders o
   ON o.OrderNo = p.P_id
)
UNION
(SELECT p.LastName, p.FirstName, o.OrderNo
 FROM   Persons p
   RIGHT JOIN Orders o
   ON o.OrderNo = p.P_id
);

+----------+-----------+---------+
| LastName | FirstName | OrderNo |
+----------+-----------+---------+
| Singh    | Shashi    |       1 |
| Yadav    | Sunil     |    NULL |
| Singh    | Satya     |    NULL |
| Jain     | Ankit     |    NULL |
| NULL     | NULL      |      11 |
| NULL     | NULL      |      12 |
| NULL     | NULL      |      13 |
+----------+-----------+---------+

What can cause a “Resource temporarily unavailable” on sock send() command

Let'e me give an example:

  1. client connect to server, and send 1MB data to server every 1 second.

  2. server side accept a connection, and then sleep 20 second, without recv msg from client.So the tcp send buffer in the client side will be full.

Code in client side:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...)                                                                          \
    if (r) {                                                                                     \
        printf(__VA_ARGS__);                                                                     \
        printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
        exit(1);                                                                                 \
    }

void setNonBlock(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    exit_if(flags < 0, "fcntl failed");
    int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    exit_if(r < 0, "fcntl failed");
}

void test_full_sock_buf_1(){
    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;


    int fd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(fd<0, "create socket error");

    int ret = connect(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(ret<0, "connect to server error");
    setNonBlock(fd);

    printf("connect to server success");

    const int LEN = 1024 * 1000;
    char msg[LEN];  // 1MB data
    memset(msg, 'a', LEN);

    for (int i = 0; i < 1000; ++i) {
        int len = send(fd, msg, LEN, 0);
        printf("send: %d, erron: %d, %s \n", len, errno, strerror(errno));
        sleep(1);
    }

}

int main(){
    test_full_sock_buf_1();

    return 0;
}

Code in server side:

    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <stdio.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <string.h>
    #define exit_if(r, ...)                                                                          \
        if (r) {                                                                                     \
            printf(__VA_ARGS__);                                                                     \
            printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
            exit(1);                                                                                 \
        }
void test_full_sock_buf_1(){

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(listenfd<0, "create socket error");

    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;

    int r = ::bind(listenfd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(r<0, "bind socket error");

    r = listen(listenfd, 100);
    exit_if(r<0, "listen socket error");

    struct sockaddr_in raddr;
    socklen_t rsz = sizeof(raddr);
    int cfd = accept(listenfd, (struct sockaddr *) &raddr, &rsz);
    exit_if(cfd<0, "accept socket error");

    sockaddr_in peer;
    socklen_t alen = sizeof(peer);
    getpeername(cfd, (sockaddr *) &peer, &alen);

    printf("accept a connection from %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));

    printf("but now I will sleep 15 second, then exit");
    sleep(15);
}

Start server side, then start client side.

server side may output:

accept a connection from 127.0.0.1:35764
but now I will sleep 15 second, then exit
Process finished with exit code 0

enter image description here

client side may output:

connect to server successsend: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 552190, erron: 0, Success 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 104, Connection reset by peer 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 

enter image description here

You can see, as the server side doesn't recv the data from client, so when the client side tcp buffer get full, but you still send data, so you may get Resource temporarily unavailable error.

Stack smashing detected

You could try to debug the problem using valgrind:

The Valgrind distribution currently includes six production-quality tools: a memory error detector, two thread error detectors, a cache and branch-prediction profiler, a call-graph generating cache profiler, and a heap profiler. It also includes two experimental tools: a heap/stack/global array overrun detector, and a SimPoint basic block vector generator. It runs on the following platforms: X86/Linux, AMD64/Linux, PPC32/Linux, PPC64/Linux, and X86/Darwin (Mac OS X).

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Adding dictionaries together, Python

If you're interested in creating a new dict without using intermediary storage: (this is faster, and in my opinion, cleaner than using dict.items())

dic2 = dict(dic0, **dic1)

Or if you're happy to use one of the existing dicts:

dic0.update(dic1)

How do I add a reference to the MySQL connector for .NET?

When you download the connector/NET choose Select Platform = .NET & Mono (not windows!)

Moving average or running mean

Another solution just using a standard library and deque:

from collections import deque
import itertools

def moving_average(iterable, n=3):
    # http://en.wikipedia.org/wiki/Moving_average
    it = iter(iterable) 
    # create an iterable object from input argument
    d = deque(itertools.islice(it, n-1))  
    # create deque object by slicing iterable
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / n

# example on how to use it
for i in  moving_average([40, 30, 50, 46, 39, 44]):
    print(i)

# 40.0
# 42.0
# 45.0
# 43.0

Javascript select onchange='this.form.submit()'

Bind them using jQuery and make jQuery handle it: http://jsfiddle.net/ZmxpW/.

$('select').change(function() {
    $(this).parents('form').submit();
});

Receive result from DialogFragment

One easy way I found was the following: Implement this is your dialogFragment,

  CallingActivity callingActivity = (CallingActivity) getActivity();
  callingActivity.onUserSelectValue("insert selected value here");
  dismiss();

And then in the activity that called the Dialog Fragment create the appropriate function as such:

 public void onUserSelectValue(String selectedValue) {

        // TODO add your implementation.
      Toast.makeText(getBaseContext(), ""+ selectedValue, Toast.LENGTH_LONG).show();
    }

The Toast is to show that it works. Worked for me.

What is the difference between . (dot) and $ (dollar sign)?

One application that is useful and took me some time to figure out from the very short description at learn you a haskell: Since:

f $ x = f x

and parenthesizing the right hand side of an expression containing an infix operator converts it to a prefix function, one can write ($ 3) (4+) analogous to (++", world") "hello".

Why would anyone do this? For lists of functions, for example. Both:

map (++", world") ["hello","goodbye"]`

and:

map ($ 3) [(4+),(3*)]

are shorter than map (\x -> x ++ ", world") ... or map (\f -> f 3) .... Obviously, the latter variants would be more readable for most people.

Display the binary representation of a number in C?

This code should handle your needs up to 64 bits.



char* pBinFill(long int x,char *so, char fillChar); // version with fill
char* pBin(long int x, char *so);                    // version without fill
#define width 64

char* pBin(long int x,char *so)
{
 char s[width+1];
 int    i=width;
 s[i--]=0x00;   // terminate string
 do
 { // fill in array from right to left
  s[i--]=(x & 1) ? '1':'0';  // determine bit
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 i++;   // point to last valid character
 sprintf(so,"%s",s+i); // stick it in the temp string string
 return so;
}

char* pBinFill(long int x,char *so, char fillChar)
{ // fill in array from right to left
 char s[width+1];
 int    i=width;
 s[i--]=0x00;   // terminate string
 do
 {
  s[i--]=(x & 1) ? '1':'0';
  x>>=1;  // shift right 1 bit
 } while( x > 0);
 while(i>=0) s[i--]=fillChar;    // fill with fillChar 
 sprintf(so,"%s",s);
 return so;
}

void test()
{
 char so[width+1]; // working buffer for pBin
 long int   val=1;
 do
 {
   printf("%ld =\t\t%#lx =\t\t0b%s\n",val,val,pBinFill(val,so,0));
   val*=11; // generate test data
 } while (val < 100000000);
}

Output:
00000001 = 0x000001 =   0b00000000000000000000000000000001
00000011 = 0x00000b =   0b00000000000000000000000000001011
00000121 = 0x000079 =   0b00000000000000000000000001111001
00001331 = 0x000533 =   0b00000000000000000000010100110011
00014641 = 0x003931 =   0b00000000000000000011100100110001
00161051 = 0x02751b =   0b00000000000000100111010100011011
01771561 = 0x1b0829 =   0b00000000000110110000100000101001
19487171 = 0x12959c3 =  0b00000001001010010101100111000011

Alternative Windows shells, besides CMD.EXE?

  1. Hard to copy and paste.

    Not true. Enable QuickEdit, either in the properties of the shortcut, or in the properties of the CMD window (right-click on the title bar), and you can mark text directly. Right-click copies marked text into the clipboard. When no text is marked, a right-click pastes text from the clipboard.

    enter image description here

  2. Hard to resize the window.

    True. Console2 (see below) does not have this limitation.

  3. Hard to open another window (no menu options do this).

    Not true. Use start cmd or define an alias if that's too much hassle:

    doskey nw=start cmd /k $*
    
  4. Seems to always start in C:\Windows\System32, which is super useless.

    Not true. Or rather, not true if you define a start directory in the properties of the shortcut

    enter image description here

    or by modifying the AutoRun registry value. Shift-right-click on a folder allows you to launch a command prompt in that folder.

  5. Weird scrolling. Sometimes it scrolls down really far into blank space, and you have to scroll up to where the window is actually populated

    Never happened to me.

An alternative to plain CMD is Console2, which uses CMD under the hood, but provides a lot more configuration options.

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

This was happening to me when I had to fix an old project that had not been looked at in a while. The chromedriver associated to the project was not compatible with my version of chrome, so when I updated the chromedriver it worked fine.

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

Highlight Bash/shell code in Markdown files

Per the documentation from GitHub regarding GFM syntax highlighted code blocks

We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.

Rendered on GitHub, console makes the lines after the console blue. bash, sh, or shell don't seem to "highlight" much ...and you can use posh for PowerShell or CMD.

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.

Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.

For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.


Update 2015-07-27: In addition to the Express Editions, Microsoft now offers Community Editions. These are still free for individual developers, open source contributors, and small teams. There are no Web, Windows, and Windows Desktop releases anymore either; the Community Edition can be used to develop any app type. In addition, the Community Edition does support (3rd party) Add-ins. The Community Edition offers the same functionality as the commercial Professional Edition.

Objective-C - Remove last character from string

The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place

...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...

Flutter command not found

In macOS Catalina the default shell is Zsh. I did Following command on Terminal:

  1. nano .zsh (Will open command line editor)
  2. export PATH="$PATH:[PATH_TO_FLUTTER_GIT_DIRECTORY]/flutter/bin:$PATH"
  3. Save file by "Control" + "O" then Press "return"
  4. "Control" + "X" to exit
  5. Relaunch Terminal.
  6. echo $PATH

How to get the last N records in mongodb?

The last N added records, from less recent to most recent, can be seen with this query:

db.collection.find().skip(db.collection.count() - N)

If you want them in the reverse order:

db.collection.find().sort({ $natural: -1 }).limit(N)

If you install Mongo-Hacker you can also use:

db.collection.find().reverse().limit(N)

If you get tired of writing these commands all the time you can create custom functions in your ~/.mongorc.js. E.g.

function last(N) {
    return db.collection.find().skip(db.collection.count() - N);
}

then from a mongo shell just type last(N)

Portable way to get file size (in bytes) in shell?

if you have Perl on your Solaris, then use it. Otherwise, ls with awk is your next best bet, since you don't have stat or your find is not GNU find.

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

if you want that not contains any of a-z and A-Z:

SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')

something like:

"98763045098" or "!%436%$7%$*#"

or other languages like persian, arabic and ... like this:

"???? ????"

How do I start my app on startup?

Listen for the ACTION_BOOT_COMPLETE and do what you need to from there. There is a code snippet here.

Update:

Original link on answer is down, so based on the comments, here it is linked code, because no one would ever miss the code when the links are down.

In AndroidManifest.xml (application-part):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

...

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  //MyActivity can be anything which you want to start on bootup...
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

Source: https://web.archive.org/web/20150520124552/http://www.androidsnippets.com/autostart-an-application-at-bootup

Check if specific input file is empty

if($_FILES['img_name']['name']!=""){
   echo "File Present";
}else{
  echo "Empty file";
}

how to list all sub directories in a directory

show all directry and sub directories

def dir():

from glob import glob

dir = []

dir = glob("path")

def all_sub_dir(dir):
{

     for item in dir:

            {
                b = "{}\*".format(item)
                dir += glob(b)
            }
         print(dir)
}

MySQL delete multiple rows in one query conditions unique to each row

You were very close, you can use this:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle.

How to increase font size in NeatBeans IDE?

At Windows in the file C:\Program Files\NetBeans x.x\etc\netbeans.conf

Add "--fontsize [size]" at the end of line netbeans_default_options:

netbeans_default_options=".... --fontsize 16"

How to flush output after each `echo` call?

I'm late to the discussion but I read that many people are saying appending flush(); at the end of each code looks dirty, and they are right.

Best solution is to disable deflate, gzip and all buffering from Apache, intermediate handlers and PHP. Then in your php.ini you should have:

            output_buffering = Off
            zlib.output_compression = Off
            implicit_flush = Off

Temporary solution is to have this in your php.ini IF you can solve your problem with flush(); but you think it is dirty and ugly to put it everywhere.

implicit_flush = On

If you only put it above in your php.ini, you don't need to put flush(); in your code anymore.

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

Open gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

change it to

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

Background image jumps when address bar hides iOS/Android/Mobile Chrome

Simple answer if your background allows, why not set background-size: to something just covering device width with media queries and use alongside the :after position: fixed; hack here.

IE: background-size: 901px; for any screens <900px? Not perfect or responsive but worked a charm for me on mobile <480px as i'm using an abstract BG.

What are the differences between numpy arrays and matrices? Which one should I use?

As others have mentioned, perhaps the main advantage of matrix was that it provided a convenient notation for matrix multiplication.

However, in Python 3.5 there is finally a dedicated infix operator for matrix multiplication: @.

With recent NumPy versions, it can be used with ndarrays:

A = numpy.ones((1, 3))
B = numpy.ones((3, 3))
A @ B

So nowadays, even more, when in doubt, you should stick to ndarray.

What is the best way to convert an array to a hash in Ruby

Not sure if it's the best way, but this works:

a = ["apple", 1, "banana", 2]
m1 = {}
for x in (a.length / 2).times
  m1[a[x*2]] = a[x*2 + 1]
end

b = [["apple", 1], ["banana", 2]]
m2 = {}
for x,y in b
  m2[x] = y
end

Make Iframe to fit 100% of container's remaining height

Here are a few modern approaches:


  • Approach 1 - Combination of viewport relative units / calc().

    The expression calc(100vh - 30px) represents the remaining height. Where 100vh is the height of the browser and the usage of calc() effectively displaces the height of the other element.

    Example Here

    _x000D_
    _x000D_
    body {_x000D_
        margin: 0;_x000D_
    }_x000D_
    .banner {_x000D_
        background: #f00;_x000D_
        height: 30px;_x000D_
    }_x000D_
    iframe {_x000D_
        display: block;_x000D_
        background: #000;_x000D_
        border: none;_x000D_
        height: calc(100vh - 30px);_x000D_
        width: 100%;_x000D_
    }
    _x000D_
    <div class="banner"></div>_x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_

    Support for calc() here; support for viewport relative units here.


  • Approach 2 - Flexbox approach

    Example Here

    Set the display of the common parent element to flex, along with flex-direction: column (assuming you want the elements to stack on top of each other). Then set flex-grow: 1 on the child iframe element in order for it to fill the remaining space.

    _x000D_
    _x000D_
    body {_x000D_
        margin: 0;_x000D_
    }_x000D_
    .parent {_x000D_
        display: flex;_x000D_
        flex-direction: column;_x000D_
        min-height: 100vh;_x000D_
    }_x000D_
    .parent .banner {_x000D_
        background: #f00;_x000D_
        width: 100%;_x000D_
        height: 30px;_x000D_
    }_x000D_
    .parent iframe {_x000D_
        background: #000;_x000D_
        border: none;_x000D_
        flex-grow: 1;_x000D_
    }
    _x000D_
    <div class="parent">_x000D_
        <div class="banner"></div>_x000D_
        <iframe></iframe>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Since this approach has less support1, I'd suggest going with the aforementioned approach.

1Though it seems to work in Chrome/FF, it doesn't work in IE (the first method works in all current browsers).

How to recover Git objects damaged by hard disk failure?

Banengusk was putting me on the right track. For further reference, I want to post the steps I took to fix my repository corruption. I was lucky enough to find all needed objects either in older packs or in repository backups.

# Unpack last non-corrupted pack
$ mv .git/objects/pack .git/objects/pack.old
$ git unpack-objects -r < .git/objects/pack.old/pack-012066c998b2d171913aeb5bf0719fd4655fa7d0.pack
$ git log
fatal: bad object HEAD

$ cat .git/HEAD 
ref: refs/heads/master

$ ls .git/refs/heads/

$ cat .git/packed-refs 
# pack-refs with: peeled 
aa268a069add6d71e162c4e2455c1b690079c8c1 refs/heads/master

$ git fsck --full 
error: HEAD: invalid sha1 pointer aa268a069add6d71e162c4e2455c1b690079c8c1
error: refs/heads/master does not point to a valid object!
missing blob 75405ef0e6f66e48c1ff836786ff110efa33a919
missing blob 27c4611ffbc3c32712a395910a96052a3de67c9b
dangling tree 30473f109d87f4bcde612a2b9a204c3e322cb0dc

# Copy HEAD object from backup of repository
$ cp repobackup/.git/objects/aa/268a069add6d71e162c4e2455c1b690079c8c1 .git/objects/aa
# Now copy all missing objects from backup of repository and run "git fsck --full" afterwards
# Repeat until git fsck --full only reports dangling objects

# Now garbage collect repo
$ git gc
warning: reflog of 'HEAD' references pruned commits
warning: reflog of 'refs/heads/master' references pruned commits
Counting objects: 3992, done.
Delta compression using 2 threads.
fatal: object bf1c4953c0ea4a045bf0975a916b53d247e7ca94 inconsistent object length (6093 vs 415232)
error: failed to run repack

# Check reflogs...
$ git reflog

# ...then clean
$ git reflog expire --expire=0 --all

# Now garbage collect again
$ git gc       
Counting objects: 3992, done.
Delta compression using 2 threads.
Compressing objects: 100% (3970/3970), done.
Writing objects: 100% (3992/3992), done.
Total 3992 (delta 2060), reused 0 (delta 0)
Removing duplicate objects: 100% (256/256), done.
# Done!

check if variable empty

You can check if it's not set (or empty) in a number of ways.

if (!$var){ }

Or:

if ($var === null){ } // This checks if the variable, by type, IS null.

Or:

if (empty($var)){ }

You can check if it's declared with:

if (!isset($var)){ }

Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.

How to check variable type at runtime in Go language

It seems that Go have special form of switch dedicate to this (it is called type switch):

func (e *Easy)SetOption(option Option, param interface{}) {

    switch v := param.(type) { 
    default:
        fmt.Printf("unexpected type %T", v)
    case uint64:
        e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
    case string:
        e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
    } 
}

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

How to remove single character from a String

By the using replace method we can change single character of string.

string= string.replace("*", "");

Mailx send html message

EMAILCC=" -c [email protected],[email protected]"
TURNO_EMAIL="[email protected]"

mailx $EMAILCC -s "$(echo "Status: Control Aplicactivo \nContent-Type: text/html")" $TURNO_EMAIL < tmp.tmp

How can I get a channel ID from YouTube?

To obtain the channel id you can do the following request which gives you the channel id and playlist id.

https://www.googleapis.com/youtube/v3/channels?part=contentDetails%2C+statistics%2Csnippet&mine=true&key={YOUR_API_KEY}

mine parameter means the current authorized user

as u said channel id is perfixed with UC+{your account id} which you get while login, you can use this one also without requesting the above url you can directly call the channel api with your google id and just prefix with UC

https://www.googleapis.com/youtube/v3/channels?part=contentDetails%2C+statistics%2Csnippet&id=UC{your account id}&key={YOUR_API_KEY}

PowerShell Connect to FTP server and get files

Invoke-WebRequest can download HTTP, HTTPS, and FTP links.

$source = 'ftp://Blah.com/somefile.txt'
$target = 'C:\Users\someuser\Desktop\BlahFiles\somefile.txt'
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList myuserid, $password

# Download
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential -UseBasicParsing

Since the cmdlet uses IE parsing you may need the -UseBasicParsing switch. Test to make sure.

jQuery `.is(":visible")` not working in Chrome

I don't know why your code doesn't work on chrome, but I suggest you use some workarounds :

$el.is(':visible') === $el.is(':not(:hidden)');

or

$el.is(':visible') === !$el.is(':hidden');  

If you are certain that jQuery gives you some bad results in chrome, you can just rely on the css rule checking :

if($el.css('display') !== 'none') {
    // i'm visible
}

Plus, you might want to use the latest jQuery because it might have bugs from older version fixed.

Linux: copy and create destination dir if it does not exist

Simple

cp -a * /path/to/dst/

should do the trick.

Use find command but exclude files in two directories

Here's how you can specify that with find:

find . -type f -name "*_peaks.bed" ! -path "./tmp/*" ! -path "./scripts/*"

Explanation:

  • find . - Start find from current working directory (recursively by default)
  • -type f - Specify to find that you only want files in the results
  • -name "*_peaks.bed" - Look for files with the name ending in _peaks.bed
  • ! -path "./tmp/*" - Exclude all results whose path starts with ./tmp/
  • ! -path "./scripts/*" - Also exclude all results whose path starts with ./scripts/

Testing the Solution:

$ mkdir a b c d e
$ touch a/1 b/2 c/3 d/4 e/5 e/a e/b
$ find . -type f ! -path "./a/*" ! -path "./b/*"

./d/4
./c/3
./e/a
./e/b
./e/5

You were pretty close, the -name option only considers the basename, where as -path considers the entire path =)

Changing ViewPager to enable infinite page scrolling

Actually, I've been looking at the various ways to do this "infinite" pagination, and even though the human notion of time is that it is infinite (even though we have a notion of the beginning and end of time), computers deal in the discrete. There is a minimum and maximum time (that can be adjusted as time goes on, remember the basis of the Y2K scare?).

Anyways, the point of this discussion is that it is/should be sufficient to support a relatively infinite date range through an actually finite date range. A great example of this is the Android framework's CalendarView implementation, and the WeeksAdapter within it. The default minimum date is in 1900 and the default maximum date is in 2100, this should cover 99% of the calendar use of anyone within a 10 year radius around today easily.

What they do in their implementation (focused on weeks) is compute the number of weeks between the minimum and maximum date. This becomes the number of pages in the pager. Remember that the pager doesn't need to maintain all of these pages simultaneously (setOffscreenPageLimit(int)), it just needs to be able to create the page based on the page number (or index/position). In this case the index is the number of weeks that the week is from the minimum date. With this approach you just have to maintain the minimum date and the number of pages (distance to the maximum date), then for any page you can easily compute the week associated with that page. No dancing around the fact that ViewPager doesn't support looping (a.k.a infinite pagination), and trying to force it to behave like it can scroll infinitely.

new FragmentStatePagerAdapter(getFragmentManager()) {
    @Override
    public Fragment getItem(int index) {
        final Bundle arguments = new Bundle(getArguments());
        final Calendar temp_calendar = Calendar.getInstance();
        temp_calendar.setTimeInMillis(_minimum_date.getTimeInMillis());
        temp_calendar.setFirstDayOfWeek(_calendar.getStartOfWeek());
        temp_calendar.add(Calendar.WEEK_OF_YEAR, index);
        // Moves to the first day of this week
        temp_calendar.add(Calendar.DAY_OF_YEAR,
                -UiUtils.modulus(temp_calendar.get(Calendar.DAY_OF_WEEK) - temp_calendar.getFirstDayOfWeek(),
                7));
        arguments.putLong(KEY_DATE, temp_calendar.getTimeInMillis());
        return Fragment.instantiate(getActivity(), WeekDaysFragment.class.getName(), arguments);
    }

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

Then WeekDaysFragment can easily display the week starting at the date passed in its arguments.

Alternatively, it seems that some version of the Calendar app on Android uses a ViewSwitcher (which means there's only 2 pages, the one you see and the hidden page). It then changes the transition animation based on which way the user swiped and renders the next/previous page accordingly. In this way you get infinite pagination because it just switching between two pages infinitely. This requires using a View for the page though, which is way I went with the first approach.

In general, if you want "infinite pagination", it's probably because your pages are based off of dates or times somehow. If this is the case consider using a finite subset of time that is relatively infinite instead. This is how CalendarView is implemented for example. Or you can use the ViewSwitcher approach. The advantage of these two approaches is that neither does anything particularly unusual with the ViewSwitcher or ViewPager, and doesn't require any tricks or reimplementation to coerce them to behave infinitely (ViewSwitcher is already designed to switch between views infinitely, but ViewPager is designed to work on a finite, but not necessarily constant, set of pages).

libpthread.so.0: error adding symbols: DSO missing from command line

The same thing happened to me as I was installing the HPCC benchmark (includes HPL and a few other benchmarks). I added -lm to the compiler flags in my build script and then it successfully compiled.

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

Mine was more of a mistake, what happened was loop click(i guess) basically by clicking on the login the parent was also clicked which ended up causing Maximum call stack size exceeded.

$('.clickhere').click(function(){
   $('.login').click();
});

<li class="clickhere">
  <a href="#" class="login">login</a>
</li>

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Laravel 5 – Clear Cache in Shared Hosting Server

I believe the more efficient approach to this is to use the cron job module in the shared server admin panel to run the laravel scheduler command which will in turn call the configured artisan command, something like this should do the job:

* * * * * /usr/bin/php /var/www/web/artisan schedule:run /dev/null 2>&1

With scheduler setup in cron, you can edit the schedule method in \App\Console\Kernel.php to call the right artisan command, something like this:

$schedule->command('queue:work')->cron('* * * * *')->withoutOverlapping();
$schedule->command('route:cache')->cron('0 0 * * *')->withoutOverlapping();

You can always delete the lines above after the commands run

How to insert a new line in strings in Android

I would personally prefer using "\n". This just puts a line break in Linux or Android.

For example,

String str = "I am the first part of the info being emailed.\nI am the second part.\n\nI am the third part.";

Output

I am the first part of the info being emailed.
I am the second part.

I am the third part.

A more generalized way would be to use,

System.getProperty("line.separator")

For example,

String str = "I am the first part of the info being emailed." + System.getProperty("line.separator") + "I am the second part." + System.getProperty("line.separator") + System.getProperty("line.separator") + "I am the third part.";

brings the same output as above. Here, the static getProperty() method of the System class can be used to get the "line.seperator" for the particular OS.

But this is not necessary at all, as the OS here is fixed, that is, Android. So, calling a method every time is a heavy and unnecessary operation.

Moreover, this also increases your code length and makes it look kind of messy. A "\n" is sweet and simple.

How to remove files from git staging area?

You could use

git reset HEAD

then add the specific files you want with

git add [directory/]filename

Encrypt and decrypt a String in java

Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.

I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.

If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.

div inside table

It is allow as TD can contain inline- AND block-elements.

Here you can find it in the reference: http://xhtml.com/en/xhtml/reference/td/#td-contains

How do I get my C# program to sleep for 50 msec?

Best of both worlds:

using System.Runtime.InteropServices;

    [DllImport("winmm.dll", EntryPoint = "timeBeginPeriod", SetLastError = true)]
    private static extern uint TimeBeginPeriod(uint uMilliseconds);

    [DllImport("winmm.dll", EntryPoint = "timeEndPeriod", SetLastError = true)]
    private static extern uint TimeEndPeriod(uint uMilliseconds);
    /**
     * Extremely accurate sleep is needed here to maintain performance so system resolution time is increased
     */
    private void accurateSleep(int milliseconds)
    {
        //Increase timer resolution from 20 miliseconds to 1 milisecond
        TimeBeginPeriod(1);
        Stopwatch stopwatch = new Stopwatch();//Makes use of QueryPerformanceCounter WIN32 API
        stopwatch.Start();

        while (stopwatch.ElapsedMilliseconds < milliseconds)
        {
            //So we don't burn cpu cycles
            if ((milliseconds - stopwatch.ElapsedMilliseconds) > 20)
            {
                Thread.Sleep(5);
            }
            else
            {
                Thread.Sleep(1);
            }
        }

        stopwatch.Stop();
        //Set it back to normal.
        TimeEndPeriod(1);
    }

How can I get the class name from a C++ object?

Just write simple template:

template<typename T>
const char* getClassName(T) {
  return typeid(T).name();
}

struct A {} a;

void main() {
   std::cout << getClassName(a);
}

Wi-Fi Direct and iOS Support

It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.

Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/index.html

It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."

Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.

There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.

How to use ng-repeat without an html element

<table>
  <tbody>
    <tr><td>{{data[0].foo}}</td></tr>
    <tr ng-repeat="d in data[1]"><td>{{d.bar}}</td></tr>
    <tr ng-repeat="d in data[2]"><td>{{d.lol}}</td></tr>
  </tbody>
</table>

I think that this is valid :)

How to increase Maximum Upload size in cPanel?

On CPanel 64.0.40 (I didn't try any other version): Go in "Software" then "Select PHP Version" then "Switch To PHP Options" then upload_max_filesize => click on the value and select the one you prefer :) It's super hidden for such a critical option...

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

Can I grep only the first n lines of a file?

The output of head -10 file can be piped to grep in order to accomplish this:

head -10 file | grep …

Using Perl:

perl -ne 'last if $. > 10; print if /pattern/' file

How do I disable TextBox using JavaScript?

With the help of jquery it can be done as follows.

$("#color").prop('disabled', true);

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

On docker with image php:7.2-apache I just needed zip and unzip. No need for php-zip :

apt-get install zip unzip

or Dockerfile

RUN ["apt-get", "update"]
RUN ["apt-get", "install", "-y", "zip"]
RUN ["apt-get", "install", "-y", "unzip"]

ngModel cannot be used to register form controls with a parent formGroup directive

OK, finally got it working: see https://github.com/angular/angular/pull/10314#issuecomment-242218563

In brief, you can no longer use name attribute within a formGroup, and must use formControlName instead

Java: Detect duplicates in ArrayList?

If you want the set of duplicate values:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FindDuplicateInArrayList {

    public static void main(String[] args) {

        Set<String> uniqueSet = new HashSet<String>();
        List<String> dupesList = new ArrayList<String>();
        for (String a : args) {
            if (uniqueSet.contains(a))
                dupesList.add(a);
            else
                uniqueSet.add(a);
        }
        System.out.println(uniqueSet.size() + " distinct words: " + uniqueSet);
        System.out.println(dupesList.size() + " dupesList words: " + dupesList);
    }
}

And probably also think about trimming values or using lowercase ... depending on your case.

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

From http://docs.python.org/library/csv.html#csv.writer:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with statement to close the file when you're done writing to it.
Tested example below:

from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
    output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
    output.writerow(dict((fn,fn) for fn in headers))
    output.writerows(rows)

How to enable relation view in phpmyadmin

1 - Change Your tables search engine from 'My ISAM' to 'Inno DB' by Operations tab 2 - you must do this for all tables that you want make relationship between 3 - localhost/phpmyadmin/tbl_relation.php?db=your_database_name&table=your_table_name then replace this url in browser, then you will be able to see the relationship page

C++, copy set to vector

std::copy cannot be used to insert into an empty container. To do that, you need to use an insert_iterator like so:

std::set<double> input;
input.insert(5);
input.insert(6);

std::vector<double> output;
std::copy(input.begin(), input.end(), inserter(output, output.begin())); 

Are 64 bit programs bigger and faster than 32 bit versions?

Any applications that require CPU usage such as transcoding, display performance and media rendering, whether it be audio or visual, will certainly require (at this point) and benefit from using 64 bit versus 32 bit due to the CPU's ability to deal with the sheer amount of data being thrown at it. It's not so much a question of address space as it is the way the data is being dealt with. A 64 bit processor, given 64 bit code, is going to perform better, especially with mathematically difficult things like transcoding and VoIP data - in fact, any sort of 'math' applications should benefit by the usage of 64 bit CPUs and operating systems. Prove me wrong.

How to change the background colour's opacity in CSS

Not too sure to add opacity via CSS is such a good idea.
Opacity has that funny way to be applied to all content and childs from where you set it, with unexpected results in mixed of colours.
It has no really purpose in that case , for a bg color, in my opinion.
If you'd like to lay it hover the bg image, then you may use multiple backgrounds.
this color transparent could be applyed via an extra png repeated (or not with background-position),
CSS gradient (radial-) linear-gradient with rgba colors (starting and ending with same color) can achieve this as well. They are treated as background-image and can be used as filter.
Idem for text, if you want them a bit transparent, use rgba (okay to put text-shadow together).

I think that today, we can drop funny behavior of CSS opacity.

Here is a mixed of rgba used for opacity if you are curious dabblet.com/gist/5685845

How to detect IE11?

I've read your answers and made a mix. It seems to work with Windows XP(IE7/IE8) and Windows 7 (IE9/IE10/IE11).

function ie_ver(){  
    var iev=0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv=navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev=new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
    if (trident&&rv!=-1) iev=11;

    return iev;         
}

Of course if I return 0, means no IE.

Node.js: Python not found exception due to node-sass and node-gyp

node-gyp requires old Python 2 - link

If you don't have it installed - check other answers about installing windows-build-tools.

If you are like me and have both old and new Python versions installed, chances are that node-gyp tries to use Python 3. And that results in the following SyntaxError: invalid syntax error.

I found an article about having two Python versions installed. And they recommend renaming Python 2.* executable to python2.exe - link.

So it looks like node-gyp is expecting to find old Python 2 executable renamed. Hence the error message:

...
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
...

Once I renamed C:\Python27\python.exe to C:\Python27\python2.exe it worked without errors.

Of course, both C:\Python27\ and C:\Python39\ have to be in PATH variable. And no need in setting old Python version in npm config. Your default Python still will be the new one.

Show div on scrollDown after 800px

You've got a few things going on there. One, why a class? Do you actually have multiple of these on the page? The CSS suggests you can't. If not you should use an ID - it's faster to select both in CSS and jQuery:

<div id=bottomMenu>You read it all.</div>

Second you've got a few crazy things going on in that CSS - in particular the z-index is supposed to just be a number, not measured in pixels. It specifies what layer this tag is on, where each higher number is closer to the user (or put another way, on top of/occluding tags with lower z-indexes).

The animation you're trying to do is basically .fadeIn(), so just set the div to display: none; initially and use .fadeIn() to animate it:

$('#bottomMenu').fadeIn(2000);

.fadeIn() works by first doing display: (whatever the proper display property is for the tag), opacity: 0, then gradually ratcheting up the opacity.

Full working example:

http://jsfiddle.net/b9chris/sMyfT/

CSS:

#bottomMenu {
    display: none;
    position: fixed;
    left: 0; bottom: 0;
    width: 100%; height: 60px;
    border-top: 1px solid #000;
    background: #fff;
    z-index: 1;
}

JS:

var $win = $(window);

function checkScroll() {
    if ($win.scrollTop() > 100) {
        $win.off('scroll', checkScroll);
        $('#bottomMenu').fadeIn(2000);
    }
}

$win.scroll(checkScroll);

PHP how to get local IP of system

$_SERVER['SERVER_ADDR']

Kill python interpeter in linux from the terminal

There's a rather crude way of doing this, but be careful because first, this relies on python interpreter process identifying themselves as python, and second, it has the concomitant effect of also killing any other processes identified by that name.

In short, you can kill all python interpreters by typing this into your shell (make sure you read the caveats above!):

ps aux | grep python | grep -v "grep python" | awk '{print $2}' | xargs kill -9

To break this down, this is how it works. The first bit, ps aux | grep python | grep -v "grep python", gets the list of all processes calling themselves python, with the grep -v making sure that the grep command you just ran isn't also included in the output. Next, we use awk to get the second column of the output, which has the process ID's. Finally, these processes are all (rather unceremoniously) killed by supplying each of them with kill -9.

Why does python use 'else' after for and while loops?

I read it like "When the iterable is exhausted completely, and the execution is about to proceed to the next statement after finishing the for, the else clause will be executed." Thus, when the iteration is broken by break, this will not be executed.

PowerShell: Run command from script's directory

I made a one-liner out of @JohnL's solution:

$MyInvocation.MyCommand.Path | Split-Path | Push-Location

Cannot construct instance of - Jackson

You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-

  @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({ 
      @Type(value = Bike.class, name = "bike"), 
      @Type(value = Auto.class, name = "auto"), 
      @Type(value = Car.class, name = "car")
    })
    public abstract class Vehicle {
        // fields, constructors, getters, setters
    }

Case Insensitive String comp in C

As others have stated, there is no portable function that works on all systems. You can partially circumvent this with simple ifdef:

#include <stdio.h>

#ifdef _WIN32
#include <string.h>
#define strcasecmp _stricmp
#else // assuming POSIX or BSD compliant system
#include <strings.h>
#endif

int main() {
    printf("%d", strcasecmp("teSt", "TEst"));
}

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

How to compile LEX/YACC files on Windows?

Go for the full installation of Git for windows (with Unix tool), and bison and flex would come with it in the bin folder.

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

How to write and save html file in python?

You can try:

colour = ["red", "red", "green", "yellow"]

with open('mypage.html', 'w') as myFile:
    myFile.write('<html>')
    myFile.write('<body>')
    myFile.write('<table>')

    s = '1234567890'
    for i in range(0, len(s), 60):
        myFile.write('<tr><td>%04d</td>' % (i+1));
    for j, k in enumerate(s[i:i+60]):
        myFile.write('<td><font style="background-color:%s;">%s<font></td>' % (colour[j %len(colour)], k));


    myFile.write('</tr>')
    myFile.write('</table>')
    myFile.write('</body>')
    myFile.write('</html>')

Removing double quotes from variables in batch file creates problems with CMD environment

The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files

SET xyz=%~1

Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).

But, This simple tilde syntax will not work for other variables that were not passed in as parameters

For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.

@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%

If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows

@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%

Can't install gems on OS X "El Capitan"

You might have two options:

  1. If you've installed ruby and rails, you can first try running the command:
    rvm fix-permissions 
    
  2. You can uninstall ruby completely, and reinstall in your ~ directory aka your home directory.

If you're using homebrew the command is:

brew uninstall ruby

For rails uninstall without homebrew the command is:

rvm remove

This should reinstall the latest ruby by running command:

curl -L https://get.rvm.io | bash -s stable --rails<br>

Mac has 2.6.3 factory installed, and it's required... if not run this command:

rvm install "ruby-2.6.3"

and then:

gem install rails

You'll get a few error messages at the end saying you have to add some other bundles...
Just make sure you're in the home ~ directory when you're installing so the permissions won't be an issue, but just in case...

I again ran:

rvm fix-permissions

and:

rvm debug

which told me I had to download yarn, I didn't save the output for it. Basically I did whatever the prompt told me to do if it had to do with my OS.

-D

How to style the UL list to a single line

in bootstrap use .list-inline css class

<ul class="list-inline">
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>

Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

Open up your build.gradle file located here:

enter image description here

This is the old way of writing the dependency libraries (for gradle version 2 and below):

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile files('libs/volley.jar')
    compile 'com.android.support:support-v4:21.+'
}

This is the new (right) way of importing the dependencies for gradle version 3:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.12'
    implementation files('libs/volley.jar')
    implementation 'com.android.support:support-v4:21.+'
}

How can I remove specific rules from iptables?

You can also use the following syntax

 iptables -D <chain name> <rule number>

For example

Chain HTTPS 
    target     prot opt source               destination
    ACCEPT     all  --  anywhere             anywhere
    ACCEPT     all  --  10.0.0.0/8           anywhere
    ACCEPT     all  --  182.162.0.0/16       anywhere

To delete the rule

ACCEPT all -- 10.0.0.0/8 anywhere

iptables -D HTTPS 2

AngularJS directive does not update on scope variable changes

I know this an old subject but in case any finds this like myself:

I used the following code when i needed my directive to update values when the "parent scope" updated. Please by all means correct me if am doing something wrong as i am still learning angular, but this did what i needed;

directive:

directive('dateRangePrint', function(){
    return {
        restrict: 'E',
        scope:{
        //still using the single dir binding
            From: '@rangeFrom',
            To: '@rangeTo',
            format: '@format'
        },
        controller: function($scope, $element){

            $scope.viewFrom = function(){
                    return formatDate($scope.From, $scope.format);
                }

            $scope.viewTo = function(){
                    return formatDate($scope.To, $scope.format);
                }

            function formatDate(date, format){
                format = format || 'DD-MM-YYYY';

                //do stuff to date...

                return date.format(format);
            }

        },
        replace: true,
        // note the parenthesis after scope var
        template: '<span>{{ viewFrom() }} - {{ viewTo() }}</span>'
    }
})

How to remove multiple indexes from a list at the same time?

Old question, but I have an answer.

First, peruse the elements of the list like so:

for x in range(len(yourlist)):
    print '%s: %s' % (x, yourlist[x])

Then, call this function with a list of the indexes of elements you want to pop. It's robust enough that the order of the list doesn't matter.

def multipop(yourlist, itemstopop):
    result = []
    itemstopop.sort()
    itemstopop = itemstopop[::-1]
    for x in itemstopop:
        result.append(yourlist.pop(x))
    return result

As a bonus, result should only contain elements you wanted to remove.

In [73]: mylist = ['a','b','c','d','charles']

In [76]: for x in range(len(mylist)):

      mylist[x])

....:

0: a

1: b

2: c

3: d

4: charles

...

In [77]: multipop(mylist, [0, 2, 4])

Out[77]: ['charles', 'c', 'a']

...

In [78]: mylist

Out[78]: ['b', 'd']

Using context in a fragment

getContext() came in API 23. Replace it with getActivity() everywhere in the code.

See if it fixes the error. Try to use methods which are in between the target and minimun API level, else this error will come in place.

Difference between Git and GitHub

In plain English:

  1. They are all source control as we all know.
  2. In an analogy, if Git is a standalone computer, then GitHub is a network of computers connected by web with bells and whistlers.
  3. So unless you open a GitHub acct and specifically tell VSC or any editor to use GitHub, you'll see your source code up-there otherwise they are only down here, - your local machine.

How to create a custom-shaped bitmap marker with Android map API v2

The alternative and easier solution that i also use is to create custom marker layout and convert it into a bitmap.

view_custom_marker.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_marker_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/marker_mask">

    <ImageView
        android:id="@+id/profile_image"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="center_horizontal"
        android:contentDescription="@null"
        android:src="@drawable/avatar" />
</FrameLayout>

Convert this view into bitmap by using the code below

 private Bitmap getMarkerBitmapFromView(@DrawableRes int resId) {

        View customMarkerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_custom_marker, null);
        ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.profile_image);
        markerImageView.setImageResource(resId);
        customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
        customMarkerView.buildDrawingCache();
        Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
        Drawable drawable = customMarkerView.getBackground();
        if (drawable != null)
            drawable.draw(canvas);
        customMarkerView.draw(canvas);
        return returnedBitmap;
    }

Add your custom marker in on Map ready callback.

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d(TAG, "onMapReady() called with");
    mGoogleMap = googleMap;
    MapsInitializer.initialize(this);
    addCustomMarker();
}
private void addCustomMarker() {
    Log.d(TAG, "addCustomMarker()");
    if (mGoogleMap == null) {
        return;
    }

    // adding a marker on map with image from  drawable
   mGoogleMap.addMarker(new MarkerOptions()
            .position(mDummyLatLng)
            .icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(R.drawable.avatar))));
}

For more details please follow the link below

How to create custom marker using layout?

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.