Programs & Examples On #C# to f#

This tag topic is about converting C# code to F#, or learning F# from the perspective of someone with C# background.

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

Getting an attribute value in xml element

Below is the code to do it in vtd-xml. It basically queries the XML with the XPath of "/xml/item/@name."

import com.ximpleware.*;

public class getAttrs{

   public static void main(String[] s) throws VTDException{
         VTDGen vg = new VTDGen();
         if (!vg.parseFile("input.xml",false)) // turn off namespace
              return;
         VTDNav vn = vg.getNav();
         AutoPilot ap =  new AutoPilot(vn);
         ap.selectXPath("/xml/item/@name");
         int i=0;
         while( (i=ap.evalXPath())!=-1){
              System.out.println(" item name is ===>"+vn.toString(i+1)); 
         }
   }
}

Sublime Text 2 Code Formatting

A similar option in Sublime Text is the built in Edit->Line->Reindent. You can put this code in Preferences -> Key Bindings User:

{ "keys": ["alt+shift+f"], "command": "reindent"} 

I use alt+shift+f because I'm a Netbeans user.

To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.


Or if you don't want to select all before formatting, add an argument to the command instead:

{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }

(as per comment by @Supr below)

How to remove a newline from a string in Bash

If you are using bash with the extglob option enabled, you can remove just the trailing whitespace via:

shopt -s extglob
COMMAND=$'\nRE BOOT\r   \n'
echo "|${COMMAND%%*([$'\t\r\n '])}|"

This outputs:

|
RE BOOT|

Or replace %% with ## to replace just the leading whitespace.

Create multiple threads and wait all of them to complete

In .NET 4.0, you can use the Task Parallel Library.

In earlier versions, you can create a list of Thread objects in a loop, calling Start on each one, and then make another loop and call Join on each one.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Just delete these lines from the root build.gradle

android {
compileSdkVersion 19
buildToolsVersion '19.1' }

Now trying and compile again. It should work.

How to get the size of a string in Python?

Python 3:

user225312's answer is correct:

A. To count number of characters in str object, you can use len() function:

>>> print(len('please anwser my question'))
25

B. To get memory size in bytes allocated to store str object, you can use sys.getsizeof() function

>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50

Python 2:

It gets complicated for Python 2.

A. The len() function in Python 2 returns count of bytes allocated to store encoded characters in a str object.

Sometimes it will be equal to character count:

>>> print(len('abc'))
3

But sometimes, it won't:

>>> print(len('???'))  # String contains Cyrillic symbols
6

That's because str can use variable-length encoding internally. So, to count characters in str you should know which encoding your str object is using. Then you can convert it to unicode object and get character count:

>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols 
3

B. The sys.getsizeof() function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object

>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32

Rails: Adding an index after adding column

For references you can call

rails generate migration AddUserIdColumnToTable user:references

If in the future you need to add a general index you can launch this

rails g migration AddOrdinationNumberToTable ordination_number:integer:index

Generate code:

class AddOrdinationNumberToTable < ActiveRecord::Migration
  def change
   add_column :tables, :ordination_number, :integer
   add_index :tables, :ordination_number, unique: true
  end
end

How to know a Pod's own IP address from inside a container in the Pod?

The container's IP address should be properly configured inside of its network namespace, so any of the standard linux tools can get it. For example, try ifconfig, ip addr show, hostname -I, etc. from an attached shell within one of your containers to test it out.

How can I align the columns of tables in Bash?

It's easier than you wonder.

If you are working with a separated by semicolon file and header too:

$ (head -n1 file.csv && sort file.csv | grep -v <header>) | column -s";" -t

If you are working with array (using tab as separator):

for((i=0;i<array_size;i++));
do

   echo stringarray[$i] $'\t' numberarray[$i] $'\t' anotherfieldarray[$i] >> tmp_file.csv

done;

cat file.csv | column -t

How to position a DIV in a specific coordinates?

Script its left and top properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;

var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';

Or do it as a function so you can attach it to an event like onmousedown

function placeDiv(x_pos, y_pos) {
  var d = document.getElementById('yourDivId');
  d.style.position = "absolute";
  d.style.left = x_pos+'px';
  d.style.top = y_pos+'px';
}

How to style a checkbox using CSS

I'd follow the advice of SW4's answer – to hide the checkbox and to cover it with a custom span, suggesting this HTML:

<label>
  <input type="checkbox">
  <span>send newsletter</span>
</label>

The wrap in label neatly allows clicking the text without the need of "for-id" attribute linking. However,

Do not hide it using visibility: hidden or display: none

It works by clicking or tapping, but that is a lame way to use checkboxes. Some people still use much more effective Tab to move focus, Space to activate, and hiding with that method disables it. If the form is long, one will save someone's wrists to use tabindex or accesskey attributes. And if you observe the system checkbox behavior, there is a decent shadow on hover. The well styled checkbox should follow this behavior.

cobberboy's answer recommends Font Awesome which is usually better than bitmap since fonts are scalable vectors. Working with the HTML above, I'd suggest these CSS rules:

  1. Hide checkboxes

     input[type="checkbox"] {
       position: absolute;
       opacity: 0;
       z-index: -1;
     }
    

    I use just negative z-index since my example uses big enough checkbox skin to cover it fully. I don't recommend left: -999px since it is not reusable in every layout. Bushan wagh's answer provides a bulletproof way to hide it and convince the browser to use tabindex, so it is a good alternative. Anyway, both is just a hack. The proper way today is appearance: none, see Joost's answer:

     input[type="checkbox"] {
       appearance: none;
       -webkit-appearance: none;
       -moz-appearance: none;
     }
    
  2. Style checkbox label

     input[type="checkbox"] + span {
       font: 16pt sans-serif;
       color: #000;
     }
    
  3. Add checkbox skin

     input[type="checkbox"] + span:before {
       font: 16pt FontAwesome;
       content: '\00f096';
       display: inline-block;
       width: 16pt;
       padding: 2px 0 0 3px;
       margin-right: 0.5em;
     }
    

\00f096 is Font Awesome's square-o, padding is adjusted to provide even dotted outline on focus (see below).

  1. Add checkbox checked skin

     input[type="checkbox"]:checked + span:before {
       content: '\00f046';
     }
    

\00f046 is Font Awesome's check-square-o, which is not the same width as square-o, which is the reason for the width style above.

  1. Add focus outline

     input[type="checkbox"]:focus + span:before {
       outline: 1px dotted #aaa;
     }
    

    Safari doesn't provide this feature (see @Jason Sankey's comment), see this answer for Safari-only CSS

  2. Set gray color for disabled checkbox

     input[type="checkbox"]:disabled + span {
       color: #999;
     }
    
  3. Set hover shadow on non-disabled checkbox

     input[type="checkbox"]:not(:disabled) + span:hover:before {
       text-shadow: 0 1px 2px #77F;
     }
    

Test it on JS Fiddle

Try to hover the mouse over the checkboxes and use Tab and Shift+Tab to move and Space to toggle.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

A quick answer, that doesn't require you to edit any configuration files (and works on other operating systems as well as Windows), is to just find the directory that you are allowed to save to using:

mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-----------------------+
| Variable_name    | Value                 |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+
1 row in set (0.06 sec)

And then make sure you use that directory in your SELECT statement's INTO OUTFILE clause:

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Original answer

I've had the same problem since upgrading from MySQL 5.6.25 to 5.6.26.

In my case (on Windows), looking at the MySQL56 Windows service shows me that the options/settings file that is being used when the service starts is C:\ProgramData\MySQL\MySQL Server 5.6\my.ini

On linux the two most common locations are /etc/my.cnf or /etc/mysql/my.cnf.

MySQL56 Service

Opening this file I can see that the secure-file-priv option has been added under the [mysqld] group in this new version of MySQL Server with a default value:

secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.6/Uploads"

You could comment this (if you're in a non-production environment), or experiment with changing the setting (recently I had to set secure-file-priv = "" in order to disable the default). Don't forget to restart the service after making changes.

Alternatively, you could try saving your output into the permitted folder (the location may vary depending on your installation):

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

It's more common to have comma seperate values using FIELDS TERMINATED BY ','. See below for an example (also showing a Linux path):

SELECT *
FROM table
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    ESCAPED BY ''
    LINES TERMINATED BY '\n';

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

Google Play on Android 4.0 emulator


Playstore + Google Play Services In Linux(Ubuntu 14.04)


Download Google apps (GoogleLoginService.apk , GoogleServicesFramework.apk )

from here http://www.securitylearn.net/2013/08/31/google-play-store-on-android-emulator/

and Download ( Phonesky.apk) from here https://basketbuild.com/filedl/devs?dev=dankoman&dl=dankoman/Phonesky.apk

GO TO ANDROID SDK LOCATION>>

cd -Android SDK's tools Location-

TO RUN EMULATOR>>

Android/Sdk/tools$ ./emulator64-x86 -avd Kitkat -partition-size 566 -no-audio -no-boot-anim

SET PERMISSIONS>>

cd Android/Sdk/platform-tools platform-tools$ adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system

platform-tools$ adb shell chmod 777 /system/app

platform-tools$ adb push /home/nazmul/Downloads/GoogleLoginService.apk /system/app/.

PUSH PLAY APKS >>

platform-tools$ adb push /home/nazmul/Downloads/GoogleServicesFramework.apk /system/app/. platform-tools$ adb push /home/nazmul/Downloads/Phonesky.apk /system/app/. platform-tools$ adb shell rm /system/app/SdkSetup*

make an html svg object also a clickable link

i tried this clean easy method and seems to work in all browsers. Inside the svg file:

_x000D_
_x000D_
<svg>_x000D_
<a id="anchor" xlink:href="http://www.google.com" target="_top">_x000D_
  _x000D_
<!--your graphic-->_x000D_
  _x000D_
</a>_x000D_
</svg>_x000D_
  
_x000D_
_x000D_
_x000D_

When to use window.opener / window.parent / window.top

when you are dealing with popups window.opener plays an important role, because we have to deal with fields of parent page as well as child page, when we have to use values on parent page we can use window.opener or we want some data on the child window or popup window at the time of loading then again we can set the values using window.opener

XAMPP on Windows - Apache not starting

I know this is somewhat of an old topic, but in case anyone reads this in the future...

I uninstalled xampp, deleted everything under the c:\xampp folder, then reinstalled xampp as administrator and it worked like a charm.

How do I create a table based on another table

select * into newtable from oldtable

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

is python capable of running on multiple cores?

CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.

Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.

The usual recommendation is to use many processes rather than many threads.

Remove Duplicates from range of cells in excel vba

If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:

 Sub norepeat()

    Range("C8:C16").RemoveDuplicates (1)

End Sub

Regards

PHP mysql insert date format

You must make sure that the date format is YYYY-MM-DD on your jQuery output. I can see jQuery returns MM-DD-YYYY, which is not the valid MySQL date format and this is why it returns an error.

To convert it to the right one you could do this:

$dateFormated = split('/', $date);
$date = $dateFormated[2].'-'.$dateFormated[0].'-'.$dateFormated[1];

Then you will get formatted date that will be valid MySQL format, which is YYYY-MM-DD, i.e. 2012-08-25

I would also recommend using mysql_real_escape_string as you insert data into database to prevent SQL injections as a quick solution or better use PDO or MySQLi.

Your insert query using mysql_real_escape_string should rather look like this:

$sql = mysql_query( "INSERT INTO user_date VALUE( '', '" .mysql_real_escape_string($name). "', '" .mysql_real_escape_string($date). "'" ) or die ( mysql_error() );

How much faster is C++ than C#?

The garbage collection is the main reason Java# CANNOT be used for real-time systems.

  1. When will the GC happen?

  2. How long will it take?

This is non-deterministic.

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

Why are iframes considered dangerous and a security risk?

The IFRAME element may be a security risk if your site is embedded inside an IFRAME on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe> or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY and hope that the browser knows its job.

In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe> on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).

That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.

If somebody claims that using an <iframe> element on your site is dangerous and causes a security risk, he does not understand what <iframe> element does, or he is speaking about possibility of <iframe> related vulnerabilities in browsers. Security of <iframe src="..."> tag is equal to <img src="..." or <a href="..."> as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>, <img> or <a> element, so it's not worth considering for this issue.

However, be warned that content from <iframe> can initiate top level navigation by default. That is, content within the <iframe> is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox attribute without value allow-top-navigation. For example, <iframe sandbox="allow-forms allow-scripts" ...>. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.

Note that X-Frame-Options: DENY also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").

Update Rows in SSIS OLEDB Destination

You can't do a bulk-update in SSIS within a dataflow task with the OOB components.

The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.

Stage data

http://www.sqlservercentral.com/Images/11369.png

Set based updates

enter image description here

You'll get much better performance with a pattern like this versus using the OLE DB Command transformation for anything but trivial amounts of data.

If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.

SQLDataReader Row Count

Maybe you can try this: though please note - This pulls the column count, not the row count

 using (SqlDataReader reader = command.ExecuteReader())
 {
     while (reader.Read())
     {
         int count = reader.VisibleFieldCount;
         Console.WriteLine(count);
     }
 }

how to disable DIV element and everything inside

I think inline scripts are hard to stop instead you can try with this:

<div id="test">
    <div>Click Me</div>
</div>

and script:

$(function () {
    $('#test').children().click(function(){
      alert('hello');
    });
    $('#test').children().off('click');
});

CHEKOUT FIDDLE AND SEE IT HELPS

Read More about .off()

How to synchronize a static variable among threads running different instances of a class in Java?

There are several ways to synchronize access to a static variable.

  1. Use a synchronized static method. This synchronizes on the class object.

    public class Test {
        private static int count = 0;
    
        public static synchronized void incrementCount() {
            count++;
        }
    } 
    
  2. Explicitly synchronize on the class object.

    public class Test {
        private static int count = 0;
    
        public void incrementCount() {
            synchronized (Test.class) {
                count++;
            }
        }
    } 
    
  3. Synchronize on some other static object.

    public class Test {
        private static int count = 0;
        private static final Object countLock = new Object();
    
        public void incrementCount() {
            synchronized (countLock) {
                count++;
            }
        }
    } 
    

Method 3 is the best in many cases because the lock object is not exposed outside of your class.

How to check if an object is a list or tuple (but not string)?

I find such a function named is_sequence in tensorflow.

def is_sequence(seq):
  """Returns a true if its input is a collections.Sequence (except strings).
  Args:
    seq: an input sequence.
  Returns:
    True if the sequence is a not a string and is a collections.Sequence.
  """
  return (isinstance(seq, collections.Sequence)
and not isinstance(seq, six.string_types))

And I have verified that it meets your needs.

AngularJS: How do I manually set input to $valid in controller?

to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.

delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);

Escape double quotes for JSON in Python

>>> s = 'my string with \\"double quotes\\" blablabla'
>>> s
'my string with \\"double quotes\\" blablabla'
>>> print s
my string with \"double quotes\" blablabla
>>> 

When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...

>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>> 

Debugging "Element is not clickable at point" error

The reason for this error is that the element that you are trying to click is not in the viewport (region seen by the user) of the browser. So the way to overcome this is by scrolling to the desired element first and then performing the click.

Javascript:

async scrollTo (webElement) {
    await this.driver.executeScript('arguments[0].scrollIntoView(true)', webElement)
    await this.driver.executeScript('window.scrollBy(0,-150)')
}

Java:

public void scrollTo (WebElement e) {
    JavascriptExecutor js = (JavascriptExecutor) driver; 
    js.executeAsyncScript('arguments[0].scrollIntoView(true)', e)
    js.executeAsyncScript('window.scrollBy(0,-150)')
}

Read a javascript cookie by name

Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)

var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';

function safeGetCookie() {
    try {
        return document.cookie || '';
    } catch (e) {
        return '';
    }
}

function safeDecodeURIComponent(str) {
    try {
        return decodeURIComponent(str);
    } catch (e) {
        return str;
    }
}

function isUndefined(value) {
    return typeof value === 'undefined';
}

return function () {
    var cookieArray, cookie, i, index, name;
    var currentCookieString = safeGetCookie();

    if (currentCookieString !== lastCookieString) {
        lastCookieString = currentCookieString;
        cookieArray = lastCookieString.split('; ');
        lastCookies = {};

        for (i = 0; i < cookieArray.length; i++) {
            cookie = cookieArray[i];
            index = cookie.indexOf('=');
            if (index > 0) { //ignore nameless cookies
                name = safeDecodeURIComponent(cookie.substring(0, index));

                if (isUndefined(lastCookies[name])) {
                    lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
                }
            }
        }
    }
    return lastCookies;
};
})();

How can I print out just the index of a pandas dataframe?

You can access the index attribute of a df using .index:

In [277]:

df = pd.DataFrame({'a':np.arange(10), 'b':np.random.randn(10)})
df
Out[277]:
   a         b
0  0  0.293422
1  1 -1.631018
2  2  0.065344
3  3 -0.417926
4  4  1.925325
5  5  0.167545
6  6 -0.988941
7  7 -0.277446
8  8  1.426912
9  9 -0.114189
In [278]:

df.index
Out[278]:
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

MAX(DATE) - SQL ORACLE

Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:

SELECT
  max(MEMBSHIP_ID)
  keep (
      dense_rank first
      order by paym_date desc NULLS LAST
  ) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1

Configuration with name 'default' not found. Android Studio

compile fileTree(dir: 'libraries', include: ['Android-Bootstrap'])

Use above line in your app's gradle file instead of

compile project (':libraries:Android-Bootstrap')

Extract substring using regexp in plain bash

Quick 'n dirty, regex-free, low-robustness chop-chop technique

string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"

Two divs side by side - Fluid display

Here's my answer for those that are Googling:

CSS:

.column {
    float: left;
    width: 50%;
}

/* Clear floats after the columns */
.container:after {
    content: "";
    display: table;
    clear: both;
}

Here's the HTML:

<div class="container">
    <div class="column"></div>
    <div class="column"></div>
</div>

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

Why doesn't java.util.Set have get(int index)?

Because sets have no ordering. Some implementations do (particularly those implementing the java.util.SortedSet interface), but that is not a general property of sets.

If you're trying to use sets this way, you should consider using a list instead.

How can I search (case-insensitive) in a column using LIKE wildcard?

SELECT  *
FROM    trees
WHERE   trees.`title` COLLATE UTF8_GENERAL_CI LIKE '%elm%'

Actually, if you add COLLATE UTF8_GENERAL_CI to your column's definition, you can just omit all these tricks: it will work automatically.

ALTER TABLE trees 
 MODIFY COLUMN title VARCHAR(…) CHARACTER 
 SET UTF8 COLLATE UTF8_GENERAL_CI. 

This will also rebuild any indexes on this column so that they could be used for the queries without leading '%'

Extracting .jar file with command line

Note that a jar file is a Zip file, and any Zip tool (such as 7-Zip) can look inside the jar.

Calling Java from Python

You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:

from py4j.java_gateway import JavaGateway
gateway = JavaGateway()                        # connect to the JVM
java_object = gateway.jvm.mypackage.MyClass()  # invoke constructor
other_object = java_object.doThat()
other_object.doThis(1,'abc')
gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.

The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)

Disclaimer: I am the author of Py4J

Detecting EOF in C

Another issue is that you're reading with scanf("%f", &input); only. If the user types something that can't be interpreted as a C floating-point number, like "pi", the scanf() call will not assign anything to input, and won't progress from there. This means it would attempt to keep reading "pi", and failing.

Given the change to while(!feof(stdin)) which other posters are correctly recommending, if you typed "pi" in there would be an endless loop of printing out the former value of input and printing the prompt, but the program would never process any new input.

scanf() returns the number of assignments to input variables it made. If it made no assignment, that means it didn't find a floating-point number, and you should read through more input with something like char string[100];scanf("%99s", string);. This will remove the next string from the input stream (up to 99 characters, anyway - the extra char is for the null terminator on the string).

You know, this is reminding me of all the reasons I hate scanf(), and why I use fgets() instead and then maybe parse it using sscanf().

See last changes in svn

You could use CommitMonitor. This little tool uses very little RAM and notifies you of all the commits you've missed.

Global variables in header file

Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol ....link :http://csapp.cs.cmu.edu/public/ch7-preview.pdf

This type of code create problem while porting.

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'

Stop recording and you can start inspecting your code.

I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"

Option Explicit

Sub SaveFile()

Dim fdate As Date
Dim fname As String
Dim path As String

fdate = Range("A1").Value
path = Application.ActiveWorkbook.path

If fdate > 0 Then
    fname = "Event " & fdate
    Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
    MsgBox "Chose a date for the event", vbOKOnly
End If

End Sub

Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!

How to format a duration in java? (e.g format H:MM:SS)

How about the following function, which returns either +H:MM:SS or +H:MM:SS.sss

public static String formatInterval(final long interval, boolean millisecs )
{
    final long hr = TimeUnit.MILLISECONDS.toHours(interval);
    final long min = TimeUnit.MILLISECONDS.toMinutes(interval) %60;
    final long sec = TimeUnit.MILLISECONDS.toSeconds(interval) %60;
    final long ms = TimeUnit.MILLISECONDS.toMillis(interval) %1000;
    if( millisecs ) {
        return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms);
    } else {
        return String.format("%02d:%02d:%02d", hr, min, sec );
    }
}

Create Table from JSON Data with angularjs and ng-repeat

Easy way to use for create dynamic header and cell in normal table :

<table width="100%" class="table">
 <thead>
  <tr>
   <th ng-repeat="(header, value) in MyRecCollection[0]">{{header}}</th>
  </tr>
 </thead>
 <tbody>
  <tr ng-repeat="row in MyRecCollection | filter:searchText">
   <td ng-repeat="cell in row">{{cell}}</td>
  </tr>
 </tbody>
</table>

MyApp.controller('dataShow', function ($scope, $http) {
    //$scope.gridheader = ['Name','City','Country']
        $http.get('http://www.w3schools.com/website/Customers_MYSQL.php').success(function (data) {

                $scope.MyRecCollection = data;
        })

        });

JSON Data :

[{
    "Name": "Alfreds Futterkiste",
    "City": "Berlin",
    "Country": "Germany"
}, {
    "Name": "Berglunds snabbköp",
    "City": "Luleå",
    "Country": "Sweden"
}, {
    "Name": "Centro comercial Moctezuma",
    "City": "México D.F.",
    "Country": "Mexico"
}, {
    "Name": "Ernst Handel",
    "City": "Graz",
    "Country": "Austria"
}, {
    "Name": "FISSA Fabrica Inter. Salchichas S.A.",
    "City": "Madrid",
    "Country": "Spain"
}, {
    "Name": "Galería del gastrónomo",
    "City": "Barcelona",
    "Country": "Spain"
}, {
    "Name": "Island Trading",
    "City": "Cowes",
    "Country": "UK"
}, {
    "Name": "Königlich Essen",
    "City": "Brandenburg",
    "Country": "Germany"
}, {
    "Name": "Laughing Bacchus Wine Cellars",
    "City": "Vancouver",
    "Country": "Canada"
}, {
    "Name": "Magazzini Alimentari Riuniti",
    "City": "Bergamo",
    "Country": "Italy"
}, {
    "Name": "North/South",
    "City": "London",
    "Country": "UK"
}, {
    "Name": "Paris spécialités",
    "City": "Paris",
    "Country": "France"
}, {
    "Name": "Rattlesnake Canyon Grocery",
    "City": "Albuquerque",
    "Country": "USA"
}, {
    "Name": "Simons bistro",
    "City": "København",
    "Country": "Denmark"
}, {
    "Name": "The Big Cheese",
    "City": "Portland",
    "Country": "USA"
}, {
    "Name": "Vaffeljernet",
    "City": "Århus",
    "Country": "Denmark"
}, {
    "Name": "Wolski Zajazd",
    "City": "Warszawa",
    "Country": "Poland"
}]

Laravel 5 call a model function in a blade view

Instead of passing functions or querying it on the controller, I think what you need is relationships on models since these are related tables on your database.

If based on your structure, input_details and products are related you should put relationship definition on your models like this:

public class InputDetail(){
 protected $table = "input_details";
 ....//other code

 public function product(){
   return $this->hasOne('App\Product');
 }
}

then in your view you'll just have to say:

<p>{{ $input_details->product->name }}</p>

More simpler that way. It is also the best practice that controllers should only do business logic for the current resource. For more info on how to do this just go to the docs: https://laravel.com/docs/5.0/eloquent#relationships

Injecting Mockito mocks into a Spring bean

If you're using spring >= 3.0, try using Springs @Configuration annotation to define part of the application context

@Configuration
@ImportResource("com/blah/blurk/rest-of-config.xml")
public class DaoTestConfiguration {

    @Bean
    public ApplicationService applicationService() {
        return mock(ApplicationService.class);
    }

}

If you don't want to use the @ImportResource, it can be done the other way around too:

<beans>
    <!-- rest of your config -->

    <!-- the container recognize this as a Configuration and adds it's beans 
         to the container -->
    <bean class="com.package.DaoTestConfiguration"/>
</beans>

For more information, have a look at spring-framework-reference : Java-based container configuration

MySQL root access from all hosts

MariaDB running on Raspbian - the file containing bind-address is hard to pinpoint. MariaDB have some not-very-helpful-info on the subject.

I used

# sudo grep -R bind-address /etc 

to locate where the damn thing is.

I also had to set the privileges and hosts in the mysql like everyone above pointed out.

And also had some fun time opening the 3306 port for remote connections to my Raspberry Pi - finally used iptables-persistent.

All works great now.

How to add button inside input

This is the cleanest way to do in bootstrap v3.

<div class="form-group">
    <div class="input-group">
        <input type="text" name="search" class="form-control" placeholder="Search">
        <span><button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button></span>
     </div>
</div>

How to see full query from SHOW PROCESSLIST

SHOW FULL PROCESSLIST

If you don't use FULL, "only the first 100 characters of each statement are shown in the Info field".

When using phpMyAdmin, you should also click on the "Full texts" option ("? T ?" on top left corner of a results table) to see untruncated results.

Cannot find Microsoft.Office.Interop Visual Studio

You can find it at link:

C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Word\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Word.dll

Browse it then add references

How do I bottom-align grid elements in bootstrap fluid layout

This is based on cfx's solution, but rather than setting the font size to zero in the parent container to remove the inter-column spaces added because of the display: inline-block and having to reset them, I simply added

_x000D_
_x000D_
.row.row-align-bottom > div {_x000D_
    float: none;_x000D_
    display: inline-block;_x000D_
    vertical-align: bottom;_x000D_
    margin-right: -0.25em;_x000D_
}
_x000D_
_x000D_
_x000D_

to the column divs to compensate.

Change Volley timeout duration

/**
 * @param request
 * @param <T>
 */
public <T> void addToRequestQueue(Request<T> request) {

    request.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    getRequestQueue().add(request);
}

Is there a function in python to split a word into a list?

>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']

Accessing SQL Database in Excel-VBA

Add set nocount on to the beginning of the stored proc (if you're on SQL Server). I just solved this problem in my own work and it was caused by intermediate results, such as "1203 Rows Affected", being loaded into the Recordset I was trying to use.

Programmatically register a broadcast receiver

package com.example.broadcastreceiver;


import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

   UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver();

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

   /**
    * This method enables the Broadcast receiver for
    * "android.intent.action.TIME_TICK" intent. This intent get
    * broadcasted every minute.
    *
    * @param view
    */
   public void registerBroadcastReceiver(View view) {

      this.registerReceiver(broadCastReceiver, new IntentFilter(
            "android.intent.action.TIME_TICK"));
      Toast.makeText(this, "Registered broadcast receiver", Toast.LENGTH_SHORT)
            .show();
   }

   /**
    * This method disables the Broadcast receiver
    *
    * @param view
    */
   public void unregisterBroadcastReceiver(View view) {

      this.unregisterReceiver(broadCastReceiver);

      Toast.makeText(this, "unregistered broadcst receiver", Toast.LENGTH_SHORT)
            .show();
   }
}

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

How to get file path from OpenFileDialog and FolderBrowserDialog?

A primitive quick fix that works.

If you only use OpenFileDialog, you can capture the FileName, SafeFileName, then subtract to get folder path:

exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");

How to run vi on docker container?

The command to run depends on what base image you are using.

For Alpine, vi is installed as part of the base OS. Installing vim would be:

apk -U add vim

For Debian and Ubuntu:

apt-get update && apt-get install -y vim

For CentOS, vi is usually installed with the base OS. For vim:

yum install -y vim

This should only be done in early development. Once you get a working container, the changes to files should be made to your image or configs stored outside of your container. Update your Dockerfile and other files it uses to build a new image. This certainly shouldn't be done in production since changes inside the container are by design ephemeral and will be lost when the container is replaced.

Select from multiple tables without a join?

Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join.
In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.

select 
   (
   select s.state_name from state s where s.state_id=3
   ) statename,
   (
   select c.description from country c where c.id=5
   ) countryname
   from dual;   

where dual is a dummy table with single column--anything just require table to view

Proper way to declare custom exceptions in modern Python?

You should override __repr__ or __unicode__ methods instead of using message, the args you provide when you construct the exception will be in the args attribute of the exception object.

How does Tomcat locate the webapps directory?

Change appBase in server.xml

If you want to keep both previous webapps and a new one, you can use another Host instance with another port defined in tomcat.

Absolute and Flexbox in React Native

The first step would be to add

position: 'absolute',

then if you want the element full width, add

left: 0,
right: 0,

then, if you want to put the element in the bottom, add

bottom: 0,
// don't need set top: 0

if you want to position the element at the top, replace bottom: 0 by top: 0

How to Access Hive via Python?

Simplest method | Using sqlalchemy

Requirements:

  • pip install pyhive

Code:

import pandas as pd
from sqlalchemy import create_engine

SECRET = {'username':'lol', 'password': 'lol'}
user_name = SECRET.get('username')
passwd = SECRET.get('password')

host_server = 'x.x.x.x'
port = '10000'
database = 'default'
conn = f'hive://{user_name}:{passwd}@{host_server}:{port}/{database}'
engine = create_engine(conn, connect_args={'auth': 'LDAP'})

query = "select * from tablename limit 100"
data = pd.read_sql(query, con=engine)
print(data)

Java get last element of a collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement = itr.next();
    }
    return lastElement;
}

How to move div vertically down using CSS

Try this configuration:

    position to absolute
    width to 100%
    height to 100px
    bottom to 10
    background-color: blue

This can help actually move the div to the bottom. Just modify accordingly.

ASP.NET Web Site or ASP.NET Web Application?

From the MCTS self paced training kit exam 70-515 book:

With web application (project),

  1. You can create an MVC application.
  2. Visual Studio stores the list of files in a project file (.csproj or .vbproj), rather than relying on the folder structure.
  3. You cannot mix Visual Basic and C#.
  4. You cannot edit code without stopping a debugging session.
  5. You can establish dependencies between multiple web projects.
  6. You must compile the application before deployment, which prevents you from testing a page if another page will not compile.
  7. You do not have to store the source code on the server.
  8. You can control the assembly name and version.
  9. You cannot edit individual files after deployment without recompiling.

Difference between declaring variables before or in loop?

It depends on the language and the exact use. For instance, in C# 1 it made no difference. In C# 2, if the local variable is captured by an anonymous method (or lambda expression in C# 3) it can make a very signficant difference.

Example:

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        List<Action> actions = new List<Action>();

        int outer;
        for (int i=0; i < 10; i++)
        {
            outer = i;
            int inner = i;
            actions.Add(() => Console.WriteLine("Inner={0}, Outer={1}", inner, outer));
        }

        foreach (Action action in actions)
        {
            action();
        }
    }
}

Output:

Inner=0, Outer=9
Inner=1, Outer=9
Inner=2, Outer=9
Inner=3, Outer=9
Inner=4, Outer=9
Inner=5, Outer=9
Inner=6, Outer=9
Inner=7, Outer=9
Inner=8, Outer=9
Inner=9, Outer=9

The difference is that all of the actions capture the same outer variable, but each has its own separate inner variable.

How do I pass parameters into a PHP script through a webpage?

Presumably you're passing the arguments in on the command line as follows:

php /path/to/wwwpublic/path/to/script.php arg1 arg2

... and then accessing them in the script thusly:

<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>

What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:

Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2

... and access:

<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>

If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:

<?php
if (PHP_SAPI === 'cli') {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
else {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
}
?>

PostgreSQL create table if not exists

I created a generic solution out of the existing answers which can be reused for any table:

CREATE OR REPLACE FUNCTION create_if_not_exists (table_name text, create_stmt text)
RETURNS text AS
$_$
BEGIN

IF EXISTS (
    SELECT *
    FROM   pg_catalog.pg_tables 
    WHERE    tablename  = table_name
    ) THEN
   RETURN 'TABLE ' || '''' || table_name || '''' || ' ALREADY EXISTS';
ELSE
   EXECUTE create_stmt;
   RETURN 'CREATED';
END IF;

END;
$_$ LANGUAGE plpgsql;

Usage:

select create_if_not_exists('my_table', 'CREATE TABLE my_table (id integer NOT NULL);');

It could be simplified further to take just one parameter if one would extract the table name out of the query parameter. Also I left out the schemas.

Grant execute permission for a user on all stored procedures in database?

use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE

USE <database_name> 
select 'GRANT EXECUTE ON ['+name+'] TO [userName]  '  
from sys.objects  
where type ='P' 
and is_ms_shipped = 0  

Convert pem key to ssh-rsa format

FWIW, this BASH script will take a PEM- or DER-format X.509 certificate or OpenSSL public key file (also PEM format) as the first argument and disgorge an OpenSSH RSA public key. This expands upon @mkalkov's answer above. Requirements are cat, grep, tr, dd, xxd, sed, xargs, file, uuidgen, base64, openssl (1.0+), and of course bash. All except openssl (contains base64) are pretty much guaranteed to be part of the base install on any modern Linux system, except maybe xxd (which Fedora shows in the vim-common package). If anyone wants to clean it up and make it nicer, caveat lector.

#!/bin/bash
#
# Extract a valid SSH format public key from an X509 public certificate.
#

# Variables:
pubFile=$1
fileType="no"
pkEightTypeFile="$pubFile"
tmpFile="/tmp/`uuidgen`-pkEightTypeFile.pk8"

# See if a file was passed:
[ ! -f "$pubFile" ] && echo "Error, bad or no input file $pubFile." && exit 1

# If it is a PEM format X.509 public cert, set $fileType appropriately:
pemCertType="X$(file $pubFile | grep 'PEM certificate')"
[ "$pemCertType" != "X" ] && fileType="PEM"

# If it is an OpenSSL PEM-format PKCS#8-style public key, set $fileType appropriately:
pkEightType="X$(grep -e '-BEGIN PUBLIC KEY-' $pubFile)"
[ "$pkEightType" != "X" ] && fileType="PKCS"

# If this is a file we can't recognise, try to decode a (binary) DER-format X.509 cert:
if [ "$fileType" = "no" ]; then
        openssl x509 -in $pubFile -inform DER -noout
        derResult=$(echo $?)
        [ "$derResult" = "0" ] && fileType="DER"
fi

# Exit if not detected as a file we can use:
[ "$fileType" = "no" ] && echo "Error, input file not of type X.509 public certificate or OpenSSL PKCS#8-style public key (not encrypted)." && exit 1

# Convert the X.509 public cert to an OpenSSL PEM-format PKCS#8-style public key:
if [ "$fileType" = "PEM" -o "$fileType" = "DER" ]; then
        openssl x509 -in $pubFile -inform $fileType -noout -pubkey > $tmpFile
        pkEightTypeFile="$tmpFile"
fi

# Build the string:
# Front matter:
frontString="$(echo -en 'ssh-rsa ')"

# Encoded modulus and exponent, with appropriate pointers:
encodedModulus="$(cat $pkEightTypeFile | grep -v -e "----" | tr -d '\n' | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 )"

# Add a comment string based on the filename, just to be nice:
commentString=" $(echo $pubFile | xargs basename | sed -e 's/\.crt\|\.cer\|\.pem\|\.pk8\|\.der//')"

# Give the user a string:
echo $frontString $encodedModulus $commentString

# cleanup:
rm -f $tmpFile

How add spaces between Slick carousel item

@Dishan TD's answer works nice, but I'm getting better results using only margin-left.

And to make this clearer to everyone else, you have to pay attention to the both opposite numbers: 27 and -27

  /* the slides */
  .slick-slide {
    margin-left:27px;
  }

  /* the parent */
  .slick-list {
    margin-left:-27px;
  }

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

You are off slightly on a few things here, so hopefully the following helps.

Firstly, you don't need to select ranges to access their properties, you can just specify their address etc. Secondly, unless you are manipulating the values within the range, you don't actually need to set them to a variant. If you do want to manipulate the values, you can leave out the bounds of the array as it will be set when you define the range.

It's also good practice to use Option Explicit at the top of your modules to force variable declaration.

The following will do what you are after:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = Range("C4:G4").Value
    Next
End Sub

If you do want to manipulate the values within the array then do this:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer
    Dim anARRAY as Variant

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       anARRAY= Range("C4:G4").Value

       'You can loop through the array and manipulate it here

       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = anARRAY
    Next
End Sub

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

UITableView Cell selected Color?

Swift 3.0 extension

extension UITableViewCell {
    var selectionColor: UIColor {
        set {
            let view = UIView()
            view.backgroundColor = newValue
            self.selectedBackgroundView = view
        }
        get {
            return self.selectedBackgroundView?.backgroundColor ?? UIColor.clear
        }
    }
}

cell.selectionColor = UIColor.FormaCar.blue

jQuery select change event get selected option

Delegated Alternative

In case anyone is using the delegated approach for their listener, use e.target (it will refer to the select element).

$('#myform').on('change', 'select', function (e) {
    var val = $(e.target).val();
    var text = $(e.target).find("option:selected").text(); //only time the find is required
    var name = $(e.target).attr('name');
}

JSFiddle Demo

Where should I put the CSS and Javascript code in an HTML webpage?

Put Stylesheets at the Top Links to discussion

While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively.

Front-end engineers that care about performance want a page to load progressively; that is, we want the browser to display whatever content it has as soon as possible. This is especially important for pages with a lot of content and for users on slower Internet connections. The importance of giving users visual feedback, such as progress indicators, has been well researched and documented. In our case the HTML page is the progress indicator! When the browser loads the page progressively the header, the navigation bar, the logo at the top, etc. all serve as visual feedback for the user who is waiting for the page. This improves the overall user experience.

The problem with putting stylesheets near the bottom of the document is that it prohibits progressive rendering in many browsers, including Internet Explorer. These browsers block rendering to avoid having to redraw elements of the page if their styles change. The user is stuck viewing a blank white page.

The HTML specification clearly states that stylesheets are to be included in the HEAD of the page: "Unlike A, [LINK] may only appear in the HEAD section of a document, although it may appear any number of times." Neither of the alternatives, the blank white screen or flash of unstyled content, are worth the risk. The optimal solution is to follow the HTML specification and load your stylesheets in the document HEAD.

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Unobtrusive validation is enabled by default in new version of ASP.NET. Unobtrusive validation aims to decrease the page size by replacing the inline JavaScript for performing validation with a small JavaScript library that uses jQuery.

You can either disable it by editing web.config to include the following:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Or better yet properly configure it by modifying the Application_Start method in global.asax:

void Application_Start(object sender, EventArgs e) 
{
    RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
        new ScriptResourceDefinition
        {
            Path = "/~Scripts/jquery-2.1.1.min.js"
        }
    );
}

Page 399 of Beginning ASP.NET 4.5.1 in C# and VB provides a discussion on the benefit of unobtrusive validation and a walkthrough for configuring it.

For those looking for RouteConfig. It is added automatically when you make a new project in visual studio to the App_Code folder. The contents look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace @default
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
        }
    }
}

Join/Where with LINQ and Lambda

Your key selectors are incorrect. They should take an object of the type of the table in question and return the key to use in the join. I think you mean this:

var query = database.Posts.Join(database.Post_Metas,
                                post => post.ID,
                                meta => meta.Post_ID,
                                (post, meta) => new { Post = post, Meta = meta });

You can apply the where clause afterwards, not as part of the key selector.

Writing an mp4 video using python opencv

This worked for me.

self._name = name + '.mp4'
self._cap = VideoCapture(0)
self._fourcc = VideoWriter_fourcc(*'MP4V')
self._out = VideoWriter(self._name, self._fourcc, 20.0, (640,480))

Specifying Font and Size in HTML table

This worked for me and also worked with bootstrap tables

<style>
    .table td, .table th {
        font-size: 10px;
    }
</style>

Converting int to string in C

Similar implementation to Ahmad Sirojuddin but slightly different semantics. From a security perspective, any time a function writes into a string buffer, the function should really "know" the size of the buffer and refuse to write past the end of it. I would guess its a part of the reason you can't find itoa anymore.

Also, the following implementation avoids performing the module/devide operation twice.

char *u32todec( uint32_t    value,
                char        *buf,
                int         size)
{
    if(size > 1){
        int i=size-1, offset, bytes;
        buf[i--]='\0';
        do{
            buf[i--]=(value % 10)+'0';
            value = value/10;
        }while((value > 0) && (i>=0));
        offset=i+1;
        if(offset > 0){
            bytes=size-i-1;
            for(i=0;i<bytes;i++)
                buf[i]=buf[i+offset];
        }
        return buf;
    }else
        return NULL;
}

The following code both tests the above code and demonstrates its correctness:

int main(void)
{
    uint64_t acc;
    uint32_t inc;
    char buf[16];
    size_t bufsize;
    for(acc=0, inc=7; acc<0x100000000; acc+=inc){
        printf("%u: ", (uint32_t)acc);
        for(bufsize=17; bufsize>0; bufsize/=2){
            if(NULL != u32todec((uint32_t)acc, buf, bufsize))
                printf("%s ", buf);
        }
        printf("\n");
        if(acc/inc > 9)
            inc*=7;
    }
    return 0;
}

getDate with Jquery Datepicker

This line looks questionable:

page_output.innerHTML = str_output;

You can use .innerHTML within jQuery, or you can use it without, but you have to address the selector semantically one way or the other:

$('#page_output').innerHTML /* for jQuery */
document.getElementByID('page_output').innerHTML /* for standard JS */

or better yet

$('#page_output').html(str_output);

Including one C source file in another?

Numerous other answers have more than covered how you can do this but why you probably should not in normal circumstances. That said, I will add why I've done it in the past.

In embedded development, it's common to have silicon vendor source code as part of your compiled files. The problem is those vendors likely don't have the same style guides or standard warning/error flag settings as your organization.

So, you can create a local source file that includes the vendor source code and then compile this wrapper C file instead to suppress any issues in the included source as well as any headers included by that source. As an example:

/**
 * @file   vendor_wrap.c
 * @brief  vendor source code wrapper to prevent warnings
 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnested-externs"
#include "vendor_source_code.c"
#pragma GCC diagnostic pop

This allows you to use less complicated Make scripting with a standard set of compiler flags and settings with specific exceptions in the code rather than have custom flags for some files in the scripting.

gcc main.c vendor_wrap.c -o $(CFLAGS) main.out

How to check if PHP array is associative or sequential?

Another variant not shown yet, as it's simply not accepting numerical keys, but I like Greg's one very much :

 /* Returns true if $var associative array */  
  function is_associative_array( $array ) {  
    return is_array($array) && !is_numeric(implode('', array_keys($array)));  
  }

Hunk #1 FAILED at 1. What's that mean?

In some cases, there is no difference in file versions, but only in indentation, spacing, line ending or line numbers.

To patch despite those differences, it's possible to use the following two arguments :

--ignore-whitespace : It ignores whitespace differences (indentation, etc).

--fuzz 3 : the "--fuzz X" option sets the maximum fuzz factor to lines. This option only applies to context and unified diffs; it ignores up to X lines while looking for the place to install a hunk. Note that a larger fuzz factor increases the odds of making a faulty patch. The default fuzz factor is 2; there is no point to setting it to more than the number of lines of context in the diff, ordinarily 3.

Don't forget to user "--dry-run" : It'll try the patch without applying it.

Example :

patch --verbose --dry-run --ignore-whitespace --fuzz 3 < /path/to/patch.patch

More informations about Fuzz :

https://www.gnu.org/software/diffutils/manual/html_node/Inexact.html

SQL selecting rows by most recent date with two unique columns

select to.chargeid,t0.po,i.chargetype from invoice i
inner join
(select chargeid,max(servicemonth)po from invoice 
group by chargeid)t0
on i.chargeid=t0.chargeid

The above query will work if the distinct charge id has different chargetype combinations.Hope this simple query helps with little performance time into consideration...

how to redirect to home page

document.location.href="/";

Scrolling to element using webdriver?

There is another option to scroll page to required element if element has "id" attribute

If you want to navigate to page and scroll down to element with @id, it can be done automatically by adding #element_id to URL...

Example

Let's say we need to navigate to Selenium Waits documentation and scroll page down to "Implicit Wait" section. We can do

driver.get('https://selenium-python.readthedocs.io/waits.html')

and add code for scrolling...OR use

driver.get('https://selenium-python.readthedocs.io/waits.html#implicit-waits')

to navigate to page AND scroll page automatically to element with id="implicit-waits" (<div class="section" id="implicit-waits">...</div>)

checking for typeof error in JS

I asked the original question - @Trott's answer is surely the best.

However with JS being a dynamic language and with there being so many JS runtime environments, the instanceof operator can fail especially in front-end development when crossing boundaries such as iframes. See: https://github.com/mrdoob/three.js/issues/5886

If you are ok with duck typing, this should be good:

let isError = function(e){
 return e && e.stack && e.message;
}

I personally prefer statically typed languages, but if you are using a dynamic language, it's best to embrace a dynamic language for what it is, rather than force it to behave like a statically typed language.

if you wanted to get a little more precise, you could do this:

   let isError = function(e){
     return e && e.stack && e.message && typeof e.stack === 'string' 
            && typeof e.message === 'string';
    }

Implementing SearchView in action bar

If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:

old:

android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"

new:

app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"

pre-android x:

app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"

For more information, it's updated documentation is located here.

Using lodash to compare jagged arrays (items existence without order)

Edit: I missed the multi-dimensional aspect of this question, so I'm leaving this here in case it helps people compare one-dimensional arrays

It's an old question, but I was having issues with the speed of using .sort() or sortBy(), so I used this instead:

function arraysContainSameStrings(array1: string[], array2: string[]): boolean {
  return (
    array1.length === array2.length &&
    array1.every((str) => array2.includes(str)) &&
    array2.every((str) => array1.includes(str))
  )
}

It was intended to fail fast, and for my purposes works fine.

How do you determine a processing time in Python?

For Python 3.3 and later time.process_time() is very nice:

import time

t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

You're missing a reference to System.Linq.

Add

using System.Linq

to get access to the ToList() function on the current code file.


To give a little bit of information over why this is necessary, Enumerable.ToList<TSource> is an extension method. Extension methods are defined outside the original class that it targets. In this case, the extension method is defined on System.Linq namespace.

Run parallel multiple commands at once in the same terminal

Use GNU Parallel:

(echo command1; echo command2) | parallel
parallel ::: command1 command2

To kill:

parallel ::: command1 command2 &
PID=$!
kill -TERM $PID
kill -TERM $PID

Android TextView Justify Text

On android, to left justify text and not have truncation of the background color, try this, it worked for me, producing consistent results on android, ff, ie & chrome but you have to measure out the space that's left in between for the text when calculating the padding.

<td style="font-family:Calibri,Arial;
    font-size:15px;
    font-weight:800;
    background-color:#f5d5fd;
    color:black;
    border-style:solid;
    border-width:1px;
    border-color:#bd07eb;
    padding-left:10px;
    padding-right:1000px;
    padding-top:3px;
    padding-bottom:3px;
>

The hack is the padding-right:1000px; that pushes the text to the extreme left.

Any attempt to to a left or justify code in css or html results in a background that's only half width.

Java URLConnection Timeout

You can manually force disconnection by a Thread sleep. This is an example:

URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
new Thread(new InterruptThread(con)).start();

then

public class InterruptThread implements Runnable {

    HttpURLConnection con;
    public InterruptThread(HttpURLConnection con) {
        this.con = con;
    }

    public void run() {
        try {
            Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout())
        } catch (InterruptedException e) {

        }
        con.disconnect();
        System.out.println("Timer thread forcing to quit connection");
    }
}

How to check if an object is an array?

A = [1,2,3]
console.log(A.map==[].map)

In search for shortest version here is what I got so far.

Note, there is no perfect function that will always detect all possible combinations. It is better to know all abilities and limitations of your tools than expect a magic tool.

Get individual query parameters from Uri

Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection instead of a dictionary, but should still do what you need.

The other option is to use string.Split().

    string url = @"http://example.com/file?a=1&b=2&c=string%20param";
    string[] parts = url.Split(new char[] {'?','&'});
    ///parts[0] now contains http://example.com/file
    ///parts[1] = "a=1"
    ///parts[2] = "b=2"
    ///parts[3] = "c=string%20param"

pandas: find percentile stats of a given column

You can use the pandas.DataFrame.quantile() function, as shown below.

import pandas as pd
import random

A = [ random.randint(0,100) for i in range(10) ]
B = [ random.randint(0,100) for i in range(10) ]

df = pd.DataFrame({ 'field_A': A, 'field_B': B })
df
#    field_A  field_B
# 0       90       72
# 1       63       84
# 2       11       74
# 3       61       66
# 4       78       80
# 5       67       75
# 6       89       47
# 7       12       22
# 8       43        5
# 9       30       64

df.field_A.mean()   # Same as df['field_A'].mean()
# 54.399999999999999

df.field_A.median() 
# 62.0

# You can call `quantile(i)` to get the i'th quantile,
# where `i` should be a fractional number.

df.field_A.quantile(0.1) # 10th percentile
# 11.9

df.field_A.quantile(0.5) # same as median
# 62.0

df.field_A.quantile(0.9) # 90th percentile
# 89.10000000000001

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

The difference between using single quotes and double quotes in php is that if we use single quotes in echo statement then it is treated as a string. ... but if we enter variable name within double quotes then it will output the value of that variable along with the string.

PHP Fatal error: Cannot redeclare class

You must use require_once() function.

How to open Atom editor from command line in OS X?

For Windows 7 x64 with default Atom installation add this to your PATH

%USERPROFILE%\AppData\Local\atom\app-1.4.0\resources\cli

and restart any running consoles

(if you don't find Atom there - right-click Atom icon and navigate to Target)

enter image description here

Spring data JPA query with parameter properties

Are you working with a @Service too? Because if you are, then you can @Autowired your PersonRepository to the @Service and then in the service just invoke the Name class and use the form that @CuriosMind... proposed:

@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
                         @Param("forename") String firstname);
}

and when invoking the method from the repository in the service, you can then pass those parameters.

How do I change db schema to dbo

USE MyDB;
GO
ALTER SCHEMA dbo TRANSFER jonathan.MovieData;
GO

Ref: ALTER SCHEMA

Best way to find os name and version in Unix/Linux platform

This work fine for all Linux environment.

#!/bin/sh
cat /etc/*-release

In Ubuntu:

$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=10.04
DISTRIB_CODENAME=lucid
DISTRIB_DESCRIPTION="Ubuntu 10.04.4 LTS"

or 12.04:

$ cat /etc/*-release

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS"
NAME="Ubuntu"
VERSION="12.04.4 LTS, Precise Pangolin"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu precise (12.04.4 LTS)"
VERSION_ID="12.04"

In RHEL:

$ cat /etc/*-release
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Red Hat Enterprise Linux Server release 6.5 (Santiago)

Or Use this Script:

#!/bin/sh
# Detects which OS and if it is Linux then it will detect which Linux
# Distribution.

OS=`uname -s`
REV=`uname -r`
MACH=`uname -m`

GetVersionFromFile()
{
    VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}

if [ "${OS}" = "SunOS" ] ; then
    OS=Solaris
    ARCH=`uname -p` 
    OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
elif [ "${OS}" = "AIX" ] ; then
    OSSTR="${OS} `oslevel` (`oslevel -r`)"
elif [ "${OS}" = "Linux" ] ; then
    KERNEL=`uname -r`
    if [ -f /etc/redhat-release ] ; then
        DIST='RedHat'
        PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
        REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
    elif [ -f /etc/SuSE-release ] ; then
        DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
        REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
    elif [ -f /etc/mandrake-release ] ; then
        DIST='Mandrake'
        PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
        REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
    elif [ -f /etc/debian_version ] ; then
        DIST="Debian `cat /etc/debian_version`"
        REV=""

    fi
    if [ -f /etc/UnitedLinux-release ] ; then
        DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
    fi

    OSSTR="${OS} ${DIST} ${REV}(${PSUEDONAME} ${KERNEL} ${MACH})"

fi

echo ${OSSTR}

How to permanently remove few commits from remote branch

This might be too little too late but what helped me is the cool sounding 'nuclear' option. Basically using the command filter-branch you can remove files or change something over a large number of files throughout your entire git history.

It is best explained here.

How do I convert a list into a string with spaces in Python?

" ".join(my_list)

you need to join with a space not an empty string ...

Update select2 data without rebuilding the control

var selBoxObj = $('#selectpill');
selBoxObj.trigger("change.select2");

How to submit an HTML form on loading the page?

You can do it by using simple one line JavaScript code and also be careful that if JavaScript is turned off it will not work. The below code will do it's job if JavaScript is turned off.

Turn off JavaScript and run the code on you own file to know it's full function.(If you turn off JavaScript here, the below Code Snippet will not work)

_x000D_
_x000D_
.noscript-error {_x000D_
  color: red;_x000D_
}
_x000D_
<body onload="document.getElementById('payment-form').submit();">_x000D_
_x000D_
  <div align="center">_x000D_
    <h1>_x000D_
      Please Waite... You Will be Redirected Shortly<br/>_x000D_
      Don't Refresh or Press Back _x000D_
    </h1>_x000D_
  </div>_x000D_
_x000D_
  <form method='post' action='acction.php' id='payment-form'>_x000D_
    <input type='hidden' name='field-name' value='field-value'>_x000D_
     <input type='hidden' name='field-name2' value='field-value2'>_x000D_
    <noscript>_x000D_
      <div align="center" class="noscript-error">Sorry, your browser does not support JavaScript!._x000D_
        <br>Kindly submit it manually_x000D_
        <input type='submit' value='Submit Now' />_x000D_
      </div>_x000D_
    </noscript>_x000D_
  </form>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

jQuery - keydown / keypress /keyup ENTERKEY detection?

JavaScript/jQuery

$("#entersomething").keyup(function(e){ 
    var code = e.key; // recommended to use e.key, it's normalized across devices and languages
    if(code==="Enter") e.preventDefault();
    if(code===" " || code==="Enter" || code===","|| code===";"){
        $("#displaysomething").html($(this).val());
    } // missing closing if brace
});

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>

Press enter in textbox to and execute button command

Alternatively, you could set the .AcceptButton property of your form. Enter will automcatically create a click event.

this.AcceptButton = this.buttonSearch;

Parsing command-line arguments in C

There is a great general-purpose C library, libUCW, which includes neat command-line option parsing and configuration file loading.

The library also comes with good documentation and includes some other useful stuff (fast I/O, data structures, allocators, ...) but this can be used separately.

Example libUCW option parser (from the library docs)

#include <ucw/lib.h>
#include <ucw/opt.h>

int english;
int sugar;
int verbose;
char *tea_name;

static struct opt_section options = {
  OPT_ITEMS {
    OPT_HELP("A simple tea boiling console."),
    OPT_HELP("Usage: teapot [options] name-of-the-tea"),
    OPT_HELP(""),
    OPT_HELP("Options:"),
    OPT_HELP_OPTION,
    OPT_BOOL('e', "english-style", english, 0, "\tEnglish style (with milk)"),
    OPT_INT('s', "sugar", sugar, OPT_REQUIRED_VALUE, "<spoons>\tAmount of sugar (in teaspoons)"),
    OPT_INC('v', "verbose", verbose, 0, "\tVerbose (the more -v, the more verbose)"),
    OPT_STRING(OPT_POSITIONAL(1), NULL, tea_name, OPT_REQUIRED, ""),
    OPT_END
  }
};

int main(int argc, char **argv)
{
  opt_parse(&options, argv+1);
  return 0;
}

Android Studio suddenly cannot resolve symbols

I'm using Android Studio 3.1.4 and I was experiencing such issue when moving from my develop branch with a lower api target to another branch with target api Oreo. I tried the first solution which worked but it is quite tricky, while the second solution did not solve the problem.

My Solution When the problem popped back again I have tried to modify slightly my app gradle file enough to AS to ask me to sync files, and that did the trick. Then I deleted the change.

I guess that "Sync Project with Gradle Files" might work as well but I haven't tried it myself

Hope it helps

How can I set the current working directory to the directory of the script in Bash?

If you just need to print present working directory then you can follow this.

$ vim test

#!/bin/bash
pwd
:wq to save the test file.

Give execute permission:

chmod u+x test

Then execute the script by ./test then you can see the present working directory.

Sending Arguments To Background Worker?

You can use the DoWorkEventArgs.Argument property.

A full example (even using an int argument) can be found on Microsoft's site:

Focus Input Box On Load

Add this to the top of your js

var input = $('#myinputbox');

input.focus();

Or to html

<script>
    var input = $('#myinputbox');

    input.focus();
</script>

How to resolve symbolic links in a shell script

Is your path a directory, or might it be a file? If it's a directory, it's simple:

(cd "$DIR"; pwd -P)

However, if it might be a file, then this won't work:

DIR=$(cd $(dirname "$FILE"); pwd -P); echo "${DIR}/$(readlink "$FILE")"

because the symlink might resolve into a relative or full path.

On scripts I need to find the real path, so that I might reference configuration or other scripts installed together with it, I use this:

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

You could set SOURCE to any file path. Basically, for as long as the path is a symlink, it resolves that symlink. The trick is in the last line of the loop. If the resolved symlink is absolute, it will use that as SOURCE. However, if it is relative, it will prepend the DIR for it, which was resolved into a real location by the simple trick I first described.

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

Value of type 'T' cannot be converted to

You will also get this error if you have a generic declaration for both your class and your method. For example the code shown below gives this compile error.

public class Foo <T> {

    T var;

    public <T> void doSomething(Class <T> cls) throws InstantiationException, IllegalAccessException {
        this.var = cls.newInstance();
    }

}

This code does compile (note T removed from method declaration):

public class Foo <T> {

    T var;

    public void doSomething(Class <T> cls) throws InstantiationException, IllegalAccessException {
        this.var = cls.newInstance();
    }

}

What's the most appropriate HTTP status code for an "item not found" error page

/**
* {@code 422 Unprocessable Entity}.
* @see <a href="https://tools.ietf.org/html/rfc4918#section-11.2">WebDAV</a>
*/
UNPROCESSABLE_ENTITY(422, "Unprocessable Entity")

PHP - find entry by object property from an array of objects

$arr = [
  [
    'ID' => 1
  ]
];

echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)

Above code echoes the index of the matching element, or false if none.

To get the corresponding element, do something like:

$i = array_search(1, array_column($arr, 'ID'));
$element = ($i !== false ? $arr[$i] : null);

array_column works both on an array of arrays, and on an array of objects.

How to get milliseconds from LocalDateTime in Java 8

I'm not entirely sure what you mean by "current milliseconds" but I'll assume it's the number of milliseconds since the "epoch," namely midnight, January 1, 1970 UTC.

If you want to find the number of milliseconds since the epoch right now, then use System.currentTimeMillis() as Anubian Noob has pointed out. If so, there's no reason to use any of the new java.time APIs to do this.

However, maybe you already have a LocalDateTime or similar object from somewhere and you want to convert it to milliseconds since the epoch. It's not possible to do that directly, since the LocalDateTime family of objects has no notion of what time zone they're in. Thus time zone information needs to be supplied to find the time relative to the epoch, which is in UTC.

Suppose you have a LocalDateTime like this:

LocalDateTime ldt = LocalDateTime.of(2014, 5, 29, 18, 41, 16);

You need to apply the time zone information, giving a ZonedDateTime. I'm in the same time zone as Los Angeles, so I'd do something like this:

ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));

Of course, this makes assumptions about the time zone. And there are edge cases that can occur, for example, if the local time happens to name a time near the Daylight Saving Time (Summer Time) transition. Let's set these aside, but you should be aware that these cases exist.

Anyway, if you can get a valid ZonedDateTime, you can convert this to the number of milliseconds since the epoch, like so:

long millis = zdt.toInstant().toEpochMilli();

Run bash command on jenkins pipeline

I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)

Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps

pipeline {
    agent none

    stages {

        stage ('Hello') {
            agent any

            steps {
                echo 'Hello, '

                sh '''#!/bin/bash

                    echo "Hello from bash"
                    echo "Who I'm $SHELL"
                '''
            }
        }
    }
}

The result of the above execution is

enter image description here

Java parsing XML document gives "Content not allowed in prolog." error

Please check the xml file whether it has any junk character like this ?.If exists,please use the following syntax to remove that.

String XString = writer.toString();
XString = XString.replaceAll("[^\\x20-\\x7e]", "");

Android Relative Layout Align Center

You can use gravity with aligning top and bottom.

 android:gravity="center_vertical"
 android:layout_alignTop="@id/place_category_icon"
 android:layout_alignBottom="@id/place_category_icon"

'invalid value encountered in double_scalars' warning, possibly numpy

In my case, I found out it was division by zero.

Setting public class variables

Inside class Testclass:

public function __construct($new_value)
{
    $this->testvar = $new_value;
}

mySQL :: insert into table, data from another table?

INSERT INTO preliminary_image (style_id,pre_image_status,file_extension,reviewer_id,
uploader_id,is_deleted,last_updated) 

SELECT '4827499',pre_image_status,file_extension,reviewer_id,
uploader_id,'0',last_updated FROM preliminary_image WHERE style_id=4827488

Analysis

We can use above query if we want to copy data from one table to another table in mysql

  1. Here source and destination table are same, we can use different tables also.
  2. Few columns we are not copying like style_id and is_deleted so we selected them hard coded from another table
  3. Table we used in source also contains auto increment field so we left that column and it get inserted automatically with execution of query.

Execution results

1 queries executed, 1 success, 0 errors, 0 warnings

Query: insert into preliminary_image (style_id,pre_image_status,file_extension,reviewer_id,uploader_id,is_deleted,last_updated) select ...

5 row(s) affected

Execution Time : 0.385 sec Transfer Time : 0 sec Total Time : 0.386 sec

showDialog deprecated. What's the alternative?

From Activity#showDialog(int):

This method is deprecated.
Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

Appending to an object

Try this:

alerts.splice(0,0,{"app":"goodbyeworld","message":"cya"});

Works pretty well, it'll add it to the start of the array.

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

How to do something to each file in a directory with a batch script

Alternatively, use:

forfiles /s /m *.png /c "cmd /c echo @path"

The forfiles command is available in Windows Vista and up.

How can I check out a GitHub pull request with git?

You can use git config command to write a new rule to .git/config to fetch pull requests from the repository:

$ git config --local --add remote.origin.fetch '+refs/pull/*/head:refs/remotes/origin/pr/*'

And then just:

$ git fetch origin
Fetching origin
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 2), reused 4 (delta 2), pack-reused 0
Unpacking objects: 100% (4/4), done.
From https://github.com/container-images/memcached
 * [new ref]         refs/pull/2/head -> origin/pr/2
 * [new ref]         refs/pull/3/head -> origin/pr/3

How do I create batch file to rename large number of files in a folder?

you can do this easily without manual editing or using fancy text editors. Here's a vbscript.

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
    If objFS.GetExtensionName(strFile) = "jpg" Then    
        strFileName = strFile.Name
        If InStr(strFileName,"Vacation2010") > 0 Then           
            strNewFileName = Replace(strFileName,"Vacation2010","December")
            strFile.Name = strNewFileName
        End If 
    End If  
Next 

save as myscript.vbs and

C:\test> cscript //nologo myscript.vbs 

Using Java to find substring of a bigger string using Regular Expression

This is a working example :

RegexpExample.java

package org.regexp.replace;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexpExample
{
    public static void main(String[] args)
    {
        String string = "var1[value1], var2[value2], var3[value3]";
        Pattern pattern = Pattern.compile("(\\[)(.*?)(\\])");
        Matcher matcher = pattern.matcher(string);

        List<String> listMatches = new ArrayList<String>();

        while(matcher.find())
        {
            listMatches.add(matcher.group(2));
        }

        for(String s : listMatches)
        {
            System.out.println(s);
        }
    }
}

It displays :

value1
value2
value3

How to delete parent element using jQuery

Delete parent:

$(document).on("click", ".remove", function() {
       $(this).parent().remove(); 
});

Delete all parents:

$(document).on("click", ".remove", function() { 
       $(this).parents().remove();
});

change background image in body

If you have JQuery loaded already, you can just do this:

$('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');

EDIT:

First load JQuery in the head tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

Then call the Javascript to change the background image when something happens on the page, like when it finishes loading:

<script type="text/javascript">
    $(document).ready(function() {
        $('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');
    });
</script>

How to show progress bar while loading, using ajax

Basically you need to have loading image Download free one from here http://www.ajaxload.info/

$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
      $('#loadingmessage').show();

    $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
        success:function(data){
             $('#loadingmessage').hide();
             $("#result").html(data);
        }
    }); 
    });
});

On html body

<div id='loadingmessage' style='display:none'>
       <img src='img/ajax-loader.gif'/>
</div>

Probably this could help you

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

I was facing the same problem when I'm trying to connecting Mysql database using the Laravel application. I would like to recommend please check the password for the user. MySQL password should not have special characters like #, &, etc...

Copy text from nano editor to shell

First method

This method seems to work when the content doesn't include ?.

Install xsel or similar and assign a global shortcut key for this command in your WM or DE:

xsel -o | sed -r 's/^ ?[[:digit:]]+($| +)//g' | perl -pe 's/\n/?/g' | sed -r 's/??/\n\n/g; s/ ?? {1,}/ /g; s/?/\n/g' | xsel -b

Put this in your ~/.Xresources:

*selectToClipboard: false

Issue this in your xterm once to activate the above option:

xrdb -load ~/.Xresources

Now select the line(s) including the line numbers by pressing Shift while dragging the mouse. After the selection click your key combo; the line(s) are coppied and ready to be pasted anywhere you like.

Second method

Doesn't have the shortcoming of the first method.

Install xdotool and xsel or similar.

Put these two lines

Ctrl <Btn3Down>: select-start(PRIMARY, CLIPBOARD)
Ctrl <Btn3Up>: select-end(CLIPBOARD, PRIMARY)

in your ~/.Xresources like so:

*VT100*translations: #override \n\
    Alt <Key> 0xf6: exec-formatted("xdg-open '%t'", PRIMARY, CUT_BUFFER0) \n\                           
    Ctrl <Key>0x2bb: copy-selection(CLIPBOARD) \n\                              
    Alt <Key>0x2bb: insert-selection(CLIPBOARD) \n\                             
    Ctrl <Key> +:       larger-vt-font() \n\                                    
    Ctrl <Key> -:       smaller-vt-font() \n\
    Ctrl <Btn3Down>: select-start(PRIMARY, CLIPBOARD) \n\
    Ctrl <Btn3Up>: select-end(CLIPBOARD, PRIMARY) 

Issue this in your xterm once to activate the above option:

xrdb -load ~/.Xresources

Create this scrip in your path:

#!/bin/bash                                                                  

filepid=$(xdotool getwindowpid $(xdotool getactivewindow))                   
file=$(ps -p "$filepid" o cmd | grep -o --color=never "/.*")                   

firstline=$(xsel -b)                                                         
lastline=$(xsel)                                                             

sed -n ""$firstline","$lastline"p" "$file" | xsel -b

Assign a global shortcut key to call this script in your WM or DE.

Now when you want to copy a line (paragraph), select only the line number of that line (paragraph) by right mouse button while pressing Shift+Ctrl. After the selection click your custom global key combo you've created before. The line (paragraph) is coppied and ready to be pasted anywhere you like.

If you want to copy multiple lines, do the above for the first line and then for the last line of the range, instead of Shift+Ctrl+Btn3 (right mouse button), just select the number by left mouse button while pressing only Shift. After this, again call the script by your custom global shortcut. The range of lines are coppied and ready to pasted anywhere you like.

Get host domain from URL?

Try like this;

Uri.GetLeftPart( UriPartial.Authority )

Defines the parts of a URI for the Uri.GetLeftPart method.


http://www.contoso.com/index.htm?date=today --> http://www.contoso.com

http://www.contoso.com/index.htm#main --> http://www.contoso.com

nntp://news.contoso.com/[email protected] --> nntp://news.contoso.com

file://server/filename.ext --> file://server

Uri uriAddress = new Uri("http://www.contoso.com/index.htm#search");
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Authority));

Demo

apache redirect from non www to www

RewriteCond %{HTTP_HOST} ^!example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

This starts with the HTTP_HOST variable, which contains just the domain name portion of the incoming URL (example.com). Assuming the domain name does not contain a www. and matches your domain name exactly, then the RewriteRule comes into play. The pattern ^(.*)$ will match everything in the REQUEST_URI, which is the resource requested in the HTTP request (foo/blah/index.html). It stores this in a back reference, which is then used to rewrite the URL with the new domain name (one that starts with www).

[NC] indicates case-insensitive pattern matching, [R=301] indicates an external redirect using code 301 (resource moved permanently), and [L] stops all further rewriting, and redirects immediately.

How to check if a file exists in Ansible?

Discovered that calling stat is slow and collects a lot of info that is not required for file existence check.
After spending some time searching for solution, i discovered following solution, which works much faster:

- raw: test -e /path/to/something && echo true || echo false
  register: file_exists

- debug: msg="Path exists"
  when: file_exists == true

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

Is there a way of setting culture for a whole application? All current threads and new threads?

This gets asked a lot. Basically, no there isn't, not for .NET 4.0. You have to do it manually at the start of each new thread (or ThreadPool function). You could perhaps store the culture name (or just the culture object) in a static field to save having to hit the DB, but that's about it.

Optimistic vs. Pessimistic locking

There are basically two most popular answers. The first one basically says

Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.

Another answer is

optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.

or

Optimistic locking works best when you have rare collisions

As it is put on this page.

I created my answer to explain how "keep connection" is related to "low collisions".

To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?

You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.

You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.

In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.

I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.

Insert a new row into DataTable

// get the data table
DataTable dt = ...;

// generate the data you want to insert
DataRow toInsert = dt.NewRow();

// insert in the desired place
dt.Rows.InsertAt(toInsert, index);

send/post xml file using curl command line

If you have multiple headers then you might want to use the following:

curl -X POST --header "Content-Type:application/json" --header "X-Auth:AuthKey" --data @hello.json Your_url

Get current date in DD-Mon-YYY format in JavaScript/Jquery

the DD-MM-YYYY is just one of the formats. The format of the jquery plugin, is based on this list: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Tested following code in chrome console:

test = new Date()
test.format('d-M-Y')
"15-Dec-2014"

Replacing few values in a pandas dataframe column with another value

You could also pass a dict to the pandas.replace method:

data.replace({
    'column_name': {
        'value_to_replace': 'replace_value_with_this'
    }
})

This has the advantage that you can replace multiple values in multiple columns at once, like so:

data.replace({
    'column_name': {
        'value_to_replace': 'replace_value_with_this',
        'foo': 'bar',
        'spam': 'eggs'
    },
    'other_column_name': {
        'other_value_to_replace': 'other_replace_value_with_this'
    },
    ...
})

Visual Studio: Relative Assembly References Paths

To expand upon Pavel Minaev's original comment - The GUI for Visual Studio supports relative references with the assumption that your .sln is the root of the relative reference. So if you have a solution C:\myProj\myProj.sln, any references you add in subfolders of C:\myProj\ are automatically added as relative references.

To add a relative reference in a separate directory, such as C:/myReferences/myDLL.dll, do the following:

  1. Add the reference in Visual Studio GUI by right-clicking the project in Solution Explorer and selecting Add Reference...
  2. Find the *.csproj where this reference exist and open it in a text editor
  3. Edit the < HintPath > to be equal to

    <HintPath>..\..\myReferences\myDLL.dll</HintPath>

This now references C:\myReferences\myDLL.dll.

Hope this helps.

Is it possible to declare two variables of different types in a for loop?

C++17: Yes! You should use a structured binding declaration. The syntax has been supported in gcc and clang since gcc-7 and clang-4.0 (clang live example). This allows us to unpack a tuple like so:

for (auto [i, f, s] = std::tuple{1, 1.0, std::string{"ab"}}; i < N; ++i, f += 1.5) {
    // ...
}

The above will give you:

  • int i set to 1
  • double f set to 1.0
  • std::string s set to "ab"

Make sure to #include <tuple> for this kind of declaration.

You can specify the exact types inside the tuple by typing them all out as I have with the std::string, if you want to name a type. For example:

auto [vec, i32] = std::tuple{std::vector<int>{3, 4, 5}, std::int32_t{12}}

A specific application of this is iterating over a map, getting the key and value,

std::unordered_map<K, V> m = { /*...*/ };
for (auto& [key, value] : m) {
   // ...
}

See a live example here


C++14: You can do the same as C++11 (below) with the addition of type-based std::get. So instead of std::get<0>(t) in the below example, you can have std::get<int>(t).


C++11: std::make_pair allows you to do this, as well as std::make_tuple for more than two objects.

for (auto p = std::make_pair(5, std::string("Hello World")); p.first < 10; ++p.first) {
    std::cout << p.second << std::endl;
}

std::make_pair will return the two arguments in a std::pair. The elements can be accessed with .first and .second.

For more than two objects, you'll need to use a std::tuple

for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
        std::get<0>(t) < 10;
        ++std::get<0>(t)) {
    std::cout << std::get<1>(t) << std::endl; // cout Hello world
    std::get<2>(t).push_back(std::get<0>(t)); // add counter value to the vector
}

std::make_tuple is a variadic template that will construct a tuple of any number of arguments (with some technical limitations of course). The elements can be accessed by index with std::get<INDEX>(tuple_object)

Within the for loop bodies you can easily alias the objects, though you still need to use .first or std::get for the for loop condition and update expression

for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
        std::get<0>(t) < 10;
        ++std::get<0>(t)) {
    auto& i = std::get<0>(t);
    auto& s = std::get<1>(t);
    auto& v = std::get<2>(t);
    std::cout << s << std::endl; // cout Hello world
    v.push_back(i); // add counter value to the vector
}

C++98 and C++03 You can explicitly name the types of a std::pair. There is no standard way to generalize this to more than two types though:

for (std::pair<int, std::string> p(5, "Hello World"); p.first < 10; ++p.first) {
    std::cout << p.second << std::endl;
}

java: run a function after a specific number of seconds

Your original question mentions the "Swing Timer". If in fact your question is related to SWing, then you should be using the Swing Timer and NOT the util.Timer.

Read the section from the Swing tutorial on "How to Use Timers" for more information.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.

  • this is against Facebook policy, so depending on the country where you live, this may not be legal
  • you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
  • when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
  • this is bypassing the OAuth concept
  • on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API

Sample implementation using WatiN:

class FacebookUser
{
  public string Name { get; set; }
  public long Id { get; set; }
}

public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
  var users = new List<FacebookUser>();
  Settings.Instance.MakeNewIeInstanceVisible = false;
  using (var browser = new IE("https://www.facebook.com"))
  {
    try
    {
      browser.TextField(Find.ByName("email")).Value = email;
      browser.TextField(Find.ByName("pass")).Value = password;
      browser.Form(Find.ById("login_form")).Submit();
      browser.WaitForComplete();
    }
    catch (ElementNotFoundException)
    {
      // We're already logged in
    }
    browser.GoTo("https://www.facebook.com/friends");
    var watch = new Stopwatch();
    watch.Start();

    Link previousLastLink = null;
    while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
    {
      var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
                       && l.GetAttributeValue("data-hovercard").Contains("user.php")
                       && l.Text != null
                     ).LastOrDefault();

      if (lastLink == null || previousLastLink == lastLink)
      {
        break;
      }

      var ieElement = lastLink.NativeElement as IEElement;
      if (ieElement != null)
      {
        var htmlElement = ieElement.AsHtmlElement;
        htmlElement.scrollIntoView();
        browser.WaitForComplete();
      }

      previousLastLink = lastLink;
    }

    var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
      && l.GetAttributeValue("data-hovercard").Contains("user.php")
      && l.Text != null
    ).ToList();

    var idRegex = new Regex("id=(?<id>([0-9]+))");
    foreach (var link in links)
    {
      string hovercard = link.GetAttributeValue("data-hovercard");
      var match = idRegex.Match(hovercard);
      long id = 0;
      if (match.Success)
      {
        id = long.Parse(match.Groups["id"].Value);
      }
      users.Add(new FacebookUser
      {
        Name = link.Text,
        Id = id
      });
    }
  }
  return users;
}

Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.

How to print a dictionary line by line in Python?

for car,info in cars.items():
    print(car)
    for key,value in info.items():
        print(key, ":", value)

How do I use dataReceived event of the SerialPort Port Object in C#?

I believe this won't work because you are using a console application and there is no Event Loop running. An Event Loop / Message Pump used for event handling is setup automatically when a Winforms application is created, but not for a console app.

Move a view up only when the keyboard covers an input field

Rewritten for swift 4.2

In ViewDidLoad..

 NotificationCenter.default.addObserver(self, selector: #selector(trailViewController.keyboardWasShown), name: UIResponder.keyboardWillShowNotification, object: nil)
 NotificationCenter.default.addObserver(self, selector: #selector(trailViewController.keyboardWillBeHidden), name: UIResponder.keyboardWillHideNotification, object: nil)

Remaining Funtions

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}

How do I format a date in VBA with an abbreviated month?

I'm using

Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"

to format a column

So I guess

Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"

would do the trick for you.

More: NumberFormat function.

Multiple IF AND statements excel

Try the following:

=IF(OR(E2="in play",E2="pre play",E2="complete",E2="suspended"),
IF(E2="in play",IF(F2="closed",3,IF(F2="suspended",2,IF(ISBLANK(F2),1,-2))),
IF(E2="pre play",IF(ISBLANK(F2),-1,-2),IF(E2="completed",IF(F2="closed",2,-2),
IF(E2="suspended",IF(ISBLANK(F2),3,-2))))),-2)

How to implement debounce in Vue2?

We can do with by using few lines of JS code:

if(typeof window.LIT !== 'undefined') {
      clearTimeout(window.LIT);
}

window.LIT = setTimeout(() => this.updateTable(), 1000);

Simple solution! Work Perfect! Hope, will be helpful for you guys.

CORS Access-Control-Allow-Headers wildcard being ignored?

here's the incantation for nginx, inside a

location / {
    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

}

Pass variables between two PHP pages without using a form or the URL of page

Use Sessions.

Page1:

session_start();
$_SESSION['message'] = "Some message"

Page2:

session_start();
var_dump($_SESSION['message']);

How can I get the actual video URL of a YouTube live stream?

This URL return to player actual video_id

https://www.youtube.com/embed/live_stream?channel=UCkA21M22vGK9GtAvq3DvSlA

Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.

is vs typeof

I did some benchmarking where they do the same - sealed types.

var c1 = "";
var c2 = typeof(string);
object oc1 = c1;
object oc2 = c2;

var s1 = 0;
var s2 = '.';
object os1 = s1;
object os2 = s2;

bool b = false;

Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    b = c1.GetType() == typeof(string); // ~60ms
    b = c1 is string; // ~60ms

    b = c2.GetType() == typeof(string); // ~60ms
    b = c2 is string; // ~50ms

    b = oc1.GetType() == typeof(string); // ~60ms
    b = oc1 is string; // ~68ms

    b = oc2.GetType() == typeof(string); // ~60ms
    b = oc2 is string; // ~64ms


    b = s1.GetType() == typeof(int); // ~130ms
    b = s1 is int; // ~50ms

    b = s2.GetType() == typeof(int); // ~140ms
    b = s2 is int; // ~50ms

    b = os1.GetType() == typeof(int); // ~60ms
    b = os1 is int; // ~74ms

    b = os2.GetType() == typeof(int); // ~60ms
    b = os2 is int; // ~68ms


    b = GetType1<string, string>(c1); // ~178ms
    b = GetType2<string, string>(c1); // ~94ms
    b = Is<string, string>(c1); // ~70ms

    b = GetType1<string, Type>(c2); // ~178ms
    b = GetType2<string, Type>(c2); // ~96ms
    b = Is<string, Type>(c2); // ~65ms

    b = GetType1<string, object>(oc1); // ~190ms
    b = Is<string, object>(oc1); // ~69ms

    b = GetType1<string, object>(oc2); // ~180ms
    b = Is<string, object>(oc2); // ~64ms


    b = GetType1<int, int>(s1); // ~230ms
    b = GetType2<int, int>(s1); // ~75ms
    b = Is<int, int>(s1); // ~136ms

    b = GetType1<int, char>(s2); // ~238ms
    b = GetType2<int, char>(s2); // ~69ms
    b = Is<int, char>(s2); // ~142ms

    b = GetType1<int, object>(os1); // ~178ms
    b = Is<int, object>(os1); // ~69ms

    b = GetType1<int, object>(os2); // ~178ms
    b = Is<int, object>(os2); // ~69ms
}

sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

The generic functions to test for generic types:

static bool GetType1<S, T>(T t)
{
    return t.GetType() == typeof(S);
}
static bool GetType2<S, T>(T t)
{
    return typeof(T) == typeof(S);
}
static bool Is<S, T>(T t)
{
    return t is S;
}

I tried for custom types as well and the results were consistent:

var c1 = new Class1();
var c2 = new Class2();
object oc1 = c1;
object oc2 = c2;

var s1 = new Struct1();
var s2 = new Struct2();
object os1 = s1;
object os2 = s2;

bool b = false;

Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    b = c1.GetType() == typeof(Class1); // ~60ms
    b = c1 is Class1; // ~60ms

    b = c2.GetType() == typeof(Class1); // ~60ms
    b = c2 is Class1; // ~55ms

    b = oc1.GetType() == typeof(Class1); // ~60ms
    b = oc1 is Class1; // ~68ms

    b = oc2.GetType() == typeof(Class1); // ~60ms
    b = oc2 is Class1; // ~68ms


    b = s1.GetType() == typeof(Struct1); // ~150ms
    b = s1 is Struct1; // ~50ms

    b = s2.GetType() == typeof(Struct1); // ~150ms
    b = s2 is Struct1; // ~50ms

    b = os1.GetType() == typeof(Struct1); // ~60ms
    b = os1 is Struct1; // ~64ms

    b = os2.GetType() == typeof(Struct1); // ~60ms
    b = os2 is Struct1; // ~64ms


    b = GetType1<Class1, Class1>(c1); // ~178ms
    b = GetType2<Class1, Class1>(c1); // ~98ms
    b = Is<Class1, Class1>(c1); // ~78ms

    b = GetType1<Class1, Class2>(c2); // ~178ms
    b = GetType2<Class1, Class2>(c2); // ~96ms
    b = Is<Class1, Class2>(c2); // ~69ms

    b = GetType1<Class1, object>(oc1); // ~178ms
    b = Is<Class1, object>(oc1); // ~69ms

    b = GetType1<Class1, object>(oc2); // ~178ms
    b = Is<Class1, object>(oc2); // ~69ms


    b = GetType1<Struct1, Struct1>(s1); // ~272ms
    b = GetType2<Struct1, Struct1>(s1); // ~140ms
    b = Is<Struct1, Struct1>(s1); // ~163ms

    b = GetType1<Struct1, Struct2>(s2); // ~272ms
    b = GetType2<Struct1, Struct2>(s2); // ~140ms
    b = Is<Struct1, Struct2>(s2); // ~163ms

    b = GetType1<Struct1, object>(os1); // ~178ms
    b = Is<Struct1, object>(os1); // ~64ms

    b = GetType1<Struct1, object>(os2); // ~178ms
    b = Is<Struct1, object>(os2); // ~64ms
}

sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

And the types:

sealed class Class1 { }
sealed class Class2 { }
struct Struct1 { }
struct Struct2 { }

Inference:

  1. Calling GetType on structs is slower. GetType is defined on object class which can't be overridden in sub types and thus structs need to be boxed to be called GetType.

  2. On an object instance, GetType is faster, but very marginally.

  3. On generic type, if T is class, then is is much faster. If T is struct, then is is much faster than GetType but typeof(T) is much faster than both. In cases of T being class, typeof(T) is not reliable since its different from actual underlying type t.GetType.

In short, if you have an object instance, use GetType. If you have a generic class type, use is. If you have a generic struct type, use typeof(T). If you are unsure if generic type is reference type or value type, use is. If you want to be consistent with one style always (for sealed types), use is..

concatenate char array in C

You could copy and paste an answer here, or you could go read what our host Joel has to say about strcat.

jQuery .val() vs .attr("value")

In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.

Use curly braces to initialize a Set in Python

From Python 3 documentation (the same holds for python 2.7):

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

in python 2.7:

>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])

Be aware that {} is also used for map/dict:

>>> m = {'a':2,3:'d'}
>>> m[3]
'd'
>>> m={}
>>> type(m)
<type 'dict'> 

One can also use comprehensive syntax to initialize sets:

>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])

In Python, what happens when you import inside of a function?

Importing inside a function will effectively import the module once.. the first time the function is run.

It ought to import just as fast whether you import it at the top, or when the function is run. This isn't generally a good reason to import in a def. Pros? It won't be imported if the function isn't called.. This is actually a reasonable reason if your module only requires the user to have a certain module installed if they use specific functions of yours...

If that's not he reason you're doing this, it's almost certainly a yucky idea.

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

How to export a CSV to Excel using Powershell

I found this while passing and looking for answers on how to compile a set of csvs into a single excel doc with the worksheets (tabs) named after the csv files. It is a nice function. Sadly, I cannot run them on my network :( so i do not know how well it works.

Function Release-Ref ($ref)
{
    ([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
    [System.__ComObject]$ref) -gt 0)
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
    }
    Function ConvertCSV-ToExcel
    {
    <#
    .SYNOPSIS
    Converts     one or more CSV files into an excel file.
    
    .DESCRIPTION
    Converts one or more CSV files into an excel file. Each CSV file is imported into its own worksheet with the name of the
    file being the name of the worksheet.
        
    .PARAMETER inputfile
    Name of the CSV file being converted
    
    .PARAMETER output
    Name of the converted excel file
    
    .EXAMPLE
    Get-ChildItem *.csv | ConvertCSV-ToExcel -output ‘report.xlsx’
    
    .EXAMPLE
    ConvertCSV-ToExcel -inputfile ‘file.csv’ -output ‘report.xlsx’
    
    .EXAMPLE
    ConvertCSV-ToExcel -inputfile @(“test1.csv”,”test2.csv”) -output ‘report.xlsx’
    
    .NOTES
    Author:     Boe Prox
    Date Created: 01SEPT210
    Last Modified:
    
    #>
    
    #Requires -version 2.0
    [CmdletBinding(
    SupportsShouldProcess = $True,
    ConfirmImpact = ‘low’,
    DefaultParameterSetName = ‘file’
    )]
    Param (
    [Parameter(
    ValueFromPipeline=$True,
    Position=0,
    Mandatory=$True,
    HelpMessage=”Name of CSV/s to import”)]
    [ValidateNotNullOrEmpty()]
    [array]$inputfile,
    [Parameter(
    ValueFromPipeline=$False,
    Position=1,
    Mandatory=$True,
    HelpMessage=”Name of excel file output”)]
    [ValidateNotNullOrEmpty()]
    [string]$output
    )
    
    Begin {
    #Configure regular expression to match full path of each file
    [regex]$regex = “^\w\:\\”
    
    #Find the number of CSVs being imported
    $count = ($inputfile.count -1)
    
    #Create Excel Com Object
    $excel = new-object -com excel.application
    
    #Disable alerts
    $excel.DisplayAlerts = $False
    
    #Show Excel application
    $excel.V    isible = $False
    
    #Add workbook
    $workbook = $excel.workbooks.Add()
    
    #Remove other worksheets
    $workbook.worksheets.Item(2).delete()
    #After the first worksheet is removed,the next one takes its place
    $workbook.worksheets.Item(2).delete()
    
    #Define initial worksheet number
    $i = 1
    }
    
    Process {
    ForEach ($input in $inputfile) {
    #If more than one file, create another worksheet for each file
    If ($i -gt 1) {
    $workbook.worksheets.Add() | Out-Null
    }
    #Use the first worksheet in the workbook (also the newest created worksheet is always 1)
    $worksheet = $workbook.worksheets.Item(1)
    #Add name of CSV as worksheet name
    $worksheet.name = “$((GCI $input).basename)”
    
    #Open the CSV file in Excel, must be converted into complete path if no already done
    If ($regex.ismatch($input)) {
    $tempcsv = $excel.Workbooks.Open($input)
    }
    ElseIf ($regex.ismatch(“$($input.fullname)”)) {
    $tempcsv = $excel.Workbooks.Open(“$($input.fullname)”)
    }
    Else {
    $tempcsv = $excel.Workbooks.Open(“$($pwd)\$input”)
    }
    $tempsheet = $tempcsv.Worksheets.Item(1)
    #Copy contents of the CSV file
    $tempSheet.UsedRange.Copy() | Out-Null
    #Paste contents of CSV into existing workbook
    $worksheet.Paste()
    
    #Close temp workbook
    $tempcsv.close()
    
    #Select all used cells
    $range = $worksheet.UsedRange
    
    #Autofit the columns
    $range.EntireColumn.Autofit() | out-null
    $i++
    }
    }
    
    End {
    #Save spreadsheet
    $workbook.saveas(“$pwd\$output”)
    
    Write-Host -Fore Green “File saved to $pwd\$output”
    
    #Close Excel
    $excel.quit()
    
    #Release processes for Excel
    $a = Release-Ref($range)
    }
}

Writing data into CSV file in C#

This is a simple tutorial on creating csv files using C# that you will be able to edit and expand on to fit your own needs.

First you’ll need to create a new Visual Studio C# console application, there are steps to follow to do this.

The example code will create a csv file called MyTest.csv in the location you specify. The contents of the file should be 3 named columns with text in the first 3 rows.

https://tidbytez.com/2018/02/06/how-to-create-a-csv-file-with-c/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CreateCsv
{
    class Program
    {
        static void Main()
        {
            // Set the path and filename variable "path", filename being MyTest.csv in this example.
            // Change SomeGuy for your username.
            string path = @"C:\Users\SomeGuy\Desktop\MyTest.csv";

            // Set the variable "delimiter" to ", ".
            string delimiter = ", ";

            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Column 1 Name" + delimiter + "Column 2 Name" + delimiter + "Column 3 Name" + delimiter + Environment.NewLine;
                File.WriteAllText(path, createText);
            }

            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is text for Column 1" + delimiter + "This is text for Column 2" + delimiter + "This is text for Column 3" + delimiter + Environment.NewLine;
            File.AppendAllText(path, appendText);

            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
}

Where do I find some good examples for DDD?

ddd-cqrs-sample is also a good resource. Written with Java, Spring and JPA.

Updated link: https://github.com/BottegaIT/ddd-leaven-v2

In Java, how do you determine if a thread is running?

You can use: Thread.currentThread().isAlive();. Returns true if this thread is alive; false otherwise.

How to put a text beside the image?

Use floats to float the image, the text should wrap beside

http://www.w3schools.com/css/css_float.asp

How to append in a json file in Python?

Assuming you have a test.json file with the following content:

{"67790": {"1": {"kwh": 319.4}}}

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

import json

a_dict = {'new_key': 'new_value'}

with open('test.json') as f:
    data = json.load(f)

data.update(a_dict)

with open('test.json', 'w') as f:
    json.dump(data, f)

Then, in test.json, you'll have:

{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}

Hope this is what you wanted.

Mocking static methods with Mockito

For those who use JUnit 5, Powermock is not an option. You'll require the following dependencies to successfully mock a static method with just Mockito.

testCompile    group: 'org.mockito', name: 'mockito-core',           version: '3.6.0'
testCompile    group: 'org.mockito', name: 'mockito-junit-jupiter',  version: '3.6.0'
testCompile    group: 'org.mockito', name: 'mockito-inline',         version: '3.6.0'

mockito-junit-jupiter add supports for JUnit 5.

And support for mocking static methods is provided by mockito-inline dependency.

Example:

@Test
void returnUtilTest() {
    assertEquals("foo", UtilClass.staticMethod("foo"));

    try (MockedStatic<UtilClass> classMock = mockStatic(UtilClass.class)) {

        classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");

        assertEquals("bar", UtilClass.staticMethod("foo"));
     }

     assertEquals("foo", UtilClass.staticMethod("foo"));
}

The try-with-resource block is used to make the static mock remains temporary, so it's mocked only within that scope.

When not using a try block, make sure to close the scoped mock, once you are done with the assertions.

MockedStatic<UtilClass> classMock = mockStatic(UtilClass.class)
classMock.when(() -> UtilClass.staticMethod("foo")).thenReturn("bar");
assertEquals("bar", UtilClass.staticMethod("foo"));
classMock.close();

Mocking void methods:

When mockStatic is called on a class, all the static void methods in that class automatically get mocked to doNothing().

Extract hostname name from string

function hostname(url) {
    var match = url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i);
    if ( match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0 ) return match[2];
}

The above code will successfully parse the hostnames for the following example urls:

http://WWW.first.com/folder/page.html first.com

http://mail.google.com/folder/page.html mail.google.com

https://mail.google.com/folder/page.html mail.google.com

http://www2.somewhere.com/folder/page.html?q=1 somewhere.com

https://www.another.eu/folder/page.html?q=1 another.eu

Original credit goes to: http://www.primaryobjects.com/CMS/Article145

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

Is SQL syntax case sensitive?

This isn't strictly SQL language, but in SQL Server if your database collation is case-sensitive, then all table names are case-sensitive.

Quick easy way to migrate SQLite3 to MySQL?

I've just gone through this process, and there's a lot of very good help and information in this Q/A, but I found I had to pull together various elements (plus some from other Q/As) to get a working solution in order to successfully migrate.

However, even after combining the existing answers, I found that the Python script did not fully work for me as it did not work where there were multiple boolean occurrences in an INSERT. See here why that was the case.

So, I thought I'd post up my merged answer here. Credit goes to those that have contributed elsewhere, of course. But I wanted to give something back, and save others time that follow.

I'll post the script below. But firstly, here's the instructions for a conversion...

I ran the script on OS X 10.7.5 Lion. Python worked out of the box.

To generate the MySQL input file from your existing SQLite3 database, run the script on your own files as follows,

Snips$ sqlite3 original_database.sqlite3 .dump | python ~/scripts/dump_for_mysql.py > dumped_data.sql

I then copied the resulting dumped_sql.sql file over to a Linux box running Ubuntu 10.04.4 LTS where my MySQL database was to reside.

Another issue I had when importing the MySQL file was that some unicode UTF-8 characters (specifically single quotes) were not being imported correctly, so I had to add a switch to the command to specify UTF-8.

The resulting command to input the data into a spanking new empty MySQL database is as follows:

Snips$ mysql -p -u root -h 127.0.0.1 test_import --default-character-set=utf8 < dumped_data.sql

Let it cook, and that should be it! Don't forget to scrutinise your data, before and after.

So, as the OP requested, it's quick and easy, when you know how! :-)

As an aside, one thing I wasn't sure about before I looked into this migration, was whether created_at and updated_at field values would be preserved - the good news for me is that they are, so I could migrate my existing production data.

Good luck!

UPDATE

Since making this switch, I've noticed a problem that I hadn't noticed before. In my Rails application, my text fields are defined as 'string', and this carries through to the database schema. The process outlined here results in these being defined as VARCHAR(255) in the MySQL database. This places a 255 character limit on these field sizes - and anything beyond this was silently truncated during the import. To support text length greater than 255, the MySQL schema would need to use 'TEXT' rather than VARCHAR(255), I believe. The process defined here does not include this conversion.


Here's the merged and revised Python script that worked for my data:

#!/usr/bin/env python

import re
import fileinput

def this_line_is_useless(line):
    useless_es = [
        'BEGIN TRANSACTION',
        'COMMIT',
        'sqlite_sequence',
        'CREATE UNIQUE INDEX',        
        'PRAGMA foreign_keys=OFF'
        ]
    for useless in useless_es:
        if re.search(useless, line):
            return True

def has_primary_key(line):
    return bool(re.search(r'PRIMARY KEY', line))

searching_for_end = False
for line in fileinput.input():
    if this_line_is_useless(line): continue

    # this line was necessary because ''); was getting
    # converted (inappropriately) to \');
    if re.match(r".*, ''\);", line):
        line = re.sub(r"''\);", r'``);', line)

    if re.match(r'^CREATE TABLE.*', line):
        searching_for_end = True

    m = re.search('CREATE TABLE "?([A-Za-z_]*)"?(.*)', line)
    if m:
        name, sub = m.groups()
        line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
        line = line % dict(name=name, sub=sub)
        line = line.replace('AUTOINCREMENT','AUTO_INCREMENT')
        line = line.replace('UNIQUE','')
        line = line.replace('"','')
    else:
        m = re.search('INSERT INTO "([A-Za-z_]*)"(.*)', line)
        if m:
            line = 'INSERT INTO %s%s\n' % m.groups()
            line = line.replace('"', r'\"')
            line = line.replace('"', "'")
            line = re.sub(r"(?<!')'t'(?=.)", r"1", line)
            line = re.sub(r"(?<!')'f'(?=.)", r"0", line)

    # Add auto_increment if it's not there since sqlite auto_increments ALL
    # primary keys
    if searching_for_end:
        if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
            line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
        # replace " and ' with ` because mysql doesn't like quotes in CREATE commands

    # And now we convert it back (see above)
    if re.match(r".*, ``\);", line):
        line = re.sub(r'``\);', r"'');", line)

    if searching_for_end and re.match(r'.*\);', line):
        searching_for_end = False

    if re.match(r"CREATE INDEX", line):
        line = re.sub('"', '`', line)

    print line,

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

SELECT a.salesorderid, a.orderdate, s.orderdate, s.salesorderid
FROM A a
OUTER APPLY (SELECT top(1) *
             FROM B b WHERE a.salesorderid = b.salesorderid) as s
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'

Does JavaScript have a built in stringbuilder class?

I have defined this function:

function format() {
        var args = arguments;
        if (args.length <= 1) { 
            return args;
        }
        var result = args[0];
        for (var i = 1; i < args.length; i++) {
            result = result.replace(new RegExp("\\{" + (i - 1) + "\\}", "g"), args[i]);
        }
        return result;
    }

And can be called like c#:

 var text = format("hello {0}, your age is {1}.",  "John",  29);

Result:

hello John, your age is 29.

How can I connect to MySQL in Python 3 on Windows?

CyMySQL https://github.com/nakagami/CyMySQL

I have installed pip on my windows 7, with python 3.3 just pip install cymysql

(you don't need cython) quick and painless

How to size an Android view based on its parent's dimensions

I've found that it's best not to mess around with setting the measured dimensions yourself. There's actually a bit of negotiation that goes on between the parent and child views and you don't want to re-write all that code.

What you can do, though, is modify the measureSpecs, then call super with them. Your view will never know that it's getting a modified message from its parent and will take care of everything for you:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
    int myWidth = (int) (parentHeight * 0.5);
    super.onMeasure(MeasureSpec.makeMeasureSpec(myWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
}

If "0" then leave the cell blank

Your question is missing most of the necessary information, so I'm going to make some assumptions:

  1. Column H is your total summation
  2. You're putting this formula into H16
  3. Column G is additions to your summation
  4. Column F is deductions from your summation
  5. You want to leave the summation cell blank if there isn't a debit or credit entered

The answer would be:

=IF(COUNTBLANK(F16:G16)<>2,H15+G16-F16,"")

COUNTBLANK tells you how many cells are unfilled or set to "".
IF lets you conditionally do one of two things based on whether the first statement is true or false. The second comma separated argument is what to do if it's true, the third comma separated argument is what to do if it's false.
<> means "not equal to".

The equation says that if the number of blank cells in the range F16:G16 (your credit and debit cells) is not 2, which means both aren't blank, then calculate the equation you provided in your question. Otherwise set the cell to blank("").
When you copy this equation to new cells in column H other than H16, it will update the row references so the proper rows for the credit and debit amounts are looked at.

CAVEAT: This equation is useful if you are just adding entries for credits and debits to the end of a list and want the running total to update automatically. You'd fill this equation down to some arbitrary long length well past the end of actual data. You wouldn't see the running total past the end of the credit/debit entries then, it would just be blank until you filled in a new credit/debit entry. If you left a blank row in your credit debit entries though, the reference to the previous total, H15, would report blank, which is treated like a 0 in this case.

PHP: maximum execution time when importing .SQL data file

you must change php_admin_value max_execution_time in your Alias config (\XAMPP\alias\phpmyadmin.conf)

answer is here: WAMPServer phpMyadmin Maximum execution time of 360 seconds exceeded

Warn user before leaving web page with unsaved changes

Built on top of Wasim A.'s excellent idea to use serialization. The problem there was that the warning was also shown when the form was being submitted. This has been fixed here.

var isSubmitting = false

$(document).ready(function () {
    $('form').submit(function(){
        isSubmitting = true
    })

    $('form').data('initial-state', $('form').serialize());

    $(window).on('beforeunload', function() {
        if (!isSubmitting && $('form').serialize() != $('form').data('initial-state')){
            return 'You have unsaved changes which will not be saved.'
        }
    });
})

It has been tested in Chrome and IE 11.