Programs & Examples On #Usb

USB is an acronym for Universal Serial Bus, a standard for a serial host-to-device protocol defined by the USB Implementors Forum.

Is it possible to program Android to act as physical USB keyboard?

Your Android already identifies with a VID/PID when plugged into a host. It already has an interface for Mass Storage. You would need to hack the driver at a low level to support a 2nd interface for 03:01 HID. Then it would just be a question of pushing scancodes to the modified driver. This wouldn't be simple, but it would be a neat hack. One use would be for typing long random passwords for logins.

Simple way to query connected USB devices info in Python?

If you are working on windows, you can use pywin32 (old link: see update below).

I found an example here:

import win32com.client

wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
    print usb.DeviceID

Update Apr 2020:

'pywin32' release versions from 218 and up can be found here at github. Current version 227.

Is there an equivalent of lsusb for OS X

How about ioreg? The output's much more detailed than the profiler, but it's a bit dense.

Source: https://lists.macosforge.org/pipermail/macports-users/2008-July/011115.html

USB Debugging option greyed out

You have to enable USB debugging before plugging your device in to the computer. Unplug device then try to enable USB debugging. This should work. If so, you can then plug it back into the computer and it should work

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

You will need to set the permissions every time you plug the converter in. I use PuTTY to connect. In order to do so, I have created a little Bash script to sort out the permissions and launch PuTTY:

#!/bin/bash
sudo chmod 666 /dev/ttyUSB0

putty

P.S. I would never recommend that permissions are set to 777.

How to change Android usb connect mode to charge only?

Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.

Controlling a USB power supply (on/off) with Linux

I have found these solutions that at least work for properly configured Terminus FE 1.1 USB hub chip:

1.To turn off power on all USB ports of a hub, you may unbind the hub from kernel using:

echo "1-4.4.4" > /sys/bus/usb/drivers/usb/unbind

to turn power back on - you may bind it back using

echo "1-4.4.4" > /sys/bus/usb/drivers/usb/bind

2.Switching power at each port individually is trickier: I was able to use hubpower to control each port - but it comes with a downside: hubpower first disconnects the usbdevfs wich causes all of the USB devices to disconect from system, at least on ubuntu:

usb_ioctl.ioctl_code = USBDEVFS_DISCONNECT;
rc = ioctl(fd, USBDEVFS_IOCTL, &usb_ioctl);

With this ioctl disabled I was able to switch off individual port power without detaching all devices - but the power goes back on immediately (probably due to kernel seeing an uninitialized device) which causes USB device just to do a "cold restart" which is what I generally wanted to do. My patched hubpower is here

"The semaphore timeout period has expired" error for USB connection

I had this problem as well on two different Windows computers when communicating with a Arduino Leonardo. The reliable solution was:

  • Find the COM port in device manager and open the device properties.
  • Open the "Port Settings" tab, and click the advanced button.
  • There, uncheck the box "Use FIFO buffers (required 16550 compatible UART), and press OK.

Unfortunately, I don't know what this feature does, or how it affects this issue. After several PC restarts and a dozen device connection cycles, this is the only thing that reliably fixed the issue.

Why does adb return offline after the device string?

I had the same issue and none of the other answers worked. It seems to occur frequently when you connect to the device using the wifi mode (running command 'adb tcpip 5555'). I found this solution, its sort of a workaround but it does work.

  1. Disconnect the usb (or turn off devices wifi if your connected over wifi)
  2. Close eclipse/other IDE
  3. Check your running programs for adb.exe (Task manager in Windows). If its running, Terminate it.
  4. Restart your android device
  5. After your device restarts, connect it via USB and run 'adb devices'. This should start the adb daemon. And you should see your device online again.

This process is a little lengthy but its the only one that has worked everytime for me.

Send raw ZPL to Zebra printer via USB

You haven't mentioned a language, so I'm going to give you some some hints how to do it with the straight Windows API in C.

First, open a connection to the printer with OpenPrinter. Next, start a document with StartDocPrinter having the pDatatype field of the DOC_INFO_1 structure set to "RAW" - this tells the printer driver not to encode anything going to the printer, but to pass it along unchanged. Use StartPagePrinter to indicate the first page, WritePrinter to send the data to the printer, and close it with EndPagePrinter, EndDocPrinter and ClosePrinter when done.

Get List of connected USB Devices

This is a much simpler example for people only looking for removable usb drives.

using System.IO;

foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    if (drive.DriveType == DriveType.Removable)
    {
        Console.WriteLine(string.Format("({0}) {1}", drive.Name.Replace("\\",""), drive.VolumeLabel));
    }
}

How to load my app from Eclipse to my Android phone instead of AVD

Some people may have the issue where your phone might not immediately get recognized by the computer as an emulator, especially if you're given the option to choose why your phone is connected to the computer on your phone. These options are:

  • charge only
  • Media device (MTP)
  • Camera file transfer (PTP)
  • Share mobile network
  • Install driver

Of these options, choose MTP and follow the instructions found in the quotes of other answers.

  • Hope this helps!

goto run menu -> run configuration. right click on android application on the right side and click new. fill the corresponding details like project name under the android tab. then under the target tab. select 'launch on all compatible devices and then select active devices from the drop down list'. save the configuration and run it by either clicking run on the 'run' button on the bottom right side of the window or close the window and run again

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
  'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
   type : "GET", 
   url : "[the-target-url]", 
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
   success : function(result) { 
       //set your variable to the result 
   }, 
   error : function(result) { 
     //handle the error 
   } 
 }); 

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

Disable a Button

If you want the button to stay static without the "pressed" appearance:

// Swift 2
editButton.userInteractionEnabled = false 

// Swift 3
editButton.isUserInteractionEnabled = false 

Remember:

1) Your IBOutlet is --> @IBOutlet weak var editButton: UIButton!

2) Code above goes in viewWillAppear

__init__() missing 1 required positional argument

You should possibly make data a keyword parameter with a default value of empty dictionary:

class DHT:
    def __init__(self, data=dict()):
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)

if __name__ == '__main__': 
    DHT().showData()

How to get current time in python and break up into year, month, day, hour, minute?

The datetime module is your friend:

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40

You don't need separate variables, the attributes on the returned datetime object have all you need.

How do I make a <div> move up and down when I'm scrolling the page?

You want to apply the fixed property to the position style of the element.

position: fixed;

What browser are you working with? Not all browsers support the fixed property. Read more about who supports it, who doesn't and some work around here

http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html

Searching for Text within Oracle Stored Procedures

If you use UPPER(text), the like '%lah%' will always return zero results. Use '%LAH%'.

jQuery show/hide not working

Use this

<script>
$(document).ready(function(){
    $( '.expand' ).click(function() {
        $( '.img_display_content' ).show();
    });
});
</script>

Event assigning always after Document Object Model loaded

The right way of setting <a href=""> when it's a local file

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

How to put Google Maps V2 on a Fragment using ViewPager

For the issue of getting a NullPointerException when we change the Tabs in a FragmentTabHost you just need to add this code to your class which has the TabHost. I mean the class where you initialize the tabs. This is the code :

/**** Fix for error : Activity has been destroyed, when using Nested tabs 
 * We are actually detaching this tab fragment from the `ChildFragmentManager`
 * so that when this inner tab is viewed back then the fragment is attached again****/

import java.lang.reflect.Field;

@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How to echo with different colors in the Windows command line

I just converted from Win 7 Home to Win 10 Pro and wanted to replace the batch I call from other batches to echo info in color. Reviewing what is discussed above I use the following which will directly replace my previous batch. NOTE the addition of "~" to the message so that messages with spaces may be used. Instead of remembering codes I use letters for the colors I needed.

If %2 contains spaces requires "..." %1 Strong Colors on black: R=Red G=GREEN Y=YELLOW W=WHITE

ECHO OFF
IF "%1"=="R" ECHO ^[91m%~2[0m
IF "%1"=="G" ECHO ^[92m%~2[0m
IF "%1"=="Y" ECHO ^[93m%~2[0m
IF "%1"=="W" ECHO ^[97m%~2[0m

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Cannot hide status bar in iOS7

To hide status bar in iOS7 you need 2 lines of code

  1. inapplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions write

    [application setStatusBarHidden:YES];
    
  2. in info.plist add this

    View-Controller Based Status Bar Appearance = NO
    

setHintTextColor() in EditText

Seems that EditText apply the hintTextColor only if the text is empty. So simple solution will be like this

Editable text = mEditText.getText();
mEditText.setText(null);
mEditText.setHintTextColor(color);
mEditText.setText(text);

If you have multiple fields, you can extend the EditText and write a method which executes this logic and use that method instead.

Turn off iPhone/Safari input element rounding

input -webkit-appearance: none; alone does not work.

Try adding -webkit-border-radius:0px; in addition.

Install Qt on Ubuntu

In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.

For QtCreator and Examples and API Docs:

sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `

sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`

sudo apt-get install build-essential qtcreator qt5-default

If something is also missing, then:

sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `

Hope to be helpful.

Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing

DateTime fields from SQL Server display incorrectly in Excel

I had the same problem as Andre. There does not seem to be a direct solution, but a CAST in the query that generates the data fixes the problem as long as you can live within the restrictions of SMALLDATETIME. In the following query, the first column does not format correctly in Excel, the second does.

SELECT GETDATE(), CAST(GETDATE() AS SMALLDATETIME)

Perhaps the fractional part of the seconds in DATETIME and DATETIME2 confuses Excel.

Most popular screen sizes/resolutions on Android phones

DEVELOPER-DOCS


  • 240*320-ldpi
  • 240*400-ldpi
  • 240*432-ldpi

  • 320*480-mdpi
  • 480*800-mdpi
  • 480*854-mdpi
  • 1024*600-mdpi
  • 1280*800-mdpi

  • 480*800-hdpi
  • 480*854-hdpi
  • 280*280-hdpi
  • 320*320-hdpi

  • 720*1280-xhdpi
  • 1200*1290-xhdpi
  • 2560*1600-xhdpi
  • 768*1280-xhdpi

  • 1080*1920-xxhdpi
  • 800*1280-tvdpi

I use these reference to make my app

Quoting an answer from another stackOverflow post for more details

---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------                                                          
Galaxy Y                                 320 x  240     ldpi    0.75    120      427 x 320      4:3     1.3333                   427 x 320
?                                        400 x  240     ldpi    0.75    120      533 x 320      5:3     1.6667                   533 x 320
?                                        432 x  240     ldpi    0.75    120      576 x 320      9:5     1.8000                   576 x 320
Galaxy Ace                               480 x  320     mdpi    1       160      480 x 320      3:2     1.5000                   480 x 320
Nexus S                                  800 x  480     hdpi    1.5     240      533 x 320      5:3     1.6667                   533 x 320
"Galaxy SIII    Mini"                    800 x  480     hdpi    1.5     240      533 x 320      5:3     1.6667                   533 x 320
?                                        854 x  480     hdpi    1.5     240      569 x 320      427:240 1.7792                   569 x 320

Galaxy SIII                             1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Galaxy Nexus                            1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
HTC One X                       4.7"    1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Nexus 5                         5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778      YES          592 x 360
Galaxy S4                       5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
HTC One                         5"      1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
Galaxy Note III                 5.7"    1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
HTC One Max                     5.9"    1920 x 1080     xxhdpi  3       480      640 x 360      16:9    1.7778                   640 x 360
Galaxy Note II                  5.6"    1280 x  720     xhdpi   2       320      640 x 360      16:9    1.7778                   640 x 360
Nexus 4                         4.4"    1200 x  768     xhdpi   2       320      600 x 384      25:16   1.5625      YES          552 x 384
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
?                                        800 x  480     mdpi    1       160      800 x 480      5:3     1.6667                   800 x 480
?                                        854 x  480     mdpi    1       160      854 x 480      427:240 1.7792                   854 x 480
Galaxy Mega                     6.3"    1280 x  720     hdpi    1.5     240      853 x 480      16:9    1.7778                   853 x 480
Kindle Fire HD                  7"      1280 x  800     hdpi    1.5     240      853 x 533      8:5     1.6000                   853 x 533
Galaxy Mega                     5.8"     960 x  540     tvdpi   1.33333 213.333  720 x 405      16:9    1.7778                   720 x 405
Sony Xperia Z Ultra             6.4"    1920 x 1080     xhdpi   2       320      960 x 540      16:9    1.7778                   960 x 540

Kindle Fire (1st & 2nd gen)     7"      1024 x  600     mdpi    1       160     1024 x 600      128:75  1.7067                  1024 x 600
Tesco Hudl                      7"      1400 x  900     hdpi    1.5     240      933 x 600      14:9    1.5556                   933 x 600
Nexus 7 (1st gen/2012)          7"      1280 x  800     tvdpi   1.33333 213.333  960 x 600      8:5     1.6000      YES          912 x 600
Nexus 7 (2nd gen/2013)          7"      1824 x 1200     xhdpi   2       320      912 x 600      38:25   1.5200      YES          864 x 600
Kindle Fire HDX                 7"      1920 x 1200     xhdpi   2       320      960 x 600      8:5     1.6000                   960 x 600
?                                        800 x  480     ldpi    0.75    120     1067 x 640      5:3     1.6667                  1067 x 640
?                                        854 x  480     ldpi    0.75    120     1139 x 640      427:240 1.7792                  1139 x 640

Kindle Fire HD                  8.9"    1920 x 1200     hdpi    1.5     240     1280 x 800      8:5     1.6000                  1280 x 800
Kindle Fire HDX                 8.9"    2560 x 1600     xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Tab 2                    10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Tab 3                    10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
ASUS Transformer                10"     1280 x  800     mdpi    1       160     1280 x 800      8:5     1.6000                  1280 x 800
ASUS Transformer 2              10"     1920 x 1200     hdpi    1.5     240     1280 x 800      8:5     1.6000                  1280 x 800
Nexus 10                        10"     2560 x  1600    xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
Galaxy Note 10.1                10"     2560 x  1600    xhdpi   2       320     1280 x 800      8:5     1.6000                  1280 x 800
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------
Device                          Inches  ResolutionPX    Density         DPI     ResolutionDP    AspectRatios        SysNavYorN  ContentResolutionDP
---------------------------     -----   ------------    --------------- ------- -----------     ----------------    ---         ----------

How to get only the date value from a Windows Forms DateTimePicker control?

string shortDate = dateTimePicker1.Value.ToShortDateString();

CSS blur on background image but not on content

jsfiddle.

<div> 
    <img class="class" src="http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465">
    </img>
    <span>
        Hello World!
    </span>
</div>

What about this? No absolute positioning on div, but instead on img and span.

Minimum 6 characters regex expression

If I understand correctly, you need a regex statement that checks for at least 6 characters (letters & numbers)?

/[0-9a-zA-Z]{6,}/

split string in two on given index and return both parts

Try this

_x000D_
_x000D_
function split_at_index(value, index)
{
 return value.substring(0, index) + "," + value.substring(index);
}

console.log(split_at_index('3123124', 2));
_x000D_
_x000D_
_x000D_

Where do I call the BatchNormalization function in Keras?

Batch Normalization is used to normalize the input layer as well as hidden layers by adjusting mean and scaling of the activations. Because of this normalizing effect with additional layer in deep neural networks, the network can use higher learning rate without vanishing or exploding gradients. Furthermore, batch normalization regularizes the network such that it is easier to generalize, and it is thus unnecessary to use dropout to mitigate overfitting.

Right after calculating the linear function using say, the Dense() or Conv2D() in Keras, we use BatchNormalization() which calculates the linear function in a layer and then we add the non-linearity to the layer using Activation().

from keras.layers.normalization import BatchNormalization
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, 
validation_split=0.2, verbose = 2)

How is Batch Normalization applied?

Suppose we have input a[l-1] to a layer l. Also we have weights W[l] and bias unit b[l] for the layer l. Let a[l] be the activation vector calculated(i.e. after adding the non-linearity) for the layer l and z[l] be the vector before adding non-linearity

  1. Using a[l-1] and W[l] we can calculate z[l] for the layer l
  2. Usually in feed-forward propagation we will add bias unit to the z[l] at this stage like this z[l]+b[l], but in Batch Normalization this step of addition of b[l] is not required and no b[l] parameter is used.
  3. Calculate z[l] means and subtract it from each element
  4. Divide (z[l] - mean) using standard deviation. Call it Z_temp[l]
  5. Now define new parameters ? and ß that will change the scale of the hidden layer as follows:

    z_norm[l] = ?.Z_temp[l] + ß

In this code excerpt, the Dense() takes the a[l-1], uses W[l] and calculates z[l]. Then the immediate BatchNormalization() will perform the above steps to give z_norm[l]. And then the immediate Activation() will calculate tanh(z_norm[l]) to give a[l] i.e.

a[l] = tanh(z_norm[l])

What is the problem with shadowing names defined in outer scopes?

A good workaround in some cases may be to move the variables and code to another function:

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

Django database query: How to get object by id?

You can use:

objects_all=Class.objects.filter(filter_condition="")

This will return a query set even if it gets one object. If you need exactly one object use:

obj=Class.objects.get(conditon="")

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
}
else {
    print "Access denied!";
}

Jquery Date picker Default Date

$( ".selector" ).datepicker({ defaultDate: null });

and return empty string from backend

Remove ':hover' CSS behavior from element

One method to do this is to add:

pointer-events: none;

to the element, you want to disable hover on.

(Note: this also disables javascript events on that element too, click events will actually fall through to the element behind ).

Browser Support ( 98.12% as of Jan 1, 2021 )

This seems to be much cleaner

_x000D_
_x000D_
/**
 * This allows you to disable hover events for any elements
*/
.disabled {
  pointer-events: none;  /* <----------- */
  opacity: 0.2;
}

.button {
  border-radius: 30px;
  padding: 10px 15px;
  border: 2px solid #000;
  color: #FFF;
  background: #2D2D2D;
  text-shadow: 1px 1px 0px #000;
  cursor: pointer;
  display: inline-block;
  margin: 10px;
}

.button-red:hover {
  background: red;
}

.button-green:hover {
  background:green;  
}
_x000D_
<div class="button button-red">I'm a red button hover over me</div>

<br />

<div class="button button-green">I'm a green button hover over me</div>

<br />

<div class="button button-red disabled">I'm a disabled red button</div>

<br />

<div class="button button-green disabled">I'm a disabled green button</div>
_x000D_
_x000D_
_x000D_

HTML form with two submit buttons and two "target" attributes

This works for me:

<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />

<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

HTML 5: Is it <br>, <br/>, or <br />?

Just use <br>. Do not use <br></br>. <br> is a special tag which doesn't need a closing unlike most tags.

How to set bootstrap navbar active class with Angular JS?

If you are working with Angular router, the RouterLinkActive directive can be used really elegantly:

<ul class="navbar-nav">
  <li class="nav-item"><a class="nav-link" routerLink="home" routerLinkActive="active">Home</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="gallery" routerLinkActive="active">Gallery</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="pricing" routerLinkActive="active">Prices</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="contact" routerLinkActive="active">Contact</a></li>
</ul>

What is the cleanest way to get the progress of JQuery ajax request?

Follow the steps to display Progress of Ajax Request:

  1. Create a Spinner using Html & CSS or use Bootstrap Spinner.
  2. Display the Spinner when the end-user is requesting for the AJAX Data for infinite loop or for threshold limit time.
  3. So, after a SUCCESS / ERROR result of AJAX Request, remove the Spinner which is currently displayed and show your results.

To make it easy I recommend you using JS Classes for dynamically Displaying & Hiding the spinner for this purpose.

I Hope this helps!

How to export data from Spark SQL to CSV

With the help of spark-csv we can write to a CSV file.

val dfsql = sqlContext.sql("select * from tablename")
dfsql.write.format("com.databricks.spark.csv").option("header","true").save("output.csv")`

How to determine if Javascript array contains an object with an attribute that equals a given value?

You can try this its work for me.

const _ = require('lodash');

var arr = [
  {
    name: 'Jack',
    id: 1
  },
  {
    name: 'Gabriel',
    id: 2
  },
  {
    name: 'John',
    id: 3
  }
]

function findValue(arr,value) {
  return _.filter(arr, function (object) {
    return object['name'].toLowerCase().indexOf(value.toLowerCase()) >= 0;
  });
}

console.log(findValue(arr,'jack'))
//[ { name: 'Jack', id: 1 } ]

How to echo in PHP, HTML tags

This will also work fine with double quotes. To echo any html_tag with double quotes we just need to remember one thing, Do not use any other double quotes(") in the middle.

<?php
    echo "
    <div>
        <h3><a href='https://stackoverflow.com/questions/3931351/how-to-echo-in-php-html-tags'>First</a></h3>
        <div>Lorem ipsum dolor sit amet.</div>
        </div>
    <div>";
?>

Notice here the link inside the PHP echo is enclosed within the single quotes. This is the precaution you should take while using the double quotes for this purpose.

How to select current date in Hive SQL

According to the LanguageManual, you can use unix_timestamp() to get the "current time stamp using the default time zone." If you need to convert that to something more human-readable, you can use from_unixtime(unix_timestamp()).

Hope that helps.

Is it correct to use alt tag for an anchor link?

I'm surprised to see all answers stating the use of alt attribute in a tag is not valid. This is absolutely wrong.

Html does not block you using any attributes:

<a your-custom-attribute="value">Any attribute can be used</a>

If you ask if it is semantically correct to use alt attribute in a then I will say:

NO. It is used to set image description <img alt="image description" />.

It is a matter of what you'd do with the attributes. Here's an example:

_x000D_
_x000D_
a::after {_x000D_
  content: attr(color); /* attr can be used as content */_x000D_
  display: block;_x000D_
  color: white;_x000D_
  background-color: blue;_x000D_
  background-color: attr(color); /* This won't work */_x000D_
  display: none;_x000D_
}_x000D_
a:hover::after {_x000D_
  display: block;_x000D_
}_x000D_
[hidden] {_x000D_
  display: none;_x000D_
}
_x000D_
<a href="#" color="red">Hover me!</a>_x000D_
<a href="#" color="red" hidden>In some cases, it can be used to hide it!</a>
_x000D_
_x000D_
_x000D_

Again, if you ask if it is semantically correct to use custom attribute then I will say:

No. Use data-* attributes for its semantic use.


Oops, question was asked in 2013.

Can't accept license agreement Android SDK Platform 24

you need to manually re-install sdk this help me: https://forum.ionicframework.com/t/you-have-not-accepted-the-license-agreements-of-the-following-sdk-component/69570/6

"android update sdk --no-ui --filter build-tools-24.0.0,android-24,extra-android-m2repository"

How do you read CSS rule values with JavaScript?

Here is code to iterate through all rules in a page:

_x000D_
_x000D_
function iterateCSS(f) {_x000D_
  for (const styleSheet of window.document.styleSheets) {_x000D_
    const classes = styleSheet.rules || styleSheet.cssRules;_x000D_
    if (!classes) continue;_x000D_
_x000D_
    for (const cssRule of classes) {_x000D_
      if (cssRule.type !== 1 || !cssRule.style) continue;_x000D_
      const selector = cssRule.selectorText, style=cssRule.style;_x000D_
      if (!selector || !style.cssText) continue;_x000D_
      for (let i=0; i<style.length; i++) {_x000D_
        const propertyName=style.item(i);_x000D_
        if (f(selector, propertyName, style.getPropertyValue(propertyName), style.getPropertyPriority(propertyName), cssRule)===false) return;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
iterateCSS( (selector, propertyName, propertyValue, propertyPriority, cssRule) => {_x000D_
  console.log(selector+' { '+propertyName+': '+propertyValue+(propertyPriority==='important' ? ' !important' : '')+' }');_x000D_
});
_x000D_
_x000D_
_x000D_

How do you merge two Git repositories?

In my case, I had a my-plugin repository and a main-project repository, and I wanted to pretend that my-plugin had always been developed in the plugins subdirectory of main-project.

Basically, I rewrote the history of the my-plugin repository so that it appeared all development took place in the plugins/my-plugin subdirectory. Then, I added the development history of my-plugin into the main-project history, and merged the two trees together. Since there was no plugins/my-plugin directory already present in the main-project repository, this was a trivial no-conflicts merge. The resulting repository contained all history from both original projects, and had two roots.

TL;DR

$ cp -R my-plugin my-plugin-dirty
$ cd my-plugin-dirty
$ git filter-branch -f --tree-filter "zsh -c 'setopt extended_glob && setopt glob_dots && mkdir -p plugins/my-plugin && (mv ^(.git|plugins) plugins/my-plugin || true)'" -- --all
$ cd ../main-project
$ git checkout master
$ git remote add --fetch my-plugin ../my-plugin-dirty
$ git merge my-plugin/master --allow-unrelated-histories
$ cd ..
$ rm -rf my-plugin-dirty

Long version

First, create a copy of the my-plugin repository, because we're going to be rewriting the history of this repository.

Now, navigate to the root of the my-plugin repository, check out your main branch (probably master), and run the following command. Of course, you should substitute for my-plugin and plugins whatever your actual names are.

$ git filter-branch -f --tree-filter "zsh -c 'setopt extended_glob && setopt glob_dots && mkdir -p plugins/my-plugin && (mv ^(.git|plugins) plugins/my-plugin || true)'" -- --all

Now for an explanation. git filter-branch --tree-filter (...) HEAD runs the (...) command on every commit that is reachable from HEAD. Note that this operates directly on the data stored for each commit, so we don't have to worry about notions of "working directory", "index", "staging", and so on.

If you run a filter-branch command that fails, it will leave behind some files in the .git directory and the next time you try filter-branch it will complain about this, unless you supply the -f option to filter-branch.

As for the actual command, I didn't have much luck getting bash to do what I wanted, so instead I use zsh -c to make zsh execute a command. First I set the extended_glob option, which is what enables the ^(...) syntax in the mv command, as well as the glob_dots option, which allows me to select dotfiles (such as .gitignore) with a glob (^(...)).

Next, I use the mkdir -p command to create both plugins and plugins/my-plugin at the same time.

Finally, I use the zsh "negative glob" feature ^(.git|plugins) to match all files in the root directory of the repository except for .git and the newly created my-plugin folder. (Excluding .git might not be necessary here, but trying to move a directory into itself is an error.)

In my repository, the initial commit did not include any files, so the mv command returned an error on the initial commit (since nothing was available to move). Therefore, I added a || true so that git filter-branch would not abort.

The --all option tells filter-branch to rewrite the history for all branches in the repository, and the extra -- is necessary to tell git to interpret it as a part of the option list for branches to rewrite, instead of as an option to filter-branch itself.

Now, navigate to your main-project repository and check out whatever branch you want to merge into. Add your local copy of the my-plugin repository (with its history modified) as a remote of main-project with:

$ git remote add --fetch my-plugin $PATH_TO_MY_PLUGIN_REPOSITORY

You will now have two unrelated trees in your commit history, which you can visualize nicely using:

$ git log --color --graph --decorate --all

To merge them, use:

$ git merge my-plugin/master --allow-unrelated-histories

Note that in pre-2.9.0 Git, the --allow-unrelated-histories option does not exist. If you are using one of these versions, just omit the option: the error message that --allow-unrelated-histories prevents was also added in 2.9.0.

You should not have any merge conflicts. If you do, it probably means that either the filter-branch command did not work correctly or there was already a plugins/my-plugin directory in main-project.

Make sure to enter an explanatory commit message for any future contributors wondering what hackery was going on to make a repository with two roots.

You can visualize the new commit graph, which should have two root commits, using the above git log command. Note that only the master branch will be merged. This means that if you have important work on other my-plugin branches that you want to merge into the main-project tree, you should refrain from deleting the my-plugin remote until you have done these merges. If you don't, then the commits from those branches will still be in the main-project repository, but some will be unreachable and susceptible to eventual garbage collection. (Also, you will have to refer to them by SHA, because deleting a remote removes its remote-tracking branches.)

Optionally, after you have merged everything you want to keep from my-plugin, you can remove the my-plugin remote using:

$ git remote remove my-plugin

You can now safely delete the copy of the my-plugin repository whose history you changed. In my case, I also added a deprecation notice to the real my-plugin repository after the merge was complete and pushed.


Tested on Mac OS X El Capitan with git --version 2.9.0 and zsh --version 5.2. Your mileage may vary.

References:

how to access the command line for xampp on windows

  • You can set environment variables as mentioned in the other answers (like here)

    or

  • you can open Start > CMD as administrator and write

    C:\xampp\php phpfile.php

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

Python element-wise tuple operations like sum

even simpler and without using map, you can do that

>>> tuple(sum(i) for i in zip((1, 2, 3), (3, 2, 1)))
(4, 4, 4)

How do you access the element HTML from within an Angular attribute directive?

This is because the content of

<p myHighlight>Highlight me!</p>

has not been rendered when the constructor of the HighlightDirective is called so there is no content yet.

If you implement the AfterContentInit hook you will get the element and its content.

import { Directive, ElementRef, AfterContentInit } from '@angular/core';

@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {

    constructor(private el: ElementRef) {
        //el.nativeElement.style.backgroundColor = 'yellow';
    }

    ngAfterContentInit(){
        //you can get to the element content here 
        //this.el.nativeElement
    }
}

Read environment variables in Node.js

Why not use them in the Users directory in the .bash_profile file, so you don't have to push any files with your variables to production?

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

Simplifying Scotts code above by removing unnecessary loops which is slowing down badly and does not make it any more secure than calling openssl_random_pseudo_bytes just once

function crypto_rand_secure($min, $max)
{
 $range = $max - $min;
 if ($range < 1) return $min; // not so random...
 $log = ceil(log($range, 2));
 $bytes = (int) ($log / 8) + 1; // length in bytes
 $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
 return $min + $rnd%$range;
}

function getToken($length)
{
 return bin2hex(openssl_random_pseudo_bytes($length)
}

Trim to remove white space

Why not try this?

html:

<p>
  a b c
</p>

js:

$("p").text().trim();

How to unescape HTML character entities in Java?

Incase you want to mimic what php function htmlspecialchars_decode does use php function get_html_translation_table() to dump the table and then use the java code like,

static Map<String,String> html_specialchars_table = new Hashtable<String,String>();
static {
        html_specialchars_table.put("&lt;","<");
        html_specialchars_table.put("&gt;",">");
        html_specialchars_table.put("&amp;","&");
}
static String htmlspecialchars_decode_ENT_NOQUOTES(String s){
        Enumeration en = html_specialchars_table.keys();
        while(en.hasMoreElements()){
                String key = en.nextElement();
                String val = html_specialchars_table.get(key);
                s = s.replaceAll(key, val);
        }
        return s;
}

Should you always favor xrange() over range()?

You should favour range() over xrange() only when you need an actual list. For instance, when you want to modify the list returned by range(), or when you wish to slice it. For iteration or even just normal indexing, xrange() will work fine (and usually much more efficiently). There is a point where range() is a bit faster than xrange() for very small lists, but depending on your hardware and various other details, the break-even can be at a result of length 1 or 2; not something to worry about. Prefer xrange().

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

Get the contents of a table row with a button click

Here is the complete code for simple example of delegate

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">
  <h2>Striped Rows</h2>
  <p>The .table-striped class adds zebra-stripes to a table:</p>            
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>

      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>[email protected]</td>
        <td>click</td>
      </tr>

    </tbody>
  </table>
  <script>
  $(document).ready(function(){
  $("div").delegate("table tbody tr td:nth-child(4)", "click", function(){
  var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)");
     $.each($tds, function() {
        console.log($(this).text());
        var x = $(this).text();
        alert(x);
    });
    });
});
  </script>
</div>

</body>
</html>

C# ASP.NET Single Sign-On Implementation

There are several Identity providers with SSO support out of the box, also third-party** products.

** The only problem with third party products is that they charge per user/month, and it can be quite expensive.

Some of the tools available and with APIs for .NET are:

If you decide to go with your own implementation, you could use the frameworks below categorized by programming language.

  • C#

    • IdentityServer3 (OAuth/OpenID protocols, OWIN/Katana)
    • IdentityServer4 (OAuth/OpenID protocols, ASP.NET Core)
    • OAuth 2.0 by Okta
  • Javascript

    • passport-openidconnect (node.js)
    • oidc-provider (node.js)
    • openid-client (node.js)
  • Python

    • pyoidc
    • Django OIDC Provider

I would go with IdentityServer4 and ASP.NET Core application, it's easy configurable and you can also add your own authentication provider. It uses OAuth/OpenID protocols which are newer than SAML 2.0 and WS-Federation.

Returning multiple objects in an R function

You can also use super-assignment.

Rather than "<-" type "<<-". The function will recursively and repeatedly search one functional level higher for an object of that name. If it can't find one, it will create one on the global level.

Websocket connections with Postman

It's not possible in Postman yet; But there is a new alternative for Postman, named Postwoman. it's open source and supports realtime Websocket and SSE requests.

Update

It seems they have rebranded Postwoman to Hoppscotch and have improved the Websocket support.

Difference between return 1, return 0, return -1 and exit?

To indicate execution status.

status 0 means the program succeeded.

status different from 0 means the program exited due to error or anomaly.

return n; from your main entry function will terminate your process and report to the parent process (the one that executed your process) the result of your process. 0 means SUCCESS. Other codes usually indicates a failure and its meaning.

Node.js Hostname/IP doesn't match certificate's altnames

A slightly updated answer (since I ran into this problem in different circumstances.)

When you connect to a server using SSL, the first thing the server does is present a certificate which says "I am api.dropbox.com." The certificate has a "subject" and the subject has a "CN" (short for "common name".) The certificate may also have one or more "subjectAltNames". When node.js connects to a server, node.js fetches this certificate, and then verifies that the domain name it thinks it's connecting to (api.dropbox.com) matches either the subject's CN or one of the altnames. Note that, in node 0.10.x, if you connect using an IP, the IP address has to be in the altnames - node.js will not try to verify the IP against the CN.

Setting the rejectUnauthorized flag to false will get around this check, but first of all if the server is giving you different credentials than you are expecting, something fishy is going on, and second this will also bypass other checks - it's not a good idea if you're connecting over the Internet.

If you are using node >= 0.11.x, you can also specify a checkServerIdentity: function(host, cert) function to the tls module, which should return undefined if you want to allow the connection and throw an exception otherwise (although I don't know if request will proxy this flag through to tls for you.) It can be handy to declare such a function and console.log(host, cert); to figure out what the heck is going on.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

From the javadoc:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

You can configure your IDE to:

  • ignore this, instead of giving a warning.
  • autogenerate an id

As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":

No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException.

How to remove an HTML element using Javascript?

This works. Just remove the button from the "dummy" div if you want to keep the button.

_x000D_
_x000D_
function removeDummy() {_x000D_
  var elem = document.getElementById('dummy');_x000D_
  elem.parentNode.removeChild(elem);_x000D_
  return false;_x000D_
}
_x000D_
#dummy {_x000D_
  min-width: 200px;_x000D_
  min-height: 200px;_x000D_
  max-width: 200px;_x000D_
  max-height: 200px;_x000D_
  background-color: #fff000;_x000D_
}
_x000D_
<div id="dummy">_x000D_
  <button onclick="removeDummy()">Remove</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if element in groovy array/hash/collection/list?

If you really want your includes method on an ArrayList, just add it:

ArrayList.metaClass.includes = { i -> i in delegate }

Chaining multiple filter() in Django, is this a bug?

Saw this in a comment and I thought it was the simplest explanation.

filter(A, B) is the AND filter(A).filter(B) is OR

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

This could be an error in the web.config file.

Open up your URL in your browser, example:

http://localhost:61277/Email.svc

Check if you have a 500 Error.

HTTP Error 500.19 - Internal Server Error

Look for the error in these sections:

Config Error

Config File

How to remove underline from a name on hover

You can assign an id to the specific link and add CSS. See the steps below:

1.Add an id of your choice (must be a unique name; can only start with text, not a number):

<a href="/abc/xyz" id="smallLinkButton">def</a>
  1. Then add the necessary CSS as follows:

    #smallLinkButton:hover,active,visited{
    
          text-decoration: none;
          }
    

How to disable GCC warnings for a few lines of code

It appears this can be done. I'm unable to determine the version of GCC that it was added, but it was sometime before June 2010.

Here's an example:

#pragma GCC diagnostic error "-Wuninitialized"
    foo(a);         /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
    foo(b);         /* no diagnostic for this one */
#pragma GCC diagnostic pop
    foo(c);         /* error is given for this one */
#pragma GCC diagnostic pop
    foo(d);         /* depends on command line options */

When to use IMG vs. CSS background-image?

I would add another two arguments:

  • An img tag is good if you need to resize the image. E.g. if the original image is 100px by 100 px, and you want it to be 80px by 80px, you can set the CSS width and height of the img tag. I don't know of any good way to do this using background-image. EDIT: This can now also be done with a background-image, using the background-size CSS3 attribute.

  • Using background-image is good when you need to dynamically switch between sprites. E.g. if you have a button image, and you want a separate image displayed when the cursor is hovering over the element, you can use a background image containing both the normal and hover sprites, and dynamically change the background-position.

How do I avoid the specification of the username and password at every git push?

Permanently authenticating with Git repositories,

Run the following command to enable credential caching.

$ git config credential.helper store
$ git push https://github.com/repo.git

Username for 'https://github.com': <USERNAME>
Password for 'https://[email protected]': <PASSWORD>

Use should also specify caching expire,

git config --global credential.helper 'cache --timeout 7200'

After enabling credential caching, it will be cached for 7200 seconds (2 hours).

Note: Credential helper stores an unencrypted password on a local disk.

What is the standard exception to throw in Java for not supported/implemented operations?

Differentiate between the two cases you named:

rmagick gem install "Can't find Magick-config"

Installing rmagick gem in Ubuntu

sudo aptitude Install Imagemagick and GraphicsMagick(If not aptitude go & install in s/w center) sudo aptitude Install libmagickcore-dev libmagickwand-dev gem install rmagick -v 2.13.1

How to set "style=display:none;" using jQuery's attr method?

Why not just use $('#msform').hide()? Behind the scene jQuery's hide and show just set display: none or display: block.

hide() will not change the style if already hidden.

based on the comment below, you are removing all style with removeAttr("style"), in which case call hide() immediately after that.

e.g.

$("#msform").removeAttr("style").hide();

The reverse of this is of course show() as in

$("#msform").show();

Or, more interestingly, toggle(), which effective flips between hide() and show() based on the current state.

Javascript can't find element by id?

The script is performed before the DOM of the body is built. Put it all into a function and call it from the onload of the body-element.

Centering a button vertically in table cell, using Twitter Bootstrap

FOR BOOTSTRAP 3.X:

Bootstrap now has the following style for table cells:

.table tbody > tr > td{
    vertical-align: top;
}

The way to go is to add your own class, adding more specificity to the previous selector:

.table tbody > tr > td.vert-aligned {
    vertical-align: middle;
}

And then add the class to your tds:

<tr>
    <td class="vert-aligned"></td>
    ...
</tr>

FOR BOOTSTRAP 2.X

There is no way to do this with Bootstrap.

When used in table cells, vertical-align does what most people expect it to, which is to mimic the (old, deprecated) valign attribute. In a modern, standards-compliant browser, the following three code snippets do the same thing:

<td valign="middle"> <!-- but you shouldn't ever use valign --> </td>
<td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>

Check your fiddle updated

Further

Also, you can't refer to the td class using .vert because Bootstrap already has this class:

.table td {
   padding: 8px;
   line-height: 20px;
   text-align: left;
   vertical-align: top; // The problem!
   border-top: 1px solid #dddddd;
}

And is overloading the vertical-align: middle in '.vert' class, so you have to define this class as td.vert.

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

With php5.4 now you can do :

use JsonSerializable;

/**
* @Entity(repositoryClass="App\Entity\User")
* @Table(name="user")
*/
class MyUserEntity implements JsonSerializable
{
    /** @Column(length=50) */
    private $name;

    /** @Column(length=50) */
    private $login;

    public function jsonSerialize()
    {
        return array(
            'name' => $this->name,
            'login'=> $this->login,
        );
    }
}

And then call

json_encode(MyUserEntity);

Should we @Override an interface's method implementation?

The problem with including the @Override is that it makes you think that you forgot to call the super.theOverridenMethod() method, which is very confusing. This should be crystal-clear. Perhaps Java should offer an @Interface to be used here. Oh well, yet another half-assed Java peculiarity...

Regex for Mobile Number Validation

This regex is very short and sweet for working.

/^([+]\d{2})?\d{10}$/

Ex: +910123456789 or 0123456789

-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length

This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.

if you want to add the space between than you can use the

[ ]

here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex

/^([+]\d{2}[ ])?\d{10}$/

Ex: +91 0123456789

Thanks ask any question if you have.

How to completely remove Python from a Windows machine?

Almost all of the python files should live in their respective folders (C:\Python26 and C:\Python27). Some installers (ActiveState) will also associate .py* files and add the python path to %PATH% with an install if you tick the "use this as the default installation" box.

Setting a property with an EventTrigger

As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.

Create a custom event in Java

There are 3 different ways you may wish to set this up:

  1. Thrower inside of Catcher
  2. Catcher inside of Thrower
  3. Thrower and Catcher inside of another class in this example Test

THE WORKING GITHUB EXAMPLE I AM CITING Defaults to Option 3, to try the others simply uncomment the "Optional" code block of the class you want to be main, and set that class as the ${Main-Class} variable in the build.xml file:

4 Things needed on throwing side code:

import java.util.*;//import of java.util.event

//Declaration of the event's interface type, OR import of the interface,
//OR declared somewhere else in the package
interface ThrowListener {
    public void Catch();
}
/*_____________________________________________________________*/class Thrower {
//list of catchers & corresponding function to add/remove them in the list
    List<ThrowListener> listeners = new ArrayList<ThrowListener>();
    public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
    //Set of functions that Throw Events.
        public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
            System.out.println("Something thrown");
        }
////Optional: 2 things to send events to a class that is a member of the current class
. . . go to github link to see this code . . .
}

2 Things needed in a class file to receive events from a class

/*_______________________________________________________________*/class Catcher
implements ThrowListener {//implement added to class
//Set of @Override functions that Catch Events
    @Override public void Catch() {
        System.out.println("I caught something!!");
    }
////Optional: 2 things to receive events from a class that is a member of the current class
. . . go to github link to see this code . . .
}

What values for checked and selected are false?

No value is considered false, only the absence of the attribute. There are plenty of invalid values though, and some implementations might consider certain invalid values as false.

HTML5 spec

http://www.w3.org/TR/html5/forms.html#attr-input-checked :

The disabled content attribute is a boolean attribute.

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion

The following are valid, equivalent and true:

<input type="checkbox" checked />
<input type="checkbox" checked="" />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="ChEcKeD" />

The following are invalid:

<input type="checkbox" checked="0" />
<input type="checkbox" checked="1" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />

The absence of the attribute is the only valid syntax for false:

<input type="checkbox" />

Recommendation

If you care about writing valid XHTML, use checked="checked", since <input checked> is invalid and other alternatives are less readable. Else, just use <input checked> as it is shorter.

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Since you are using the lower version of PS:

What you can do in your case is you first download the module in your local folder.

Then, there will be a .psm1 file under that folder for this module.

You just

import-Module "Path of the file.psm1"

Here is the link to download the Azure Module: Azure Powershell

This will do your work.

Reading PDF documents in .Net

PDFClown might help, but I would not recommend it for a big or heavy use application.

Get total size of file in bytes

You don't need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size().

Which sort algorithm works best on mostly sorted data?

Splaysort is an obscure sorting method based on splay trees, a type of adaptive binary tree. Splaysort is good not only for partially sorted data, but also partially reverse-sorted data, or indeed any data that has any kind of pre-existing order. It is O(nlogn) in the general case, and O(n) in the case where the data is sorted in some way (forward, reverse, organ-pipe, etc.).

Its great advantage over insertion sort is that it doesn't revert to O(n^2) behaviour when the data isn't sorted at all, so you don't need to be absolutely sure that the data is partially sorted before using it.

Its disadvantage is the extra space overhead of the splay tree structure it needs, as well as the time required to build and destroy the splay tree. But depending on the size of data and amount of pre-sortedness that you expect, the overhead may be worth it for the increase in speed.

A paper on splaysort was published in Software--Practice & Experience.

Could not load file or assembly '' or one of its dependencies

Microsoft Enterprise Library (referenced by .NetTiers) was our problem, which was in turn referencing an older version of Unity. In order to solve the problem we used the following binding redirection in the web.config:

<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Microsoft.Practices.Unity" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="1.0.0.0-2.0.414.0" newVersion="2.1.505.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Microsoft.Practices.Unity.Configuration" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="1.0.0.0-2.0.414.0" newVersion="2.1.505.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>

Alternatively, you may want to just update the Enterprise Library to the latest version.

JavaFX - create custom button with image

There are a few different ways to accomplish this, I'll outline my favourites.

Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.

My preferred method is to define a graphic for the button in css:

.toggle-button {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}

.toggle-button:selected {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

OR use the attached css to define a background image.

// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
  -fx-background-repeat: no-repeat;
  -fx-background-position: center;
}

.toggle-button:selected {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.

And some sample code:

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImage extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle = new ToggleButton();
    toggle.getStylesheets().add(this.getClass().getResource(
      "imagetogglebutton.css"
    ).toExternalForm());
    toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

Some advantages of doing this are:

  1. You get the default toggle button behavior and don't have to re-implement it yourself by adding your own focus styling, mouse and key handlers etc.
  2. If your app gets ported to different platform such as a mobile device, it will work out of the box responding to touch events rather than mouse events, etc.
  3. Your styling is separated from your application logic so it is easier to restyle your application.

An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImageViaGraphic extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle      = new ToggleButton();
    final Image        unselected  = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
    );
    final Image        selected    = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
    );
    final ImageView    toggleImage = new ImageView();
    toggle.setGraphic(toggleImage);
    toggleImage.imageProperty().bind(Bindings
      .when(toggle.selectedProperty())
        .then(selected)
        .otherwise(unselected)
    );

    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

The code based approach has the advantage that you don't have to use css if you are unfamilar with it.

For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.

Uninstall Eclipse under OSX?

Under Lion I deleted the following files and folders:

  • eclipse in /Applications (obviously)

  • .eclipse in ~

  • .eclipse_keyring in ~

  • org.eclipse.eclipse in ~/Library/Caches

  • org.eclipse.eclipse.savedState in ~/Library/Saved Application State/

Some of them are hidden so you should delete them via Terminal.

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

Implement preferredStatusBarStyle as you mentioned and call self.setNeedsStatusBarAppearanceUpdate() in ViewDidLoad and also in Info.plist set UIViewControllerBasedStatusBarAppearance to YES (It's YES by default)

It is not clear why it is not working.I need to check code.One other suggestion is go with working code in viewDidLoad UIApplication.sharedApplication().statusBarStyle = .LightContent and change this to default when you view get disappeared viewWillDisappear.

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

XML Schema minOccurs / maxOccurs default values

example:

XML

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<country xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="country.xsd">
    <countryName>Australia</countryName>
    <capital>Canberra</capital>
    <nationalLanguage>English</nationalLanguage>
    <population>21000000</population>
    <currency>Australian Dollar</currency>
    <nationalIdentities>
        <nationalAnthem>Advance Australia Fair</nationalAnthem>
        <nationalDay>Australia Day (26 January)</nationalDay>
        <nationalColour>Green and Gold</nationalColour>
        <nationalGemstone>Opal</nationalGemstone>
        <nationalFlower>Wattle (Acacia pycnantha)</nationalFlower>
    </nationalIdentities>
    <publicHolidays>
        <newYearDay>1 January</newYearDay>
        <australiaDay>26 January</australiaDay>
        <anzacDay>25 April</anzacDay>
        <christmasDay>25 December</christmasDay>
        <boxingDay>26 December</boxingDay>
        <laborDay>Variable Date</laborDay>
        <easter>Variable Date</easter>
        <queenBirthDay>21 April (Variable Date)</queenBirthDay>
    </publicHolidays>
    <states>
        <stateName><Name>NSW -  New South Wales</Name></stateName>
        <stateName><Name>VIC -  Victoria</Name></stateName>
        <stateName><Name>QLD -  Queensland</Name></stateName>
        <stateName><Name>SA -  South Australia</Name></stateName>
        <stateName><Name>WA -  Western Australia</Name></stateName>
        <stateName><Name>TAS -  Tasmania</Name></stateName>
    </states>
    <territories>
        <territoryName>ACT -  Australian Capital Territory</territoryName>
        <territoryName>NT -  Northern Territory</territoryName>
    </territories>
</country>

XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="country">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="countryName" type="xs:string"/>
                <xs:element name="capital" type="xs:string"/>
                <xs:element name="nationalLanguage" type="xs:string"/>
                <xs:element name="population" type="xs:double"/>
                <xs:element name="currency" type="xs:string"/>
                <xs:element name="nationalIdentities">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="nationalAnthem" type="xs:string"/>
                        <xs:element name="nationalDay" type="xs:string"/>
                        <xs:element name="nationalColour" type="xs:string"/>
                        <xs:element name="nationalGemstone" type="xs:string"/>
                        <xs:element name="nationalFlower" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
                </xs:element>
                <xs:element name="publicHolidays">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="newYearDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="australiaDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="anzacDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="christmasDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="boxingDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="laborDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="easter" maxOccurs="1" type="xs:string"/>
                            <xs:element name="queenBirthDay" maxOccurs="1" type="xs:string"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="states">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="stateName" minOccurs="1" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Name" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="territories">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="territoryName" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSL:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" version="4.0"/>
    <xsl:template match="/">
        <html>
            <body>          
                <xsl:for-each select="country">         
                    <xsl:value-of select="countryName"/><br/>
                    <xsl:value-of select="capital"/><br/>
                    <xsl:value-of select="nationalLanguage"/><br/>
                    <xsl:value-of select="population"/><br/>
                    <xsl:value-of select="currency"/><br/>              
                    <xsl:for-each select="nationalIdentities">
                        <xsl:value-of select="nationalAnthem"/><br/>
                        <xsl:value-of select="nationalDay"/><br/>
                        <xsl:value-of select="nationalColour"/><br/>
                        <xsl:value-of select="nationalGemstone"/><br/>
                        <xsl:value-of select="nationalFlower"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="publicHolidays">
                        <xsl:value-of select="newYearDay"/><br/>
                        <xsl:value-of select="australiaDay"/><br/>
                        <xsl:value-of select="anzacDay"/><br/>
                        <xsl:value-of select="christmasDay"/><br/>
                        <xsl:value-of select="boxingDay"/><br/>
                        <xsl:value-of select="laborDay"/><br/>
                        <xsl:value-of select="easter"/><br/>
                        <xsl:value-of select="queenBirthDay"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="states/stateName">
                        <xsl:value-of select="Name"/><br/>
                    </xsl:for-each>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Result:

Australia
Canberra
English
21000000
Australian Dollar
Advance Australia Fair
Australia Day (26 January)
Green and Gold
Opal
Wattle (Acacia pycnantha)
1 January
26 January
25 April
25 December
26 December
Variable Date
Variable Date
21 April (Variable Date)
NSW - New South Wales
VIC - Victoria
QLD - Queensland
SA - South Australia
WA - Western Australia
TAS - Tasmania

Why are primes important in cryptography?

It's not so much the prime numbers themselves that are important, but the algorithms that work with primes. In particular, finding the factors of a number (any number).

As you know, any number has at least two factors. Prime numbers have the unique property in that they have exactly two factors: 1 and themselves.

The reason factoring is so important is mathematicians and computer scientists don't know how to factor a number without simply trying every possible combination. That is, first try dividing by 2, then by 3, then by 4, and so forth. If you try to factor a prime number--especially a very large one--you'll have to try (essentially) every possible number between 2 and that large prime number. Even on the fastest computers, it will take years (even centuries) to factor the kinds of prime numbers used in cryptography.

It is the fact that we don't know how to efficiently factor a large number that gives cryptographic algorithms their strength. If, one day, someone figures out how to do it, all the cryptographic algorithms we currently use will become obsolete. This remains an open area of research.

Comparing two java.util.Dates to see if they are in the same day

Java 8

If you are using Java 8 in your project and comparing java.sql.Timestamp, you could use the LocalDate class:

sameDate = date1.toLocalDateTime().toLocalDate().equals(date2.toLocalDateTime().toLocalDate());

If you are using java.util.Date, have a look at Istvan answer which is less ambiguous.

What is the best way to search the Long datatype within an Oracle database?

Example:

create table longtable(id number,text long);

insert into longtable values(1,'hello world');
insert into longtable values(2,'say hello!');

commit;

create or replace function search_long(r rowid) return varchar2 is
temporary_varchar varchar2(4000);
begin
select text into temporary_varchar from longtable where rowid=r;
return temporary_varchar;
end;
/


SQL> select text from longtable where search_long(rowid) like '%hello%';                                                                              

TEXT
--------------------------------------------------------------------------------
hello world
say hello!

But be careful. A PL/SQL function will only search the first 32K of LONG.

exceeds the list view threshold 5000 items in Sharepoint 2010

The setting for the list throttle

  • Open the SharePoint Central Administration,
  • go to Application Management --> Manage Web Applications
  • Click to select the web application that hosts your list (eg. SharePoint - 80)
  • At the Ribbon, select the General Settings and select Resource Throttling
  • Then, you can see the 5000 List View Threshold limit and you can edit the value you want.
  • Click OK to save it.

For addtional reading: http://blogs.msdn.com/b/dinaayoub/archive/2010/04/22/sharepoint-2010-how-to-change-the-list-view-threshold.aspx

How to get the start time of a long-running Linux process?

As a follow-up to Adam Matan's answer, the /proc/<pid> directory's time stamp as such is not necessarily directly useful, but you can use

awk -v RS=')' 'END{print $20}' /proc/12345/stat

to get the start time in clock ticks since system boot.1

This is a slightly tricky unit to use; see also convert jiffies to seconds for details.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat

This should give you seconds, which you can pass to strftime() to get a (human-readable, or otherwise) timestamp.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat

Updated with some fixes from Stephane Chazelas in the comments; thanks as always!

If you only have Mawk, maybe try

awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
  NR==1 { now=$1; next }
  END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}

1 man proc; search for starttime.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

The model backing the <Database> context has changed since the database was created

Just in case someone has the same scenario as mine.

I have database first EF and at the same time using the asp.net identity

so I have two connectionStrings in my webconfig, and there is no problem with that. It happened that I created/run the scripts to generate manually the asp.net identity tables which I should not.

so DROP first all the asp.net identity tables created by you manually/from scripts.

DROP TABLE __MigrationHistory
DROP TABLE AspNetRoles
DROP TABLE AspNetUserClaims
DROP TABLE AspNetUserLogins
DROP TABLE AspNetUserRoles
DROP TABLE AspNetUsers

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

I know this is a very old question but this is more for someone else who might have the same problem and I think this is more accurate to what was wanted.

SELECT * FROM member WHERE email = (Select email From member Where login_id = [email protected]) 

This will return all records that have [email protected] as a login_id value.

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

Delete column from SQLite table

In Python 3.8... Preserves primary key and column types.

Takes 3 inputs:

  1. a sqlite cursor: db_cur,
  2. table name: t and,
  3. list of columns to junk: columns_to_junk
def removeColumns(db_cur, t, columns_to_junk):

    # Obtain column information
    sql = "PRAGMA table_info(" + t + ")"
    record = query(db_cur, sql)

    # Initialize two strings: one for column names + column types and one just
    # for column names
    cols_w_types = "("
    cols = ""

    # Build the strings, filtering for the column to throw out
    for r in record:
        if r[1] not in columns_to_junk:
            if r[5] == 0:
                cols_w_types += r[1] + " " + r[2] + ","
            if r[5] == 1:
                cols_w_types += r[1] + " " + r[2] + " PRIMARY KEY,"
            cols += r[1] + ","

    # Cut potentially trailing commas
    if cols_w_types[-1] == ",":
        cols_w_types = cols_w_types[:-1]
    else:
        pass

    if cols[-1] == ",":
        cols = cols[:-1]
    else:
        pass

    # Execute SQL
    sql = "CREATE TEMPORARY TABLE xfer " + cols_w_types + ")"
    db_cur.execute(sql)
    sql = "INSERT INTO xfer SELECT " + cols + " FROM " + t
    db_cur.execute(sql)
    sql = "DROP TABLE " + t
    db_cur.execute(sql)
    sql = "CREATE TABLE " + t + cols_w_types + ")"
    db_cur.execute(sql)
    sql = "INSERT INTO " + t + " SELECT " + cols  + " FROM xfer"
    db_cur.execute(sql)

You'll find a reference to a query() function. Just a helper...

Takes two inputs:

  1. sqlite cursor db_cur and,
  2. the query string: query
def query(db_cur, query):

    r = db_cur.execute(query).fetchall()

    return r

Don't forget to include a "commit()"!

Insert line break in wrapped cell via code

Yes there are two way to add a line feed:

  1. Use the existing function from VBA vbCrLf in the string you want to add a line feed, as such:

    Dim text As String

    text = "Hello" & vbCrLf & "World!"

    Worksheets(1).Cells(1, 1) = text

  2. Use the Chr() function and pass the ASCII characters 13 and 10 in order to add a line feed, as shown bellow:

    Dim text As String

    text = "Hello" & Chr(13) & Chr(10) & "World!"

    Worksheets(1).Cells(1, 1) = text

In both cases, you will have the same output in cell (1,1) or A1.

ValueError: max() arg is an empty sequence

try parsing a default value which can be returned by max if length of v none

max(v, default=0)

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

I suggest to run in two steps:

1) generate mapping A that maps A:column index->non zero objects

2) for each object i (row) with non-zero occurrences(columns) {k1,..kn} calculate cosine similarity just for elements in the union set A[k1] U A[k2] U.. A[kn]

Assuming a big sparse matrix with high sparsity this will gain a significant boost over brute force

Convert character to ASCII numeric value in java

The several answers that purport to show how to do this are all wrong because Java characters are not ASCII characters. Java uses a multibyte encoding of Unicode characters. The Unicode character set is a super set of ASCII. So there can be characters in a Java string that do not belong to ASCII. Such characters do not have an ASCII numeric value, so asking how to get the ASCII numeric value of a Java character is unanswerable.

But why do you want to do this anyway? What are you going to do with the value?

If you want the numeric value so you can convert the Java String to an ASCII string, the real question is "how do I encode a Java String as ASCII". For that, use the object StandardCharsets.US_ASCII.

How do I access the $scope variable in browser's console using AngularJS?

This requires jQuery to be installed as well, but works perfectly for a dev environment. It looks through each element to get the instances of the scopes then returns them labelled with there controller names. Its also removing any property start with a $ which is what angularjs generally uses for its configuration.

let controllers = (extensive = false) => {
            let result = {};
            $('*').each((i, e) => {
                let scope = angular.element(e).scope();
                if(Object.prototype.toString.call(scope) === '[object Object]' && e.hasAttribute('ng-controller')) {
                    let slimScope = {};
                    for(let key in scope) {
                        if(key.indexOf('$') !== 0 && key !== 'constructor' || extensive) {
                            slimScope[key] = scope[key];
                        }
                    }
                    result[$(e).attr('ng-controller')] = slimScope;
                }
            });

            return result;
        }

Disable Transaction Log

There is a third recovery mode not mentioned above. The recovery mode ultimately determines how large the LDF files become and how ofter they are written to. In cases where you are going to be doing any type of bulk inserts, you should set the DB to be in "BULK/LOGGED". This makes bulk inserts move speedily along and can be changed on the fly.

To do so,

USE master ;
ALTER DATABASE model SET RECOVERY BULK_LOGGED ;

To change it back:

USE master ;
ALTER DATABASE model SET RECOVERY FULL ;

In the spirit of adding to the conversation about why someone would not want an LDF, I add this: We do multi-dimensional modelling. Essentially we use the DB as a large store of variables that are processed in bulk using external programs. We do not EVER require rollbacks. If we could get a performance boost by turning of ALL logging, we'd take it in a heart beat.

Return outside function error in Python

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break

Gradle: Execution failed for task ':processDebugManifest'

This appears to occur because Google Play Services require Android 2.2, which is SDK version 8.

In build.gradle, make sure your minSdkVersion is at least 8. The default appears to be 7. So you have something like this:

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
    }
}

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
    compile 'com.google.android.gms:play-services:3.1.36'
}

HTML CSS How to stop a table cell from expanding

Simply set the max-width attribute to 280px like this:

<td align="left" valign="top" style="overflow:hidden;" nowrap="nowrap" max-width="280px" width="280px">

This will solve your problem.

Linear regression with matplotlib / numpy

import numpy as np
import matplotlib.pyplot as plt 
from scipy import stats

x = np.array([1.5,2,2.5,3,3.5,4,4.5,5,5.5,6])
y = np.array([10.35,12.3,13,14.0,16,17,18.2,20,20.7,22.5])
gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
mn=np.min(x)
mx=np.max(x)
x1=np.linspace(mn,mx,500)
y1=gradient*x1+intercept
plt.plot(x,y,'ob')
plt.plot(x1,y1,'-r')
plt.show()

USe this ..

Remove leading comma from a string

var s = ",'first string','more','even more'";

var array = s.split(',').slice(1);

That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.

Expression ___ has changed after it was checked

I think a most simple solution would be as follows:

  1. Make one implementation of assigning a value to some variable i.e. via function or setter.
  2. Create a class variable (static working: boolean) in the class where this function exists and every time you call the function, simply make it true whichever you like. Within the function, if the value of working is true, then simply return right away without doing anything. else, perform the task you want. Make sure to change this variable to false once the task is completed i.e. at the end of the line of codes or within the subscribe method when you are done assigning values!

C# Java HashMap equivalent

the answer is

Dictionary

take look at my function, its simple add uses most important member functions inside Dictionary

this function return false if the list contain Duplicates items

 public static bool HasDuplicates<T>(IList<T> items)
    {
        Dictionary<T, bool> mp = new Dictionary<T, bool>();
        for (int i = 0; i < items.Count; i++)
        {
            if (mp.ContainsKey(items[i]))
            {
                return true; // has duplicates
            }
            mp.Add(items[i], true);
        }
        return false; // no duplicates
    }

Add borders to cells in POI generated Excel File

a Helper function:

private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) {
        Workbook wb = sheet.getWorkbook();
        RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb);
    }

When you want to add Border in Excel, then

String cellAddr="$A$11:$A$17";

setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);

how to find seconds since 1970 in java

Another option is to use the TimeUtils utility method:

TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)

Can't get value of input type="file"?

$('input[type=file]').val()

That'll get you the file selected.

However, you can't set the value yourself.

Random state (Pseudo-random number) in Scikit learn

If you don't specify the random_state in your code, then every time you run(execute) your code a new random value is generated and the train and test datasets would have different values each time.

However, if a fixed value is assigned like random_state = 42 then no matter how many times you execute your code the result would be the same .i.e, same values in train and test datasets.

Visual Studio Code pylint: Unable to import 'protorpc'

I got the same error on my vscode where I had a library installed and the code working when running from the terminal, but for some reason, the vscode pylint was not able to pick the installed package returning the infamous error:

Unable to import 'someLibrary.someModule' pylint(import-error)

The problem might arise due to the multiple Python installations. Basically you have installed a library/package on one, and vscode pylint is installed and running from another installation. For example, on macOS and many Linux distros, there are by default Python2 installed and when you install Python3 this might cause confusion. Also on windows the Chocolatey package manager might cause some mess and you end up with multiple Python installations. To figure it out if you are on a *nix machine (i.e., macOS, GNU/Linux, BSD...), use the which command, and if you are on Windows, use the where command to find the installed Python interpreters. For example, on *nix machines:

which python3

and on Windows

where python

then you may want to uninstall the ones you don't want. and the one you want to use check if the package causing above issue is installed by

python -c "import someLibrary"

if you get an error then you should install it by for example pip:

pip install someLibrary

then on vscode press ??P if you are on a mac and CtrlShiftP on other operating systems. Then type-select the >python: Select Interpreter option and select the one you know have the library installed. At this moment vscode might asks you to install pyling again, which you just go on with.

Zookeeper connection error

I also get the same error when i started my replicated zk, one of zkClient can not connect to localhost:2181, i checked the log file under apache-zookeeper-3.5.5-bin/logs directory, and found this:

2019-08-20 11:30:39,763 [myid:5] - WARN [QuorumPeermyid=5(secure=disabled):QuorumCnxManager@677] - Cannot open channel to 3 at election address /xxxx:3888 java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:648) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:705) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectAll(QuorumCnxManager.java:733) at org.apache.zookeeper.server.quorum.FastLeaderElection.lookForLeader(FastLeaderElection.java:910) at org.apache.zookeeper.server.quorum.QuorumPeer.run(QuorumPeer.java:1247) 2019-08-20 11:30:44,768 [myid:5] - WARN [QuorumPeermyid=5(secure=disabled):QuorumCnxManager@677] - Cannot open channel to 4 at election address /xxxxxx:3888 java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:648) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:705) at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectAll(QuorumCnxManager.java:733) at org.apache.zookeeper.server.quorum.FastLeaderElection.lookForLeader(FastLeaderElection.java:910) at org.apache.zookeeper.server.quorum.QuorumPeer.run(QuorumPeer.java:1247) 2019-08-20 11:30:44,769 [myid:5] - INFO [QuorumPeermyid=5(secure=disabled):FastLeaderElection@919] - Notification time out: 51200

that means this zk server can not connect to other servers, and i found this server ping other servers fail, and after remove this server from the replica, the problem is solved.

hope this will be helpful.

How can I scroll a web page using selenium webdriver in python?

driver.execute_script("document.getElementById('your ID Element').scrollIntoView();")

it's working for my case.

403 - Forbidden: Access is denied. ASP.Net MVC

Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?

Straight from msdn .....

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file

  • In Windows Explorer, locate and select the required file.
  • Right-click the file, and then click Properties.
  • In the Properties dialog box, click the Security tab.
  • On the Security tab, examine the list of users. If the Network Service
  • account is not listed, add it.
  • In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  • Click Apply, and then click OK.

Click here for more

casting int to char using C++ style casting

Using static cast would probably result in something like this:

// This does not prevent a possible type overflow
const char char_max = -1;

int i = 48;
char c = (i & char_max);

To prevent possible type overflow you could do this:

const char char_max = (char)(((unsigned char) char(-1)) / 2);

int i = 128;
char c = (i & char_max); // Would always result in positive signed values.

Where reinterpret_cast would probably just directly convert to char, without any cast safety. -> Never use reinterpret_cast if you can also use static_cast. If you're casting between classes, static_cast will also ensure, that the two types are matching (the object is a derivate of the cast type).

If your object a polymorphic type and you don't know which one it is, you should use dynamic_cast which will perform a type check at runtime and return nullptr if the types do not match.

IF you need const_cast you most likely did something wrong and should think about possible alternatives to fix const correctness in your code.

How can one create an overlay in css?

         div{
         background-image:url('');
         background-size:cover;
         background-position:top center;
         position:relative;
         }

         div:before{
         content:'';
         position:absolute;
         left:0;
         top:0;
         height:100%;
         width:100%;
         background-color:rgba(0,0,0,0.7);
         }

offsetTop vs. jQuery.offset().top

It is possible that the offset could be a non-integer, using em as the measurement unit, relative font-sizes in %.

I also theorise that the offset might not be a whole number when the zoom isn't 100% but that depends how the browser handles scaling.

Visual studio equivalent of java System.out

Or, if you want to see output in the Output window of Visual Studio, System.Diagnostics.Debug.WriteLine(stuff)

Get Hard disk serial Number

I’m using this:

<!-- language: c# -->
private static string wmiProperty(string wmiClass, string wmiProperty){
  using (var searcher = new ManagementObjectSearcher($"SELECT * FROM {wmiClass}")) {
   try {
                    IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
                    return objects.Select(x => x.GetPropertyValue(wmiProperty)).FirstOrDefault().ToString().Trim();
                } catch (NullReferenceException) {
                    return null;
                }
            }
        }

Maven build debug in Eclipse

The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

What is a simple C or C++ TCP server and client example?

If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like boost::asio are imho quite complicated when it comes to short and simple "hello world" example.

To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
http://www.linuxhowtos.org/data/6/server.c
http://www.linuxhowtos.org/data/6/client.c
from: http://www.linuxhowtos.org/C_C++/socket.htm

  1. Add following includes to both files:

    #include <cstdlib>
    #include <cstring>
    #include <unistd.h>
    
  2. In client.c, change the line:

    if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

    to:

    if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

As you can see in C++ an explicit cast is needed.

How do I get today's date in C# in mm/dd/yyyy format?

DateTime.Now.Date.ToShortDateString()

I think this is what you are looking for

Drop all data in a pandas dataframe

You need to pass the labels to be dropped.

df.drop(df.index, inplace=True)

By default, it operates on axis=0.

You can achieve the same with

df.iloc[0:0]

which is much more efficient.

How to store Node.js deployment settings/configuration files?

I tryied some of suggested solutions here, but was not sattisfied with them, so I created my own module. It is called mikro-config and the main difference is that it honors convention over configuration, so you can just require the module and start using it.

You store your configuration in either plain js, or json files from /config folder. First it loads default.js file, then all other files from /config directory, then it loads environment specific configuration based on $NODE_ENV variable.

It also allows to override this configuration for local development with local.js or environment specific /config/env/$NODE_ENV.local.js.

You can take at look at it here:

https://www.npmjs.com/package/mikro-config

https://github.com/B4nan/mikro-config

How to save .xlsx data to file as a blob

The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data.

Here's what I did on the server side (asp.net mvc core):

string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);

On the client side, I did the following code:

const xhr = new XMLHttpRequest();

xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");

xhr.onload = () => {
    var bin = atob(xhr.response);
    var ab = s2ab(bin); // from example above
    var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });

    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'demo.xlsx';

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
};

xhr.send();

And it works perfectly for me.

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

I find it easier to think of Joins in the following order:

  • CROSS JOIN - a Cartesian product of both tables. ALL joins begin here
  • INNER JOIN - a CROSS JOIN with a filter added.
  • OUTER JOIN - an INNER JOIN with missing elements (from either LEFT or RIGHT table) added afterward.

Until I figured out this (relatively) simple model, JOINS were always a bit more of a black art. Now they make perfect sense.

Hope this helps more than it confuses.

Java ArrayList for integers

List of Integer.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

Excel: Can I create a Conditional Formula based on the Color of a Cell?

You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel

In your worksheet, you can use the following: =GetFillColor(B5)

Java converting Image to BufferedImage

If you are getting back a sun.awt.image.ToolkitImage, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage.

So instead of your last line of code where you are casting you would just do:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();

How to show MessageBox on asp.net?

Message box is only defaultly available for windows form application.If you want to use the message box resource the you would have to use 'using system.windows.forms' to enable the message box for web forms mode.

Use Excel pivot table as data source for another Pivot Table

In a new sheet (where you want to create a new pivot table) press the key combination (Alt+D+P). In the list of data source options choose "Microsoft Excel list of database". Click Next and select the pivot table that you want to use as a source (select starting with the actual headers of the fields). I assume that this range is rather static and if you refresh the source pivot and it changes it's size you would have to re-size the range as well. Hope this helps.

Is it possible to use std::string in a constexpr?

Since the problem is the non-trivial destructor so if the destructor is removed from the std::string, it's possible to define a constexpr instance of that type. Like this

struct constexpr_str {
    char const* str;
    std::size_t size;

    // can only construct from a char[] literal
    template <std::size_t N>
    constexpr constexpr_str(char const (&s)[N])
        : str(s)
        , size(N - 1) // not count the trailing nul
    {}
};

int main()
{
    constexpr constexpr_str s("constString");

    // its .size is a constexpr
    std::array<int, s.size> a;
    return 0;
}

getFilesDir() vs Environment.getDataDirectory()

getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Environment.getDataDirectory()

Return the user data directory.

handling dbnull data in vb.net

You can also use the Convert.ToString() and Convert.ToInteger() methods to convert items with DB null effectivly.

Android Studio doesn't see device

I am using Android Studio 4.0, Android Studio said "Device was detected by ADB but not Android Studio". I tried re-enable "developer option" and "usb debug", re-plugin the usb, but no luck. I restart the Android Studio and it works.

Please try restart the Android Studio.

Hope it could save you some time.

In python, how do I cast a class object to a dict

I think this will work for you.

class A(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __iter__(self):
        return self.__dict__.iteritems()

a = A(1,2,3,4,5)
print dict(a)

Output

{'a': 1, 'c': 3, 'b': 2, 'sum': 6, 'version': 5}

Why would you use String.Equals over ==?

It's entirely likely that a large portion of the developer base comes from a Java background where using == to compare strings is wrong and doesn't work.

In C# there's no (practical) difference (for strings) as long as they are typed as string.

If they are typed as object or T then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.

How do AX, AH, AL map onto EAX?

no your ans is Wrong

Selection of Al and Ah is from AX not from EAX

e.g

EAX=0000 0000 0000 0000 0000 0000 0000 0111

So if we call AX it should return

0000 0000 0000 0111

if we call AH it should return

0000 0000

and when we call AL it should return

0000 0111

Example number 2

EAX: 22 33 55 77
AX: 55 77
AH: 55    
AL: 77

example 3

EAX: 1111 0000 0000 0000 0000 0000 0000 0111    
AX= 0000 0000 0000 0111
AH= 0000 0000
AL= 0000 0111  

Populating a ComboBox using C#

  Language[] items = new Language[]{new Language("English", "En"),
                new Language("Italian", "It")};

            languagesCombo.ValueMember = "Alias";
            languagesCombo.DisplayMember = "FullName";
            languagesCombo.DataSource = items.ToList();

            languagesCombo.DropDownStyle = ComboBoxStyle.DropDownList;

 class Language
    {
        public string FullName { get; set; }
        public string Alias { get; set; }

        public Language(string fullName, string alias)
        {
            this.FullName = fullName;
            this.Alias = alias;
        }
    }

By making your drop down box "read-only" I am assuming you want to prevent user's typing in other options as opposed to being fully read-only where users cannot select a value??

If you wanted it to be fully read-only you could set the enabled property to be false.

Concatenate two slices in Go

append( ) function and spread operator

Two slices can be concatenated using append method in the standard golang library. Which is similar to the variadic function operation. So we need to use ...

package main

import (
    "fmt"
)

func main() {
    x := []int{1, 2, 3}
    y := []int{4, 5, 6}
    z := append([]int{}, append(x, y...)...)
    fmt.Println(z)
}

output of the above code is: [1 2 3 4 5 6]

How to loop through each and every row, column and cells in a GridView and get its value

The easiest would be using a foreach:

foreach(GridViewRow row in GridView2.Rows)
{
    // here you'll get all rows with RowType=DataRow
    // others like Header are omitted in a foreach
}

Edit: According to your edits, you are accessing the column incorrectly, you should start with 0:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

No restricted globals

/* eslint no-restricted-globals:0 */

is another alternate approach

How to determine if OpenSSL and mod_ssl are installed on Apache2

Just look in the ssl_engine.log in your Apache log directory where you should find something like:

[ssl:info] [pid 5963:tid 139718276048640] AH01876: mod_ssl/2.4.9 compiled against Server: Apache/2.4.9, Library: OpenSSL/1.0.1h

Callback functions in C++

Note: Most of the answers cover function pointers which is one possibility to achieve "callback" logic in C++, but as of today not the most favourable one I think.

What are callbacks(?) and why to use them(!)

A callback is a callable (see further down) accepted by a class or function, used to customize the current logic depending on that callback.

One reason to use callbacks is to write generic code which is independant from the logic in the called function and can be reused with different callbacks.

Many functions of the standard algorithms library <algorithm> use callbacks. For example the for_each algorithm applies an unary callback to every item in a range of iterators:

template<class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
  for (; first != last; ++first) {
    f(*first);
  }
  return f;
}

which can be used to first increment and then print a vector by passing appropriate callables for example:

std::vector<double> v{ 1.0, 2.2, 4.0, 5.5, 7.2 };
double r = 4.0;
std::for_each(v.begin(), v.end(), [&](double & v) { v += r; });
std::for_each(v.begin(), v.end(), [](double v) { std::cout << v << " "; });

which prints

5 6.2 8 9.5 11.2

Another application of callbacks is the notification of callers of certain events which enables a certain amount of static / compile time flexibility.

Personally, I use a local optimization library that uses two different callbacks:

  • The first callback is called if a function value and the gradient based on a vector of input values is required (logic callback: function value determination / gradient derivation).
  • The second callback is called once for each algorithm step and receives certain information about the convergence of the algorithm (notification callback).

Thus, the library designer is not in charge of deciding what happens with the information that is given to the programmer via the notification callback and he needn't worry about how to actually determine function values because they're provided by the logic callback. Getting those things right is a task due to the library user and keeps the library slim and more generic.

Furthermore, callbacks can enable dynamic runtime behaviour.

Imagine some kind of game engine class which has a function that is fired, each time the users presses a button on his keyboard and a set of functions that control your game behaviour. With callbacks you can (re)decide at runtime which action will be taken.

void player_jump();
void player_crouch();

class game_core
{
    std::array<void(*)(), total_num_keys> actions;
    // 
    void key_pressed(unsigned key_id)
    {
        if(actions[key_id]) actions[key_id]();
    }
    // update keybind from menu
    void update_keybind(unsigned key_id, void(*new_action)())
    {
        actions[key_id] = new_action;
    }
};

Here the function key_pressed uses the callbacks stored in actions to obtain the desired behaviour when a certain key is pressed. If the player chooses to change the button for jumping, the engine can call

game_core_instance.update_keybind(newly_selected_key, &player_jump);

and thus change the behaviour of a call to key_pressed (which the calls player_jump) once this button is pressed the next time ingame.

What are callables in C++(11)?

See C++ concepts: Callable on cppreference for a more formal description.

Callback functionality can be realized in several ways in C++(11) since several different things turn out to be callable*:

  • Function pointers (including pointers to member functions)
  • std::function objects
  • Lambda expressions
  • Bind expressions
  • Function objects (classes with overloaded function call operator operator())

* Note: Pointer to data members are callable as well but no function is called at all.

Several important ways to write callbacks in detail

  • X.1 "Writing" a callback in this post means the syntax to declare and name the callback type.
  • X.2 "Calling" a callback refers to the syntax to call those objects.
  • X.3 "Using" a callback means the syntax when passing arguments to a function using a callback.

Note: As of C++17, a call like f(...) can be written as std::invoke(f, ...) which also handles the pointer to member case.

1. Function pointers

A function pointer is the 'simplest' (in terms of generality; in terms of readability arguably the worst) type a callback can have.

Let's have a simple function foo:

int foo (int x) { return 2+x; }

1.1 Writing a function pointer / type notation

A function pointer type has the notation

return_type (*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to foo has the type:
int (*)(int)

where a named function pointer type will look like

return_type (* name) (parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. f_int_t is a type: function pointer taking one int argument, returning int
typedef int (*f_int_t) (int); 

// foo_p is a pointer to function taking int returning int
// initialized by pointer to function foo taking int returning int
int (* foo_p)(int) = &foo; 
// can alternatively be written as 
f_int_t foo_p = &foo;

The using declaration gives us the option to make things a little bit more readable, since the typedef for f_int_t can also be written as:

using f_int_t = int(*)(int);

Where (at least for me) it is clearer that f_int_t is the new type alias and recognition of the function pointer type is also easier

And a declaration of a function using a callback of function pointer type will be:

// foobar having a callback argument named moo of type 
// pointer to function returning int taking int as its argument
int foobar (int x, int (*moo)(int));
// if f_int is the function pointer typedef from above we can also write foobar as:
int foobar (int x, f_int_t moo);

1.2 Callback call notation

The call notation follows the simple function call syntax:

int foobar (int x, int (*moo)(int))
{
    return x + moo(x); // function pointer moo called using argument x
}
// analog
int foobar (int x, f_int_t moo)
{
    return x + moo(x); // function pointer moo called using argument x
}

1.3 Callback use notation and compatible types

A callback function taking a function pointer can be called using function pointers.

Using a function that takes a function pointer callback is rather simple:

 int a = 5;
 int b = foobar(a, foo); // call foobar with pointer to foo as callback
 // can also be
 int b = foobar(a, &foo); // call foobar with pointer to foo as callback

1.4 Example

A function ca be written that doesn't rely on how the callback works:

void tranform_every_int(int * v, unsigned n, int (*fp)(int))
{
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = fp(v[i]);
  }
}

where possible callbacks could be

int double_int(int x) { return 2*x; }
int square_int(int x) { return x*x; }

used like

int a[5] = {1, 2, 3, 4, 5};
tranform_every_int(&a[0], 5, double_int);
// now a == {2, 4, 6, 8, 10};
tranform_every_int(&a[0], 5, square_int);
// now a == {4, 16, 36, 64, 100};

2. Pointer to member function

A pointer to member function (of some class C) is a special type of (and even more complex) function pointer which requires an object of type C to operate on.

struct C
{
    int y;
    int foo(int x) const { return x+y; }
};

2.1 Writing pointer to member function / type notation

A pointer to member function type for some class T has the notation

// can have more or less parameters
return_type (T::*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to C::foo has the type
int (C::*) (int)

where a named pointer to member function will -in analogy to the function pointer- look like this:

return_type (T::* name) (parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. a type `f_C_int` representing a pointer to member function of `C`
// taking int returning int is:
typedef int (C::* f_C_int_t) (int x); 

// The type of C_foo_p is a pointer to member function of C taking int returning int
// Its value is initialized by a pointer to foo of C
int (C::* C_foo_p)(int) = &C::foo;
// which can also be written using the typedef:
f_C_int_t C_foo_p = &C::foo;

Example: Declaring a function taking a pointer to member function callback as one of its arguments:

// C_foobar having an argument named moo of type pointer to member function of C
// where the callback returns int taking int as its argument
// also needs an object of type c
int C_foobar (int x, C const &c, int (C::*moo)(int));
// can equivalently declared using the typedef above:
int C_foobar (int x, C const &c, f_C_int_t moo);

2.2 Callback call notation

The pointer to member function of C can be invoked, with respect to an object of type C by using member access operations on the dereferenced pointer. Note: Parenthesis required!

int C_foobar (int x, C const &c, int (C::*moo)(int))
{
    return x + (c.*moo)(x); // function pointer moo called for object c using argument x
}
// analog
int C_foobar (int x, C const &c, f_C_int_t moo)
{
    return x + (c.*moo)(x); // function pointer moo called for object c using argument x
}

Note: If a pointer to C is available the syntax is equivalent (where the pointer to C must be dereferenced as well):

int C_foobar_2 (int x, C const * c, int (C::*meow)(int))
{
    if (!c) return x;
    // function pointer meow called for object *c using argument x
    return x + ((*c).*meow)(x); 
}
// or equivalent:
int C_foobar_2 (int x, C const * c, int (C::*meow)(int))
{
    if (!c) return x;
    // function pointer meow called for object *c using argument x
    return x + (c->*meow)(x); 
}

2.3 Callback use notation and compatible types

A callback function taking a member function pointer of class T can be called using a member function pointer of class T.

Using a function that takes a pointer to member function callback is -in analogy to function pointers- quite simple as well:

 C my_c{2}; // aggregate initialization
 int a = 5;
 int b = C_foobar(a, my_c, &C::foo); // call C_foobar with pointer to foo as its callback

3. std::function objects (header <functional>)

The std::function class is a polymorphic function wrapper to store, copy or invoke callables.

3.1 Writing a std::function object / type notation

The type of a std::function object storing a callable looks like:

std::function<return_type(parameter_type_1, parameter_type_2, parameter_type_3)>

// i.e. using the above function declaration of foo:
std::function<int(int)> stdf_foo = &foo;
// or C::foo:
std::function<int(const C&, int)> stdf_C_foo = &C::foo;

3.2 Callback call notation

The class std::function has operator() defined which can be used to invoke its target.

int stdf_foobar (int x, std::function<int(int)> moo)
{
    return x + moo(x); // std::function moo called
}
// or 
int stdf_C_foobar (int x, C const &c, std::function<int(C const &, int)> moo)
{
    return x + moo(c, x); // std::function moo called using c and x
}

3.3 Callback use notation and compatible types

The std::function callback is more generic than function pointers or pointer to member function since different types can be passed and implicitly converted into a std::function object.

3.3.1 Function pointers and pointers to member functions

A function pointer

int a = 2;
int b = stdf_foobar(a, &foo);
// b == 6 ( 2 + (2+2) )

or a pointer to member function

int a = 2;
C my_c{7}; // aggregate initialization
int b = stdf_C_foobar(a, c, &C::foo);
// b == 11 == ( 2 + (7+2) )

can be used.

3.3.2 Lambda expressions

An unnamed closure from a lambda expression can be stored in a std::function object:

int a = 2;
int c = 3;
int b = stdf_foobar(a, [c](int x) -> int { return 7+c*x; });
// b == 15 ==  a + (7*c*a) == 2 + (7+3*2)

3.3.3 std::bind expressions

The result of a std::bind expression can be passed. For example by binding parameters to a function pointer call:

int foo_2 (int x, int y) { return 9*x + y; }
using std::placeholders::_1;

int a = 2;
int b = stdf_foobar(a, std::bind(foo_2, _1, 3));
// b == 23 == 2 + ( 9*2 + 3 )
int c = stdf_foobar(a, std::bind(foo_2, 5, _1));
// c == 49 == 2 + ( 9*5 + 2 )

Where also objects can be bound as the object for the invocation of pointer to member functions:

int a = 2;
C const my_c{7}; // aggregate initialization
int b = stdf_foobar(a, std::bind(&C::foo, my_c, _1));
// b == 1 == 2 + ( 2 + 7 )

3.3.4 Function objects

Objects of classes having a proper operator() overload can be stored inside a std::function object, as well.

struct Meow
{
  int y = 0;
  Meow(int y_) : y(y_) {}
  int operator()(int x) { return y * x; }
};
int a = 11;
int b = stdf_foobar(a, Meow{8});
// b == 99 == 11 + ( 8 * 11 )

3.4 Example

Changing the function pointer example to use std::function

void stdf_tranform_every_int(int * v, unsigned n, std::function<int(int)> fp)
{
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = fp(v[i]);
  }
}

gives a whole lot more utility to that function because (see 3.3) we have more possibilities to use it:

// using function pointer still possible
int a[5] = {1, 2, 3, 4, 5};
stdf_tranform_every_int(&a[0], 5, double_int);
// now a == {2, 4, 6, 8, 10};

// use it without having to write another function by using a lambda
stdf_tranform_every_int(&a[0], 5, [](int x) -> int { return x/2; });
// now a == {1, 2, 3, 4, 5}; again

// use std::bind :
int nine_x_and_y (int x, int y) { return 9*x + y; }
using std::placeholders::_1;
// calls nine_x_and_y for every int in a with y being 4 every time
stdf_tranform_every_int(&a[0], 5, std::bind(nine_x_and_y, _1, 4));
// now a == {13, 22, 31, 40, 49};

4. Templated callback type

Using templates, the code calling the callback can be even more general than using std::function objects.

Note that templates are a compile-time feature and are a design tool for compile-time polymorphism. If runtime dynamic behaviour is to be achieved through callbacks, templates will help but they won't induce runtime dynamics.

4.1 Writing (type notations) and calling templated callbacks

Generalizing i.e. the std_ftransform_every_int code from above even further can be achieved by using templates:

template<class R, class T>
void stdf_transform_every_int_templ(int * v,
  unsigned const n, std::function<R(T)> fp)
{
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = fp(v[i]);
  }
}

with an even more general (as well as easiest) syntax for a callback type being a plain, to-be-deduced templated argument:

template<class F>
void transform_every_int_templ(int * v, 
  unsigned const n, F f)
{
  std::cout << "transform_every_int_templ<" 
    << type_name<F>() << ">\n";
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = f(v[i]);
  }
}

Note: The included output prints the type name deduced for templated type F. The implementation of type_name is given at the end of this post.

The most general implementation for the unary transformation of a range is part of the standard library, namely std::transform, which is also templated with respect to the iterated types.

template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first,
  UnaryOperation unary_op)
{
  while (first1 != last1) {
    *d_first++ = unary_op(*first1++);
  }
  return d_first;
}

4.2 Examples using templated callbacks and compatible types

The compatible types for the templated std::function callback method stdf_transform_every_int_templ are identical to the above mentioned types (see 3.4).

Using the templated version however, the signature of the used callback may change a little:

// Let
int foo (int x) { return 2+x; }
int muh (int const &x) { return 3+x; }
int & woof (int &x) { x *= 4; return x; }

int a[5] = {1, 2, 3, 4, 5};
stdf_transform_every_int_templ<int,int>(&a[0], 5, &foo);
// a == {3, 4, 5, 6, 7}
stdf_transform_every_int_templ<int, int const &>(&a[0], 5, &muh);
// a == {6, 7, 8, 9, 10}
stdf_transform_every_int_templ<int, int &>(&a[0], 5, &woof);

Note: std_ftransform_every_int (non templated version; see above) does work with foo but not using muh.

// Let
void print_int(int * p, unsigned const n)
{
  bool f{ true };
  for (unsigned i = 0; i < n; ++i)
  {
    std::cout << (f ? "" : " ") << p[i]; 
    f = false;
  }
  std::cout << "\n";
}

The plain templated parameter of transform_every_int_templ can be every possible callable type.

int a[5] = { 1, 2, 3, 4, 5 };
print_int(a, 5);
transform_every_int_templ(&a[0], 5, foo);
print_int(a, 5);
transform_every_int_templ(&a[0], 5, muh);
print_int(a, 5);
transform_every_int_templ(&a[0], 5, woof);
print_int(a, 5);
transform_every_int_templ(&a[0], 5, [](int x) -> int { return x + x + x; });
print_int(a, 5);
transform_every_int_templ(&a[0], 5, Meow{ 4 });
print_int(a, 5);
using std::placeholders::_1;
transform_every_int_templ(&a[0], 5, std::bind(foo_2, _1, 3));
print_int(a, 5);
transform_every_int_templ(&a[0], 5, std::function<int(int)>{&foo});
print_int(a, 5);

The above code prints:

1 2 3 4 5
transform_every_int_templ <int(*)(int)>
3 4 5 6 7
transform_every_int_templ <int(*)(int&)>
6 8 10 12 14
transform_every_int_templ <int& (*)(int&)>
9 11 13 15 17
transform_every_int_templ <main::{lambda(int)#1} >
27 33 39 45 51
transform_every_int_templ <Meow>
108 132 156 180 204
transform_every_int_templ <std::_Bind<int(*(std::_Placeholder<1>, int))(int, int)>>
975 1191 1407 1623 1839
transform_every_int_templ <std::function<int(int)>>
977 1193 1409 1625 1841

type_name implementation used above

#include <type_traits>
#include <typeinfo>
#include <string>
#include <memory>
#include <cxxabi.h>

template <class T>
std::string type_name()
{
  typedef typename std::remove_reference<T>::type TR;
  std::unique_ptr<char, void(*)(void*)> own
    (abi::__cxa_demangle(typeid(TR).name(), nullptr,
    nullptr, nullptr), std::free);
  std::string r = own != nullptr?own.get():typeid(TR).name();
  if (std::is_const<TR>::value)
    r += " const";
  if (std::is_volatile<TR>::value)
    r += " volatile";
  if (std::is_lvalue_reference<T>::value)
    r += " &";
  else if (std::is_rvalue_reference<T>::value)
    r += " &&";
  return r;
}

SQL Sum Multiple rows into one

Thank you for your responses. Turns out my problem was a database issue with duplicate entries, not with my logic. A quick table sync fixed that and the SUM feature worked as expected. This is all still useful knowledge for the SUM feature and is worth reading if you are having trouble using it.

TypeError: Image data can not convert to float

This happened for me when I was trying to plot an imagePath, instead of the image itself. The fix was to load the image, and plotting it.

How do I make a simple makefile for gcc on Linux?

The simplest make file can be

all : test

test : test.o
        gcc -o test test.o 

test.o : test.c
        gcc -c test.c

clean :
        rm test *.o

How to convert object array to string array in Java

I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.

First, let's see what Oracle has to say

 * <p>The returned array will be "safe" in that no references to it are
 * maintained by this list.  (In other words, this method must
 * allocate a new array even if this list is backed by an array).
 * The caller is thus free to modify the returned array.

It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?

List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();   

Probably, many of you would think that this code is doing the same, but it does not.

Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;

When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!

Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;   

So tList.toArray is instantiating a Objects and not Strings...

Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following

String tArray[] = tList.toArray(new String[0]);

Hope it is clear enough.

What's the easiest way to install a missing Perl module?

On Fedora you can use

# yum install foo

as long as Fedora has an existing package for the module.

What is special about /dev/tty?

The 'c' means it's a character special file.

What can be the reasons of connection refused errors?

Connection refused means that the port you are trying to connect to is not actually open.

So either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.

A common mistake is not specifying the port number when binding or connecting in network byte order...

How to make MySQL handle UTF-8 properly

The short answer: Use utf8mb4 in 4 places:

  • The bytes in your client are utf8, not latin1/cp1251/etc.
  • SET NAMES utf8mb4 or something equivalent when establishing the client's connection to MySQL
  • CHARACTER SET utf8mb4 on all tables/columns -- except columns that are strictly ascii/hex/country_code/zip_code/etc.
  • <meta charset charset=UTF-8> if you are outputting to HTML. (Yes the spelling is different here.)

More info ;
UTF8 all the way

The above links provide the "detailed canonical answer is required to address all the concerns". -- There is a space limit on this forum.

Edit

In addition to CHARACTER SET utf8mb4 containing "all" the world's characters, COLLATION utf8mb4_unicode_520_ci is arguable the 'best all-around' collation to use. (There are also Turkish, Spanish, etc, collations for those who want the nuances in those languages.)

Exporting results of a Mysql query to excel?

This is an old question, but it's still one of the first results on Google. The fastest way to do this is to link MySQL directly to Excel using ODBC queries or MySQL For Excel. The latter was mentioned in a comment to the OP, but I felt it really deserved its own answer because exporting to CSV is not the most efficient way to achieve this.

ODBC Queries - This is a little bit more complicated to setup, but it's a lot more flexible. For example, the MySQL For Excel add-in doesn't allow you to use WHERE clauses in the query expressions. The flexibility of this method also allows you to use the data in more complex ways.

MySQL For Excel - Use this add-in if you don't need to do anything complex with the query or if you need to get something accomplished quickly and easily. You can make views in your database to workaround some of the query limitations.

Reading file contents on the client-side in javascript in various browsers

In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file"> tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.

_x000D_
_x000D_
function onFileLoad(elementId, event) {_x000D_
    document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
    if (typeof window.FileReader !== 'function')_x000D_
        throw ("The file API isn't supported on this browser.");_x000D_
    let input = event.target;_x000D_
    if (!input)_x000D_
        throw ("The browser does not properly implement the event object");_x000D_
    if (!input.files)_x000D_
        throw ("This browser does not support the `files` property of the file input.");_x000D_
    if (!input.files[0])_x000D_
        return undefined;_x000D_
    let file = input.files[0];_x000D_
    let fr = new FileReader();_x000D_
    fr.onload = onLoadFileHandler;_x000D_
    fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
_x000D_
_x000D_

How to create an infinite loop in Windows batch file?

A really infinite loop, counting from 1 to 10 with increment of 0.
You need infinite or more increments to reach the 10.

for /L %%n in (1,0,10) do (
  echo do stuff
  rem ** can't be leaved with a goto (hangs)
  rem ** can't be stopped with exit /b (hangs)
  rem ** can be stopped with exit
  rem ** can be stopped with a syntax error
  call :stop
)

:stop
call :__stop 2>nul

:__stop
() creates a syntax error, quits the batch

This could be useful if you need a really infinite loop, as it is much faster than a goto :loop version because a for-loop is cached completely once at startup.

How does one generate a random number in Apple's Swift language?

Use arc4random_uniform(n) for a random integer between 0 and n-1.

let diceRoll = Int(arc4random_uniform(6) + 1)

Cast the result to Int so you don't have to explicitly type your vars as UInt32 (which seems un-Swifty).

How to Customize the time format for Python logging?

if using logging.config.fileConfig with a configuration file use something like:

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

Android Lint contentDescription warning

Non textual widgets need a content description in some ways to describe textually the image so that screens readers to be able to describe the user interface. You can ignore the property xmlns:tools="http://schemas.android.com/tools"
tools:ignore="contentDescription"
or define the property android:contentDescription="your description"

How to specify in crontab by what user to run script?

Since you're running Ubuntu, your system crontab is located at /etc/crontab.

As the root user (or using sudo), you can simply edit this file and specify the user that should run this command. Here is the format of entries in the system crontab and how you should enter your command:

# m h dom mon dow user  command
*/1 * * * * www-data php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1

Of course the permissions for your php script and your log file should be set so that the www-data user has access to them.

What does -> mean in C++?

member b of object pointed to by a a->b

I do not want to inherit the child opacity from the parent in CSS

As others have mentioned in this and other similar threads, the best way to avoid this problem is to use RGBA/HSLA or else use a transparent PNG.

But, if you want a ridiculous solution, similar to the one linked in another answer in this thread (which is also my website), here's a brand new script I wrote that fixes this problem automatically, called thatsNotYoChild.js:

http://www.impressivewebs.com/fixing-parent-child-opacity/

Basically it uses JavaScript to remove all children from the parent div, then reposition the child elements back to where they should be without actually being children of that element anymore.

To me, this should be a last resort, but I thought it would be fun to write something that did this, if anyone wants to do this.

How do I find out if a column exists in a VB.Net DataRow

DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.

    If DataRow.Table.Columns.Contains("column") Then
        MsgBox("YAY")
    End If

CSS horizontal scroll

check this link here i change display:inline-block http://cssdesk.com/gUGBH

How do I specify different layouts for portrait and landscape orientations?

Create a new directory layout-land, then create xml file with same name in layout-land as it was layout directory and align there your content for Landscape mode.

Note that id of content in both xml is same.

ARM compilation error, VFP registers used by executable, not object file

"Note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries." https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html arm-none-eabi-gcc.exe

Silicon Labs "kjostera" "Employee" response to EFR32 Flex Gecko (crossreference Cortex-M4F): "So code compiled with the softfp ABI is not link time compatible with code compiled with hardfp ABI. So since we currently only support RAIL library compiled using the softfp ABI, this means that you will have to build your application as well using the softfp ABI." "Note that using softfp ABI does not mean that your code cannot use FPU instructions. Any code doing floating point arithmetic will use the FPU when the compiler thinks that it makes sense." "kjostera" then goes on to demonstrate that the GCC 7 generated Assembly for both the case of -mfloat-abi=softfp and -mfloat-abi=hard, the vmul.f32 instruction is invoked and the instruction count is 10 for softfp and 9 for hard. https://www.silabs.com/community/mcu/32-bit/forum.topic.html/enable_fpu_in_rail-p-SEYr https://www.silabs.com/documents/public/data-sheets/efr32fg1-datasheet.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg12-rm.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg13-rm.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg14-rm.pdf

How can I write to the console in PHP?

Though this is an old question, I've been looking for this. Here's my compilation of some solutions answered here and some other ideas found elsewhere to get a one-size-fits-all solution.

CODE :

    // Post to browser console
    function console($data, $is_error = false, $file = false, $ln = false) {
        if(!function_exists('console_wer')) {
            function console_wer($data, $is_error = false, $bctr, $file, $ln) {
                echo '<div display="none">'.'<script type="text/javascript">'.(($is_error!==false) ? 'if(typeof phperr_to_cns === \'undefined\') { var phperr_to_cns = 1; document.addEventListener("DOMContentLoaded", function() { setTimeout(function(){ alert("Alert. see console."); }, 4000); });  }' : '').' console.group("PHP '.(($is_error) ? 'error' : 'log').' from "+window.atob("'.base64_encode((($file===false) ? $bctr['file'] : $file)).'")'.((($ln!==false && $file!==false) || $bctr!==false) ? '+" on line '.(($ln===false) ? $bctr['line'] : $ln).' :"' : '+" :"').'); console.'.(($is_error) ? 'error' : 'log').'('.((is_array($data)) ? 'JSON.parse(window.atob("'.base64_encode(json_encode($data)).'"))' : '"'.$data.'"').'); console.groupEnd();</script></div>'; return true;
            }
        }
        return @console_wer($data, $is_error, (($file===false && $ln===false) ? array_shift(debug_backtrace()) : false), $file, $ln);
    }
    
    //PHP Exceptions handler
    function exceptions_to_console($svr, $str, $file, $ln) {
        if(!function_exists('severity_tag')) {
            function severity_tag($svr) {
                $names = [];
                $consts = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
                foreach ($consts as $code => $name) {
                    if ($svr & $code) $names []= $name;
                }
                return join(' | ', $names);
            }
        }
        if (error_reporting() == 0) {
            return false;
        }
        if(error_reporting() & $svr) {
            console(severity_tag($svr).' : '.$str, true, $file, $ln);
        }
    }

    // Divert php error traffic
    error_reporting(E_ALL);  
    ini_set("display_errors", "1");
    set_error_handler('exceptions_to_console');

TESTS & USAGE :

Usage is simple. Include first function for posting to console manually. Use second function for diverting php exception handling. Following test should give an idea.

    // Test 1 - Auto - Handle php error and report error with severity info
    $a[1] = 'jfksjfks';
    try {
          $b = $a[0];
    } catch (Exception $e) {
          echo "jsdlkjflsjfkjl";
    }

    // Test 2 - Manual - Without explicitly providing file name and line no.
          console(array(1 => "Hi", array("hellow")), false);
    
    // Test 3 - Manual - Explicitly providing file name and line no.
          console(array(1 => "Error", array($some_result)), true, 'my file', 2);
    
    // Test 4 - Manual - Explicitly providing file name only.
          console(array(1 => "Error", array($some_result)), true, 'my file');
    

EXPLANATION :

  • The function console($data, $is_error, $file, $fn) takes string or array as first argument and posts it on console using js inserts.

  • Second argument is a flag to differentiate normal logs against errors. For errors, we're adding event listeners to inform us through alerts if any errors were thrown, also highlighting in console. This flag is defaulted to false.

  • Third and fourth arguments are explicit declarations of file and line numbers, which is optional. If absent, they're defaulted to using the predefined php function debug_backtrace() to fetch them for us.

  • Next function exceptions_to_console($svr, $str, $file, $ln) has four arguments in the order called by php default exception handler. Here, the first argument is severity, which we further crosscheck with predefined constants using function severity_tag($code) to provide more info on error.

NOTICE :

  • Above code uses JS functions and methods that are not available in older browsers. For compatibility with older versions, it needs replacements.

  • Above code is for testing environments, where you alone have access to the site. Do not use this in live (production) websites.

SUGGESTIONS :

  • First function console() threw some notices, so I've wrapped them within another function and called it using error control operator '@'. This can be avoided if you didn't mind the notices.

  • Last but not least, alerts popping up can be annoying while coding. For this I'm using this beep (found in solution : https://stackoverflow.com/a/23395136/6060602) instead of popup alerts. It's pretty cool and possibilities are endless, you can play your favorite tunes and make coding less stressful.

Set default syntax to different filetype in Sublime Text 2

In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice].

Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as... at the top of the menu.

Updated 2016-04-19: As of now, this also works for Sublime Text 3.

Padding characters in printf

using echo only

The anwser of @Dennis Williamson is working just fine except I was trying to do this using echo. Echo allows to output charcacters with a certain color. Using printf would remove that coloring and print unreadable characters. Here's the echo-only alternative:

string1=abc
string2=123456
echo -en "$string1 "
for ((i=0; i< (25 - ${#string1}); i++)){ echo -n "-"; }
echo -e " $string2"

output:

abc ---------------------- 123456

of course you can use all the variations proposed by @Dennis Williamson whether you want the right part to be left- or right-aligned (replacing 25 - ${#string1} by 25 - ${#string1} - ${#string2} etc...

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

Print empty line?

Python's print function adds a newline character to its input. If you give it no input it will just print a newline character

print()

Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text

my_str = "hello world"
print(my_str + "\n")

If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")

print("hello world", end="\n\n")

But you probably don't need this last method, the two before are much clearer.

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;
    title[title.length]=titleValue;
    names[names.length]=actorValue;
    tickets[tickets.length]=ticketsValue;
  }

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  }
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  }
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  }
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup
}

Here's a jsfiddle for you to play around.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Open a terminal and take a look at:

/Applications/Python 3.6/Install Certificates.command

Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.

(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)

Generate GUID in MySQL for existing Data?

I faced mostly the same issue. Im my case uuid is stored as BINARY(16) and has NOT NULL UNIQUE constraints. And i faced with the issue when the same UUID was generated for every row, and UNIQUE constraint does not allow this. So this query does not work:

UNHEX(REPLACE(uuid(), '-', ''))

But for me it worked, when i used such a query with nested inner select:

UNHEX(REPLACE((SELECT uuid()), '-', ''))

Then is produced unique result for every entry.

What is polymorphism, what is it for, and how is it used?

Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.

Here is an example in C#. Create four classes within a console application:

public abstract class Vehicle
{
    public abstract int Wheels;
}

public class Bicycle : Vehicle
{
    public override int Wheels()
    {
        return 2;
    }
}

public class Car : Vehicle
{
    public override int Wheels()
    {
        return 4;
    }
}

public class Truck : Vehicle
{
    public override int Wheels()
    {
        return 18;
    }
}

Now create the following in the Main() of the module for the console application:

public void Main()
{
    List<Vehicle> vehicles = new List<Vehicle>();

    vehicles.Add(new Bicycle());
    vehicles.Add(new Car());
    vehicles.Add(new Truck());

    foreach (Vehicle v in vehicles)
    {
        Console.WriteLine(
            string.Format("A {0} has {1} wheels.",
                v.GetType().Name, v.Wheels));
    }
}

In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.

We then add a Bicycle, Car and Truck to the list.

Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.

This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.

I hope that this helps you.

How do I list all the columns in a table?

Example:

select Table_name as [Table] , column_name as [Column] , Table_catalog as [Database], table_schema as [Schema]  from information_schema.columns
where table_schema = 'dbo'
order by Table_name,COLUMN_NAME

Just my code

Get data from php array - AJAX - jQuery

you cannot access array (php array) from js try

<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>

and js

$(document).ready( function() {
$('#prev').click(function() {
  $.ajax({
  type: 'POST',
  url: 'ajax.php',
  data: 'id=testdata',
  cache: false,
  success: function(data) {
    result=data.split('~');
    $('#content1').html(result[0]);
  },
  });
});
});

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

How do I test a private function or a class that has private methods, fields or inner classes?

First, I'll throw this question out: Why do your private members need isolated testing? Are they that complex, providing such complicated behaviors as to require testing apart from the public surface? It's unit testing, not 'line-of-code' testing. Don't sweat the small stuff.

If they are that big, big enough that these private members are each a 'unit' large in complexity -- consider refactoring such private members out of this class.

If refactoring is inappropriate or infeasible, can you use the strategy pattern to replace access to these private member functions / member classes when under unit test? Under unit test, the strategy would provide added validation, but in release builds it would be simple passthrough.

CSS3 background image transition

You can transition background-image. Use the CSS below on the img element:

-webkit-transition: background-image 0.2s ease-in-out;
transition: background-image 0.2s ease-in-out;

This is supported natively by Chrome, Opera and Safari. Firefox hasn't implemented it yet (bugzil.la). Not sure about IE.

How can I check if a URL exists via PHP?

kind of an old thread, but.. i do this:

$file = 'http://www.google.com';
$file_headers = @get_headers($file);
if ($file_headers) {
    $exists = true;
} else {
    $exists = false;
}

How to convert an object to JSON correctly in Angular 2 with TypeScript

Because you're encapsulating the product again. Try to convert it like so:

let body = JSON.stringify(product); 

What's the environment variable for the path to the desktop?

This is not a solution but I hope it helps: This comes close except that when the KEY = %userprofile%\desktop the copy fails even though zdesktop=%userprofile%\desktop. I think because the embedded %userprofile% is not getting translated.

REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop>z.out
for /f "tokens=3 skip=4" %%t in (z.out) do set zdesktop=%%t
copy myicon %zdesktop%
set zdesktop=
del z.out

So it sucessfully parses out the REG key but if the key contains an embedded %var% it doesn't get translated during the copy command.

Can I override and overload static methods in Java?

Overloading is also called static binding, so as soon as the word static is used it means a static method cannot show run-time polymorphism.

We cannot override a static method but presence of different implementations of the same static method in a super class and its sub class is valid. Its just that the derived class will hide the implementations of the base class.

For static methods, the method call depends on the type of reference and not which object is being referred, i.e. Static method belongs only to a class and not its instances , so the method call is decided at the compile time itself.

Whereas in case of method overloading static methods can be overloaded iff they have diff number or types of parameters. If two methods have the same name and the same parameter list then they cannot be defined different only by using the 'static' keyword.

Regex to check whether a string contains only numbers

If the numbers aren't supposed to be absurdly huge, maybe use:

new RegExp(
    '^' +                           // No leading content.
    '[-+]?' +                       // Optional sign.
    '(?:[0-9]{0,30}\\.)?' +         // Optionally 0-30 decimal digits of mantissa.
    '[0-9]{1,30}' +                 // 1-30 decimal digits of integer or fraction.
    '(?:[Ee][-+]?[1-2]?[0-9])?' +   // Optional exponent 0-29 for scientific notation.
    '$'                             // No trailing content.
)

This tries to avoid some scenarios, just in case:

  • Overflowing any buffers the original string might get passed to.
  • Slowness or oddities caused by denormal numbers like 1E-323.
  • Passing Infinity when a finite number is expected (try 1E309 or -1E309).

How to input a path with a white space?

If the file contains only parameter assignments, you can use the following loop in place of sourcing it:

# Instead of source file.txt
while IFS="=" read name value; do
    declare "$name=$value"
done < file.txt

This saves you having to quote anything in the file, and is also more secure, as you don't risk executing arbitrary code from file.txt.

brew install mysql on macOS

Try solution I provided for MariaDB, high change that it works with MySQL also:

MacOSX homebrew mysql root password

In short, try to login with your username! not root.

Try same name as your MacOS account username, e.g. johnsmit.

To login as root, issue:

mysql -u johnsmit

How can I check if some text exist or not in the page using Selenium?

There is no verifyTextPresent in Selenium 2 webdriver, so you've to check for the text within the page source. See some practical examples below.

Python

In Python driver you can write the following function:

def is_text_present(self, text):
    return str(text) in self.driver.page_source

then use it as:

try: self.is_text_present("Some text.")
except AssertionError as e: self.verificationErrors.append(str(e))

To use regular expression, try:

def is_regex_text_present(self, text = "(?i)Example|Lorem|ipsum"):
    self.assertRegex(self.driver.page_source, text)
    return True

See: FooTest.py file for full example.

Or check below few other alternatives:

self.assertRegexpMatches(self.driver.find_element_by_xpath("html/body/div[1]/div[2]/div/div[1]/label").text, r"^[\s\S]*Weather[\s\S]*$")
assert "Weather" in self.driver.find_element_by_css_selector("div.classname1.classname2>div.clearfix>label").text

Source: Another way to check (assert) if text exists using Selenium Python

Java

In Java the following function:

public void verifyTextPresent(String value)
{
  driver.PageSource.Contains(value);
}

and the usage would be:

try
{
  Assert.IsTrue(verifyTextPresent("Selenium Wiki"));
  Console.WriteLine("Selenium Wiki test is present on the home page");
}
catch (Exception)
{
  Console.WriteLine("Selenium Wiki test is not present on the home page");
}

Source: Using verifyTextPresent in Selenium 2 Webdriver


Behat

For Behat, you can use Mink extension. It has the following methods defined in MinkContext.php:

/**
 * Checks, that page doesn't contain text matching specified pattern
 * Example: Then I should see text matching "Bruce Wayne, the vigilante"
 * Example: And I should not see "Bruce Wayne, the vigilante"
 *
 * @Then /^(?:|I )should not see text matching (?P<pattern>"(?:[^"]|\\")*")$/
 */
public function assertPageNotMatchesText($pattern)
{
    $this->assertSession()->pageTextNotMatches($this->fixStepArgument($pattern));
}

/**
 * Checks, that HTML response contains specified string
 * Example: Then the response should contain "Batman is the hero Gotham deserves."
 * Example: And the response should contain "Batman is the hero Gotham deserves."
 *
 * @Then /^the response should contain "(?P<text>(?:[^"]|\\")*)"$/
 */
public function assertResponseContains($text)
{
    $this->assertSession()->responseContains($this->fixStepArgument($text));
}

Add text to Existing PDF using Python

I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:

  1. read your PDF using PdfFileReader(), we'll call this input
  2. create a new pdf containing your text to add using ReportLab, save this as a string object
  3. read the string object using PdfFileReader(), we'll call this text
  4. create a new PDF object using PdfFileWriter(), we'll call this output
  5. iterate through input and apply .mergePage(*text*.getPage(0)) for each page you want the text added to, then use output.addPage() to add the modified pages to a new document

This works well for simple text additions. See PyPDF's sample for watermarking a document.

Here is some code to answer the question below:

packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
<do something with canvas>
can.save()
packet.seek(0)
input = PdfFileReader(packet)

From here you can merge the pages of the input file with another document.

How to check size of a file using Bash?

If your find handles this syntax, you can use it:

find -maxdepth 1 -name "file.txt" -size -90k

This will output file.txt to stdout if and only if the size of file.txt is less than 90k. To execute a script script if file.txt has a size less than 90k:

find -maxdepth 1 -name "file.txt" -size -90k -exec script \;

set font size in jquery

You can try another way like that:

<div class="content">
        Australia
    </div>

jQuery code:

$(".content").css({
    background: "#d1d1d1",
    fontSize: "30px"
})

Now you can add more css property as you want.

Simple DatePicker-like Calendar

No need to include JQuery or any other third party library.

Specify your input date format in title tag.

HTML:

<script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js">

Body

<input type="text" name="date1" id="date1" alt="date" class="IP_calendar" title="d/m/Y">