Programs & Examples On #Datagridcolumn

How do I make XAML DataGridColumns fill the entire DataGrid?

My 2 Cent ->

Very late to party

DataGrid -> Column -> Width="*" only work if DataGrid parent container has fix width.

example : i put the DataGrid in Grid -> Column whose width="Auto" then Width="*" in DataGrid does not work but if you set Grid -> Column Width="450" mean fixed then it work fine

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

return string with first match Regex

I'd go with:

r = re.search("\d+", ch)
result = return r.group(0) if r else ""

re.search only looks for the first match in the string anyway, so I think it makes your intent slightly more clear than using findall.

How to decode a QR-code image in (preferably pure) Python?

For Windows using ZBar

Pre-requisites:

To decode:

from PIL import Image
from pyzbar import pyzbar

img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)

Alternatively, you can also try using ZBarLight by setting it up as mentioned here:
https://pypi.org/project/zbarlight/

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

  • I had a similar problem (trying to start a Jenkins slave agent on Windows) on Windows 2008R2, Java 1.7.0_15

  • I had two situations that contributed to the problem and that changing both of them fixed it:

    1) Installing Java in a unix-compatible path (changing from c:\Program Files\... to c:\Software\...); I don't think this directly affected the problem described in this thread, but noting the change;

    2) Running Java not through a shortcut. It originally failed with a shortcut, but re-running from the direct executable (C:\Software\Java...\bin\java) worked.

The character encoding of the plain text document was not declared - mootool script

For HTML5:

Simply add to your <head>

 <meta charset="UTF-8"> 

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

How to determine equality for two JavaScript objects?

If you are working in AngularJS, the angular.equals function will determine if two objects are equal. In Ember.js use isEqual.

  • angular.equals - See the docs or source for more on this method. It does a deep compare on arrays too.
  • Ember.js isEqual - See the docs or source for more on this method. It does not do a deep compare on arrays.

_x000D_
_x000D_
var purple = [{"purple": "drank"}];_x000D_
var drank = [{"purple": "drank"}];_x000D_
_x000D_
if(angular.equals(purple, drank)) {_x000D_
    document.write('got dat');_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
_x000D_
_x000D_
_x000D_

Adding backslashes without escaping [Python]

The extra backslash is not actually added; it's just added by the repr() function to indicate that it's a literal backslash. The Python interpreter uses the repr() function (which calls __repr__() on the object) when the result of an expression needs to be printed:

>>> '\\'
'\\'
>>> print '\\'
\
>>> print '\\'.__repr__()
'\\'

When should I use GC.SuppressFinalize()?

That method must be called on the Dispose method of objects that implements the IDisposable, in this way the GC wouldn't call the finalizer another time if someones calls the Dispose method.

See: GC.SuppressFinalize(Object) Method - Microsoft Docs

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

From lambda answer, I have made something closer to the requirements.

boolean imageCreated = false;

Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
    if (!imageCreated) {
        imageCreated = true;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        bmp = Bitmap.createBitmap(400, 400, conf);
        Canvas canvas1 = new Canvas(bmp);

        Paint color = new Paint();
        color.setTextSize(30);
        color.setColor(Color.WHITE);

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inMutable = true;

        Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
                R.drawable.messi,opt);
        Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
        canvas1.drawBitmap(resized, 40, 40, color);

        canvas1.drawText("Le Messi", 30, 40, color);

        currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
                .icon(BitmapDescriptorFactory.fromBitmap(bmp))
                // Specifies the anchor to be at a particular point in the marker image.
                .anchor(0.5f, 1));
    } else {
        currentLocationMarker.setPosition(currentLocation);
    }

}

How to find third or n?? maximum salary from salary table?

//you can find n' th salary from table.if you want to retrive 2nd highest salary then put n=2,if 3rd hs then out n=3 as so on..

SELECT *  FROM tablename t1 
WHERE (N-1) = (SELECT COUNT(DISTINCT(t2.Salary)) 
 FROM tablename t2
WHERE t2.Salary > t1.Salary)

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

"Couldn't read dependencies" error with npm

Recently, I've started to get an error:

npm ERR! install Couldn't read dependencies
npm ERR! Error: Invalid version: "1.0"

So, you may need to specify version of your package with 3 numbers, e.g. 1.0.0 instead of 1.0 if you get similar error.

Virtual Memory Usage from Java under Linux, too much memory used

No, you can't configure memory amount needed by VM. However, note that this is virtual memory, not resident, so it just stays there without harm if not actually used.

Alernatively, you can try some other JVM then Sun one, with smaller memory footprint, but I can't advise here.

Swift how to sort array of custom objects by property value

You can also do something like

images = sorted(images) {$0.fileID > $1.fileID}

so your images array will be stored as sorted

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

The simplest way to comma-delimit a list?

None of the answers uses recursion so far...

public class Main {

    public static String toString(List<String> list, char d) {
        int n = list.size();
        if(n==0) return "";
        return n > 1 ? Main.toString(list.subList(0, n - 1), d) + d
                  + list.get(n - 1) : list.get(0);
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList(new String[]{"1","2","3"});
        System.out.println(Main.toString(list, ','));
    }

}

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

python catch exception and continue try block

You could iterate through your methods...

for m in [do_smth1, do_smth2]:
    try:
        m()
    except:
        pass

Memory errors and list limits?

If you want to circumvent this problem you could also use the shelve. Then you would create files that would be the size of your machines capacity to handle, and only put them on the RAM when necessary, basically writing to the HD and pulling the information back in pieces so you can process it.

Create binary file and check if information is already in it if yes make a local variable to hold it else write some data you deem necessary.

Data = shelve.open('File01')
   for i in range(0,100):
     Matrix_Shelve = 'Matrix' + str(i)
     if Matrix_Shelve in Data:
        Matrix_local = Data[Matrix_Shelve]
     else:
        Data[Matrix_Selve] = 'somenthingforlater'

Hope it doesn't sound too arcaic.

Android XXHDPI resources

As per this PPI calculation tool, Google Nexus 10 has a display density of about 300 DPI...

However, Android documentation states that:

ldpi : ~120dpi mdpi : ~160dpi hdpi : ~240dpi xhdpi : ~320dpi xxhdpi is not specified.

I think we just let Android OS scale up xhdpi resources...

How to customize the back button on ActionBar

Changing back navigation icon differs for ActionBar and Toolbar.

For ActionBar override homeAsUpIndicator attribute:

<style name="CustomThemeActionBar" parent="android:Theme.Holo">
    <item name="homeAsUpIndicator">@drawable/ic_nav_back</item>
</style>

For Toolbar override navigationIcon attribute:

<style name="CustomThemeToolbar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="navigationIcon">@drawable/ic_nav_back</item>
</style>

Selenium -- How to wait until page is completely loaded

It seems that you need to wait for the page to be reloaded before clicking on the "Add" button. In this case you could wait for the "Add Item" element to become stale before clicking on the reloaded element:

WebDriverWait wait = new WebDriverWait(driver, 20);
By addItem = By.xpath("//input[.='Add Item']");

// get the "Add Item" element
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));

//trigger the reaload of the page
driver.findElement(By.id("...")).click();

// wait the element "Add Item" to become stale
wait.until(ExpectedConditions.stalenessOf(element));

// click on "Add Item" once the page is reloaded
wait.until(ExpectedConditions.presenceOfElementLocated(addItem)).click();

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

Taking @Mike Houston's answer as pointer, here is a complete sample code that does Signature and Hash and encryption.

/**
 * @param args
 */
public static void main(String[] args)
{
    try
    {
        boolean useBouncyCastleProvider = false;

        Provider provider = null;
        if (useBouncyCastleProvider)
        {
            provider = new BouncyCastleProvider();
            Security.addProvider(provider);
        }

        String plainText = "This is a plain text!!";

        // KeyPair
        KeyPairGenerator keyPairGenerator = null;
        if (null != provider)
            keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider);
        else
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Signature
        Signature signatureProvider = null;
        if (null != provider)
            signatureProvider = Signature.getInstance("SHA256WithRSA", provider);
        else
            signatureProvider = Signature.getInstance("SHA256WithRSA");
        signatureProvider.initSign(keyPair.getPrivate());

        signatureProvider.update(plainText.getBytes());
        byte[] signature = signatureProvider.sign();

        System.out.println("Signature Output : ");
        System.out.println("\t" + new String(Base64.encode(signature)));

        // Message Digest
        String hashingAlgorithm = "SHA-256";
        MessageDigest messageDigestProvider = null;
        if (null != provider)
            messageDigestProvider = MessageDigest.getInstance(hashingAlgorithm, provider);
        else
            messageDigestProvider = MessageDigest.getInstance(hashingAlgorithm);
        messageDigestProvider.update(plainText.getBytes());

        byte[] hash = messageDigestProvider.digest();

        DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder();
        AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm);

        DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, hash);
        byte[] hashToEncrypt = digestInfo.getEncoded();

        // Crypto
        // You could also use "RSA/ECB/PKCS1Padding" for both the BC and SUN Providers.
        Cipher encCipher = null;
        if (null != provider)
            encCipher = Cipher.getInstance("RSA/NONE/PKCS1Padding", provider);
        else
            encCipher = Cipher.getInstance("RSA");
        encCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());

        byte[] encrypted = encCipher.doFinal(hashToEncrypt);

        System.out.println("Hash and Encryption Output : ");
        System.out.println("\t" + new String(Base64.encode(encrypted)));
    }
    catch (Throwable e)
    {
        e.printStackTrace();
    }
}

You can use BouncyCastle Provider or default Sun Provider.

JSON.parse unexpected token s

You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.

If you want an equivalent to your first example:

var s = '"something"';
var result = JSON.parse(s);

How to compile and run C files from within Notepad++ using NppExec plugin?

I recommend my solution. My situation: g++(cygwin) on win10

My solution: Write a .bat batch file and execute compiler in that batch. compileCpp.bat

@echo off  
set PATH=%PATH%;C:\cygwin64\bin\
rm %~n1.exe
c++.exe -g %~dpnx1 -o %~dpn1.exe
%~n1.exe  

Console:

NPP_EXEC: "runCpp"
NPP_SAVE: E:\hw.cpp
CD: E:\
Current directory: E:\
cmd /c C:\cygwin64\bin\compileCpp.bat "hw.cpp"
Process started >>>
Hello World<<< Process finished. (Exit code 0)
================ READY ================

Convert String to Calendar Object in Java

SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.

For example, the following will return 12 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

While this will return 24 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

Java - remove last known item from ArrayList

First error: You're casting a ClientThread as a String for some reason.

Second error: You're not calling remove on your List.

Is is homework? If so, you might want to use the tag.

Python ValueError: too many values to unpack

Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity into (m, k).

My crystal ball says m.type and m.purity are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)

To fix this, you can iterate explicitly over the items of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.

(In 2.x, itervalues, iterkeys, and iteritems are typically a better idea; the non-iter versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter versions which just set up an iterator.)

How to increase editor font size?

In latest version of android studio ,We can change the appearance settings like font size and font style using following steps Android Studio ---->preference--font

enter image description here

<div> cannot appear as a descendant of <p>

I had a similar issue and wrapped the component in "div" instead of "p" and the error went away.

How to set maximum height for table-cell?

You can do either of the following:

  1. Use css attribute "line-height" and set it per table row (), this will also vertically center the content within

  2. Set "display" css attribute to "block" and as the following:

td 
{
  display: block;
  overflow-y: hidden;
  max-height: 20px;
}

good luck!

Check if value exists in the array (AngularJS)

You could use indexOf function.

if(list.indexOf(createItem.artNr) !== -1) {
  $scope.message = 'artNr already exists!';
}

More about indexOf:

How to change ProgressBar's progress indicator color in Android

In xml:

<ProgressBar
                    android:id="@+id/progressBar"
                    style="?android:attr/progressBarStyleInverse"
                    android:layout_width="60dp"
                    android:layout_height="60dp"
                    android:layout_margin="@dimen/dimen_10dp"


                 android:indeterminateTint="@{viewModel.getComplainStatusUpdate(position)}"
                    android:indeterminate="true"
                    android:indeterminateOnly="false"
                    android:max="100"
                    android:clickable="false"
                    android:indeterminateDrawable="@drawable/round_progress"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

ViewModel:

fun getComplainStatusUpdate(position: Int):Int{

                val list = myAllComplainList!!.getValue()
                if (list!!.get(position).complainStatus.equals("P")) {
                  //  progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
                   // progressBar.setBackgroundResource(R.drawable.circle_shape)
                    return Color.RED
                } else if (list!!.get(position).complainStatus.equals("I")) {

                    return Color.GREEN
                } else {

                    return Color.GREEN
                }


return Color.CYAN
    }

Java 8 Streams: multiple filters vs. complex condition

This is the result of the 6 different combinations of the sample test shared by @Hank D It's evident that predicate of form u -> exp1 && exp2 is highly performant in all the cases.

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=3372, min=31, average=33.720000, max=47}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9150, min=85, average=91.500000, max=118}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9046, min=81, average=90.460000, max=150}

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8336, min=77, average=83.360000, max=189}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9094, min=84, average=90.940000, max=176}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10501, min=99, average=105.010000, max=136}

two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=11117, min=98, average=111.170000, max=238}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8346, min=77, average=83.460000, max=113}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9089, min=81, average=90.890000, max=137}

two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10434, min=98, average=104.340000, max=132}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9113, min=81, average=91.130000, max=179}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8258, min=77, average=82.580000, max=100}

one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9131, min=81, average=91.310000, max=139}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10265, min=97, average=102.650000, max=131}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8442, min=77, average=84.420000, max=156}

one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8553, min=81, average=85.530000, max=125}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8219, min=77, average=82.190000, max=142}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10305, min=97, average=103.050000, max=132}

Send parameter to Bootstrap modal window?

There is a better solution than the accepted answer, specifically using data-* attributes. Setting the id to 1 will cause you issues if any other element on the page has id=1. Instead, you can do:

<button class="btn btn-primary" data-toggle="modal" data-target="#yourModalID" data-yourparameter="whateverYouWant">Load</button>

<script>
$('#yourModalID').on('show.bs.modal', function(e) {
  var yourparameter = e.relatedTarget.dataset.yourparameter;
  // Do some stuff w/ it.
});
</script>

The ScriptManager must appear before any controls that need it

The script manager must be put onto the page before it is used. This would be directly on the page itself, or alternatively, if you are using them, on the Master Page.

The markup would be;

 <asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="true"
            EnablePartialRendering="true" />

How can I put CSS and HTML code in the same file?

Is this what you're looking for? You place you CSS between style tags in the HTML document header. I'm guessing for iPhone it's webkit so it should work.

<html>
<head>
    <style type="text/css">
    .title { color: blue; text-decoration: bold; text-size: 1em; }
    .author { color: gray; }
    </style>
</head>
<body>
    <p>
    <span class="title">La super bonne</span>
    <span class="author">proposée par Jérém</span>
    </p>
</body>
</html>

Calculate difference in keys contained in two Python dictionaries

If you want a built-in solution for a full comparison with arbitrary dict structures, @Maxx's answer is a good start.

import unittest

test = unittest.TestCase()
test.assertEqual(dictA, dictB)

Export Postgresql table data using pgAdmin

Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.

pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.

It uses something like this:

pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.

How to make audio autoplay on chrome

As of April 2018, Chrome's autoplay policies changed:

"Chrome's autoplay policies are simple:

  • Muted autoplay is always allowed.

Autoplay with sound is allowed if:

  • User has interacted with the domain (click, tap, etc.).
  • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
  • On mobile, the user has added the site to his or her home screen.

Also

  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound. "

Chrome's developer site has more information, including some programming examples, which can be found here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

How do I reformat HTML code using Sublime Text 2?

You don't need any plugins to do this. Just select all lines (Ctrl A) and then from the menu select Edit → Line → Reindent. This will work if your file is saved with an extension that contains HTML like .html or .php.

If you do this often, you may find this key mapping useful:

{ "keys": ["ctrl+shift+r"], "command": "reindent" , "args": { "single_line": false } }

If your file is not saved (e.g. you just pasted in a snippet to a new window), you can manually set the language for indentation by selecting the menu View → Syntax → language of choice before selecting the reindent option.

What does it mean when an HTTP request returns status code 0?

In addition to Lee's answer, you may find more information about the real cause by switching to synchronous requests, as you'll get also an exception :

function request(url) {
    var request = new XMLHttpRequest();
    try {
        request.open('GET', url, false);
        request.send(null);
    } catch (e) {
        console.log(url + ': ' + e);
    }
}

For example :

NetworkError: A network error occurred.

Add new element to an existing object

Use this:

myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';

Or, if you are using jQuery:

$(myFunction).extend({
    bookName:'mybook',
    bookdesc: 'new'
});

The push method is wrong because it belongs to the Array.prototype object.

To create a named object, try this:

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}
myObj.prototype.objProp = true;
var newObj = new myObj();

Is it possible to read the value of a annotation in java?

Elaborating to the answer of @Cephalopod, if you wanted all column names in a list you could use this oneliner:

List<String> columns = 
        Arrays.asList(MyClass.class.getFields())
              .stream()
              .filter(f -> f.getAnnotation(Column.class)!=null)
              .map(f -> f.getAnnotation(Column.class).columnName())
              .collect(Collectors.toList());

How to check if NSString begins with a certain character

You can use the -hasPrefix: method of NSString:

Objective-C:

NSString* output = nil;
if([string hasPrefix:@"*"]) {
    output = [string substringFromIndex:1];
}

Swift:

var output:String?
if string.hasPrefix("*") {
    output = string.substringFromIndex(string.startIndex.advancedBy(1))
}

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

JavaScript isset() equivalent

window.isset = function(v_var) {
    if(typeof(v_var) == 'number'){ if(isNaN(v_var)){ return false; }}
    if(typeof(v_var) == 'undefined' || v_var === null){ return false;   } else { return true; }
};

plus Tests:

https://gist.github.com/daylik/24acc318b6abdcdd63b46607513ae073

Android Studio SDK location

  • Linux (Ubuntu 18.4)

/home/<USER_NAME>/Android/Sdk

  • windows (8.1)

C:\Users\<USER_NAME>\AppData\Local\Android\sdk

(AppData folder is hidden, check folder properties first)

  • macOS (Sierra 10.12.6)

/Users/<USER_NAME>/Library/Android/sdk

How to create a foreign key in phpmyadmin

When you create table than you can give like follows.

CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;


CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;

and when after the table create like this

   ALTER table_name
    ADD CONSTRAINT constraint_name
    FOREIGN KEY foreign_key_name(columns)
    REFERENCES parent_table(columns)
    ON DELETE action
    ON UPDATE action;

Following on example for it.

CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;

ALTER TABLE products 
ADD COLUMN vdr_id int not null AFTER cat_id;

To add a foreign key to the products table, you use the following statement:

ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

For drop the key

ALTER TABLE table_name 
DROP FOREIGN KEY constraint_name;

Hope this help to learn FOREIGN keys works

How to find distinct rows with field in list using JPA and Spring?

I finally was able to figure out a simple solution without the @Query annotation.

List<People> findDistinctByNameNotIn(List<String> names);

Of course, I got the people object instead of only Strings. I can then do the change in java.

What is dynamic programming?

The key bits of dynamic programming are "overlapping sub-problems" and "optimal substructure". These properties of a problem mean that an optimal solution is composed of the optimal solutions to its sub-problems. For instance, shortest path problems exhibit optimal substructure. The shortest path from A to C is the shortest path from A to some node B followed by the shortest path from that node B to C.

In greater detail, to solve a shortest-path problem you will:

  • find the distances from the starting node to every node touching it (say from A to B and C)
  • find the distances from those nodes to the nodes touching them (from B to D and E, and from C to E and F)
  • we now know the shortest path from A to E: it is the shortest sum of A-x and x-E for some node x that we have visited (either B or C)
  • repeat this process until we reach the final destination node

Because we are working bottom-up, we already have solutions to the sub-problems when it comes time to use them, by memoizing them.

Remember, dynamic programming problems must have both overlapping sub-problems, and optimal substructure. Generating the Fibonacci sequence is not a dynamic programming problem; it utilizes memoization because it has overlapping sub-problems, but it does not have optimal substructure (because there is no optimization problem involved).

When to use extern in C++

It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.

For example:

in file1.cpp:

int global_int = 1;

in file2.cpp:

extern int global_int;
//in some function
cout << "global_int = " << global_int;

setting content between div tags using javascript

See Creating and modifying HTML at what used to be called the Web Standards Curriculum.

Use the createElement, createTextNode and appendChild methods.

jQuery using append with effects

Another way when working with incoming data (like from an ajax call):

var new_div = $(data).hide();
$('#old_div').append(new_div);
new_div.slideDown();

How do I create a copy of an object in PHP?

In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).

You can use the 'clone' operator in PHP5 to copy objects:

$objectB = clone $objectA;

Also, it's just objects that are passed by reference, not everything as you've said in your question...

How to properly stop the Thread in Java?

You should always end threads by checking a flag in the run() loop (if any).

Your thread should look like this:

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
    private volatile boolean execute;

    @Override
    public void run() {
        this.execute = true;
        while (this.execute) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                this.execute = false;
            }
        }
    }

    public void stopExecuting() {
        this.execute = false;
    }
}

Then you can end the thread by calling thread.stopExecuting(). That way the thread is ended clean, but this takes up to 15 seconds (due to your sleep). You can still call thread.interrupt() if it's really urgent - but the prefered way should always be checking the flag.

To avoid waiting for 15 seconds, you can split up the sleep like this:

        ...
        try {
            LOGGER.debug("Sleeping...");
            for (int i = 0; (i < 150) && this.execute; i++) {
                Thread.sleep((long) 100);
            }

            LOGGER.debug("Processing");
        } catch (InterruptedException e) {
        ...

Count occurrences of a char in a string using Bash

I Would suggest the following:

var="any given string"
N=${#var}
G=${var//g/}
G=${#G}
(( G = N - G ))
echo "$G"

No call to any other program

JavaFX FXML controller - constructor vs initialize method

The initialize method is called after all @FXML annotated members have been injected. Suppose you have a table view you want to populate with data:

class MyController { 
    @FXML
    TableView<MyModel> tableView; 

    public MyController() {
        tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point. 
    }

    @FXML
    public void initialize() {
        tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members. 
    }
}

Determine a string's encoding in C#

Another option, very late in coming, sorry:

http://www.architectshack.com/TextFileEncodingDetector.ashx

This small C#-only class uses BOMS if present, tries to auto-detect possible unicode encodings otherwise, and falls back if none of the Unicode encodings is possible or likely.

It sounds like UTF8Checker referenced above does something similar, but I think this is slightly broader in scope - instead of just UTF8, it also checks for other possible Unicode encodings (UTF-16 LE or BE) that might be missing a BOM.

Hope this helps someone!

How do you test a public/private DSA keypair?

If it returns nothing, then they match:

cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys
ssh -i $HOME/.ssh/id_rsa localhost

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

There is a slick-looking jQuery plugin that apparently plays nice with Bootstrap called SelectBoxIt (http://gregfranko.com/jquery.selectBoxIt.js/). The thing I like about it is that it allows you to trigger the native select box on whatever OS you are on while still maintaining a consistent styling (http://gregfranko.com/jquery.selectBoxIt.js/#TriggertheNativeSelectBox). Oh how I wish Bootstrap provided this option!

The only downside to this is that it adds another layer of complexity into a solution, and additional work to ensure compatibility with all other plug-ins as they get upgraded/patched over time. I'm also not sure about Bootstrap 3 compatibility. But, this may be a good solution to ensure a consistent look across browsers and OS's.

How to change the default GCC compiler in Ubuntu?

I used just the lines below and it worked. I just wanted to compile VirtualBox and VMWare WorkStation using kernel 4.8.10 on Ubuntu 14.04. Initially, most things were not working for example graphics and networking. I was lucky that VMWare workstation requested for gcc 6.2.0. I couldn't start my Genymotion Android emulators because virtualbox was down. Will post results later if necessary.

VER=4.6 ; PRIO=60
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=6 ; PRIO=50
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=4.8 ; PRIO=40
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER

Sum of Numbers C++

The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Use Font Awesome Icon in Placeholder

You can't add an icon and text because you can't apply a different font to part of a placeholder, however, if you are satisfied with just an icon then it can work. The FontAwesome icons are just characters with a custom font (you can look at the FontAwesome Cheatsheet for the escaped Unicode character in the content rule. In the less source code it's found in variables.less The challenge would be to swap the fonts when the input is not empty. Combine it with jQuery like this.

<form role="form">
  <div class="form-group">
    <input type="text" class="form-control empty" id="iconified" placeholder="&#xF002;"/>
  </div>
</form>

With this CSS:

input.empty {
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    text-decoration: inherit;
}

And this (simple) jQuery

$('#iconified').on('keyup', function() {
    var input = $(this);
    if(input.val().length === 0) {
        input.addClass('empty');
    } else {
        input.removeClass('empty');
    }
});

The transition between fonts will not be smooth, however.

Generate GUID in MySQL for existing Data?

Looks like a simple typo. Didn't you mean "...where columnId is null"?

UPDATE db.tablename
  SET columnID = UUID()
  where columnID is null

Setting value of active workbook in Excel VBA

This is all you need

Set wbOOR = ActiveWorkbook

How to convert a String into an ArrayList?

I recommend use the StringTokenizer, is very efficient

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

     StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
     while (token.hasMoreTokens()) {
           list.add(token.nextToken());
     }

Install IPA with iTunes 12

iTunes 12.7 ( Xcode needed )

You cannot install a release ipa directly on your device. Ipa generated withAppStore Distribution Profile requires to be distributed from App Store or TestFlight. However, I found that app panel was removed even for installing ad hoc ipa from iTunes 12.7. I found a workaround to install ad-hoc apps which might help to them who cannot install even ad hoc ipa. Please follow the instructions below,

  1. Connect your device
  2. Open Xcode and go to Window -> Devices
  3. Select the connected device from left panel
  4. Brows the IPA from Installed Apps -> + button
  5. Wait few seconds and its done!

enter image description here

How do I make this file.sh executable via double click?

By default, *.sh files are opened in a text editor (Xcode or TextEdit). To create a shell script that will execute in Terminal when you open it, name it with the “command” extension, e.g., file.command. By default, these are sent to Terminal, which will execute the file as a shell script.

You will also need to ensure the file is executable, e.g.:

chmod +x file.command

Without this, Terminal will refuse to execute it.

Note that the script does not have to begin with a #! prefix in this specific scenario, because Terminal specifically arranges to execute it with your default shell. (Of course, you can add a #! line if you want to customize which shell is used or if you want to ensure that you can execute it from the command line while using a different shell.)

Also note that Terminal executes the shell script without changing the working directory. You’ll need to begin your script with a cd command if you actually need it to run with a particular working directory.

Read text file into string array (and write)

You can use os.File (which implements the io.Reader interface) with the bufio package for that. However, those packages are build with fixed memory usage in mind (no matter how large the file is) and are quite fast.

Unfortunately this makes reading the whole file into the memory a bit more complicated. You can use a bytes.Buffer to join the parts of the line if they exceed the line limit. Anyway, I recommend you to try to use the line reader directly in your project (especially if do not know how large the text file is!). But if the file is small, the following example might be sufficient for you:

package main

import (
    "os"
    "bufio"
    "bytes"
    "fmt"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err os.Error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 1024))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == os.EOF {
        err = nil
    }
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
}

Another alternative might be to use io.ioutil.ReadAll to read in the complete file at once and do the slicing by line afterwards. I don't give you an explicit example of how to write the lines back to the file, but that's basically an os.Create() followed by a loop similar to that one in the example (see main()).

concatenate two database columns into one resultset column

The SQL standard way of doing this would be:

SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1

Example:

INSERT INTO table1 VALUES ('hello', null, 'world');
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1;

helloworld

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

jQuery select child element by class with unknown path

Try this

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

Generate .pem file used to set up Apple Push Notifications

it is very simple after exporting the Cert.p12 and key.p12, Please find below command for the generating 'apns' .pem file.

https://www.sslshopper.com/ssl-converter.html ?

command to create apns-dev.pem from Cert.pem and Key.pem
?    

openssl rsa -in Key.pem -out apns-dev-key-noenc.pem
?    

cat Cert.pem apns-dev-key-noenc.pem > apns-dev.pem

Above command is useful for both Sandbox and Production.

javac option to compile all java files under a given directory recursively

javac -cp "jar_path/*" $(find . -name '*.java')

(I prefer not to use xargs because it can split them up and run javac multiple times, each with a subset of java files, some of which may import other ones not specified on the same javac command line)

If you have an App.java entrypoint, freaker's way with -sourcepath is best. It compiles every other java file it needs, following the import-dependencies. eg:

javac -cp "jar_path/*" -sourcepath src/ src/com/companyname/modulename/App.java

You can also specify a target class-file dir: -d target/.

Create an Oracle function that returns a table

  CREATE OR REPLACE PACKAGE BODY TEST AS 

   FUNCTION GET_UPS(
   TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
   STARTING_DATE_IN DATE,
   ENDING_DATE_IN DATE
   )RETURN MEASURE_TABLE IS

    T MEASURE_TABLE;

 BEGIN

    **SELECT   MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
             PERIOD,VALUE )  BULK COLLECT  INTO    T
    FROM    ...**

  ;

   RETURN T;

   END GET_UPS;

END TEST;

Remove git mapping in Visual Studio 2015

A Git repository can be removed from the Local Git Repositories list in VS-2015 when it is no longer the active project.

Your screen shot has only have one repository present, and it is active, so you can't remove it.

When you have two or more repositories, one of them will be shown in BOLD representing the active repository. Other non-active repositories can, at that time, be removed.

So, to solve your problem, if you connect with a second local repository, you will be able to remove the one you are highlighting in your screen shot.

Unfortunately, Team Explorer seems to always keep one repository active. Not sure how to convince it to let go altogether without switching to another repository.

The page cannot be displayed because an internal server error has occurred on server

For those of you who hit this stackoverflow entry because it ranks high for the phrase:

The page cannot be displayed because an internal server error has occurred.

In my personal situation with this exact error message, I had turned on python 2.7 thinking I could use some python with my .NET API. I then had that exact error message when I attempted to deploy a vanilla version of the API or MVC from visual studio pro 2013. I was deploying to an azure cloud webapp.

Hope this helps anyone with my same experience. I didn't even think to turn off python until I found this suggestion.

Trying to use Spring Boot REST to Read JSON String from POST

To further work with array of maps, the followings could help:

@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {

  List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
  maps.addAll(payload);

}

Activity transition in Android

zoom in out animation

Intent i = new Intent(getApplicationContext(), LoginActivity.class);
 overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
startActivity(i);
finish();

zoom_enter

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:fromAlpha="0.0" android:toAlpha="1.0"
    android:duration="500" />

zoom_exit

<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:fromAlpha="1.0" android:toAlpha="0.0"
    android:fillAfter="true"
    android:duration="500" />

How to stop line breaking in vim

I'm not sure I understand completely, but you might be looking for the 'formatoptions' configuration setting. Try something like :set formatoptions-=t. The t option will insert line breaks to make text wrap at the width set by textwidth. You can also put this command in your .vimrc, just remove the colon (:).

Open a Web Page in a Windows Batch FIle

start did not work for me.

I used:

firefox http://www.stackoverflow.com

or

chrome http://www.stackoverflow.com

Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

For Meteor, this can be solved by changing twbs:[email protected] to twbs:[email protected] in .versions

Differences between fork and exec

They are use together to create a new child process. First, calling fork creates a copy of the current process (the child process). Then, exec is called from within the child process to "replace" the copy of the parent process with the new process.

The process goes something like this:

child = fork();  //Fork returns a PID for the parent process, or 0 for the child, or -1 for Fail

if (child < 0) {
    std::cout << "Failed to fork GUI process...Exiting" << std::endl;
    exit (-1);
} else if (child == 0) {       // This is the Child Process
    // Call one of the "exec" functions to create the child process
    execvp (argv[0], const_cast<char**>(argv));
} else {                       // This is the Parent Process
    //Continue executing parent process
}

Press Enter to move to next control

You could also write your own Control for this, in case you want to use this more often. Assuming you have multiple TextBoxes in a Grid, it would look something like this:

public class AdvanceOnEnterTextBox : UserControl
{

    TextBox _TextBox;
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(String), typeof(AdvanceOnEnterTextBox), null);
    public static readonly DependencyProperty InputScopeProperty = DependencyProperty.Register("InputScope", typeof(InputScope), typeof(AdvanceOnEnterTextBox), null);


    public AdvanceOnEnterTextBox()
    {
        _TextBox = new TextBox();
        _TextBox.KeyDown += customKeyDown;
        Content = _TextBox;

    }


    /// <summary>
    /// Text for the TextBox
    /// </summary>
    public String Text
    {
        get { return _TextBox.Text; }
        set { _TextBox.Text = value; }
    }


    /// <summary>
    /// Inputscope for the Custom Textbox
    /// </summary>
    public InputScope InputScope
    {
        get { return _TextBox.InputScope; }
        set { _TextBox.InputScope = value; }
    }


    void customKeyDown(object sender, KeyEventArgs e)
    {
        if (!e.Key.Equals(Key.Enter)) return;

        var element = ((TextBox)sender).Parent as AdvanceOnEnterTextBox;
        if (element != null)
        {
            int currentElementPosition = ((Grid)element.Parent).Children.IndexOf(element);
            try
            {
                // Jump to the next AdvanceOnEnterTextBox (assuming, that Labels are inbetween).
                ((AdvanceOnEnterTextBox)((Grid)element.Parent).Children.ElementAt(currentElementPosition + 2)).Focus();
            }
            catch (Exception)
            {
                // Close Keypad if this was the last AdvanceOnEnterTextBox
                ((AdvanceOnEnterTextBox)((Grid)element.Parent).Children.ElementAt(currentElementPosition)).IsEnabled = false;
                ((AdvanceOnEnterTextBox)((Grid)element.Parent).Children.ElementAt(currentElementPosition)).IsEnabled = true;
            }
        }
    }
}

No increment operator (++) in Ruby?

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.

Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)

That explains it better than I ever could.

EDIT: and the reason from the language author himself (source):

  1. ++ and -- are NOT reserved operator in Ruby.
  2. C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
  3. self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

How to convert UTF-8 byte[] to string?

Definition:

public static string ConvertByteToString(this byte[] source)
{
    return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}

Using:

string result = input.ConvertByteToString();

Force an SVN checkout command to overwrite current files

I did not have 1.5 available to me, because I am not in control of the computer. The file that was causing me a problem happened to be a .jar file in the lib directory. Here is what I did to solve the problem:

rm -rf lib
svn up

This builds on Ned's answer. That is: I just removed the sub directory that was causing me a problem rather than the entire repository.

How to use regex in file find

find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
  1. -name uses globular expressions, aka wildcards. What you want is -regex
  2. To use intervals as you intend, you need to tell find to use Extended Regular Expressions via the -regextype posix-extended flag
  3. You need to escape out the periods because in regex a period has the special meaning of any single character. What you want is a literal period denoted by \.
  4. To match only those files that are greater than 3 days old, you need to prefix your number with a + as in -mtime +3.

Proof of Concept

$ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip'
./test.log.1234-12-12.zip

Cast Double to Integer in Java

It's worked for me. Try this:

double od = Double.parseDouble("1.15");
int oi = (int) od;

Launching a website via windows commandline

IE has a setting, located in Tools / Internet options / Advanced / Browsing, called Reuse windows for launching shortcuts, which is checked by default. For IE versions that support tabbed browsing, this option is relevant only when tab browsing is turned off (in fact, IE9 Beta explicitly mentions this). However, since IE6 does not have tabbed browsing, this option does affect opening URLs through the shell (as in your example).

Ansible playbook shell output

Perhaps not relevant if you're looking to do this ONLY using ansible. But it's much easier for me to have a function in my .bash_profile and then run _check_machine host1 host2

function _check_machine() {
    echo 'hostname,num_physical_procs,cores_per_procs,memory,Gen,RH Release,bios_hp_power_profile,bios_intel_qpi_link_power_management,bios_hp_power_regulator,bios_idle_power_state,bios_memory_speed,'
    hostlist=$1
    for h in `echo $hostlist | sed 's/ /\n/g'`;
    do
        echo $h | grep -qE '[a-zA-Z]'
        [ $? -ne 0 ] && h=plabb$h
        echo -n $h,
        ssh root@$h 'grep "^physical id" /proc/cpuinfo | sort -u | wc -l; grep "^cpu cores" /proc/cpuinfo |sort -u | awk "{print \$4}"; awk "{print \$2/1024/1024; exit 0}" /proc/meminfo; /usr/sbin/dmidecode | grep "Product Name"; cat /etc/redhat-release; /etc/facter/bios_facts.sh;' | sed 's/Red at Enterprise Linux Server release //g; s/.*=//g; s/\tProduct Name: ProLiant BL460c //g; s/-//g' | sed 's/Red Hat Enterprise Linux Server release //g; s/.*=//g; s/\tProduct Name: ProLiant BL460c //g; s/-//g' | tr "\n" ","
         echo ''
    done
}

E.g.

$ _machine_info '10 20 1036'
hostname,num_physical_procs,cores_per_procs,memory,Gen,RH Release,bios_hp_power_profile,bios_intel_qpi_link_power_management,bios_hp_power_regulator,bios_idle_power_state,bios_memory_speed,
plabb10,2,4,47.1629,G6,5.11 (Tikanga),Maximum_Performance,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
plabb20,2,4,47.1229,G6,6.6 (Santiago),Maximum_Performance,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
plabb1036,2,12,189.12,Gen8,6.6 (Santiago),Custom,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
$ 

Needless to say function won't work for you as it is. You need to update it appropriately.

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

calling javascript function on OnClientClick event of a Submit button

The above solutions must work. However you can try this one:

OnClientClick="return SomeMethod();return false;"

and remove return statement from the method.

How do I serialize a Python dictionary into a string, and then back to a dictionary?

While not strictly serialization, json may be reasonable approach here. That will handled nested dicts and lists, and data as long as your data is "simple": strings, and basic numeric types.

Is there a simple way that I can sort characters in a string in alphabetical order

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

How to make Unicode charset in cmd.exe by default?

Reg file

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Console]
"CodePage"=dword:fde9

Command Prompt

REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 0xfde9

PowerShell

sp -t d HKCU:\Console CodePage 0xfde9

Cygwin

regtool set /user/Console/CodePage 0xfde9

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

Instead of using a PreferenceActivity to directly load preferences, use an AppCompatActivity or equivalent that loads a PreferenceFragmentCompat that loads your preferences. It's part of the support library (now Android Jetpack) and provides compatibility back to API 14.

In your build.gradle, add a dependency for the preference support library:

dependencies {
    // ...
    implementation "androidx.preference:preference:1.0.0-alpha1"
}

Note: We're going to assume you have your preferences XML already created.

For your activity, create a new activity class. If you're using material themes, you should extend an AppCompatActivity, but you can be flexible with this:

public class MyPreferencesActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_preferences_activity)
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, MyPreferencesFragment())
                    .commitNow()
        }
    }
}

Now for the important part: create a fragment that loads your preferences from XML:

public class MyPreferencesFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.my_preferences_fragment); // Your preferences fragment
    }
}

For more information, read the Android Developers docs for PreferenceFragmentCompat.

How to call a method daily, at specific time, in C#?

If you want an executable to run, use Windows Scheduled Tasks. I'm going to assume (perhaps erroneously) that you want a method to run in your current program.

Why not just have a thread running continuously storing the last date that the method was called?

Have it wake up every minute (for example) and, if the current time is greater than the specified time and the last date stored is not the current date, call the method then update the date.

How to do multiple arguments to map function where one remains the same in python?

The correct answer is simpler than you think. Simply do:

map(add, [(x, 2) for x in [1,2,3]])

And change the implementation of add to take a tuple i.e

def add(t):
   x, y = t
   return x+y

This can handle any complicated use case where both add parameters are dynamic.

Difference between margin and padding?

padding is the space between the content and the border, whereas margin is the space outside the border. Here's an image I found from a quick Google search, that illustrates this idea.

enter image description here

Copying a local file from Windows to a remote server using scp

Drive letter can be used in the source like

scp /c/path/to/file.txt user@server:/dir1/file.txt

Add number of days to a date

You can use strtotime()
$data['created'] = date('Y-m-d H:m:s', strtotime('+1 week'));

How do I get some variable from another class in Java?

The code that you have is correct. To get a variable from another class you need to create an instance of the class if the variable is not static, and just call the explicit method to get access to that variable. If you put get and set method like the above is the same of declaring that variable public.

Put the method setNum private and inside the getNum assign the value that you want, you will have "get" access to the variable in that case

REACT - toggle class onclick

Here is a code I came Up with:

import React, {Component} from "react";
import './header.css'

export default class Header extends Component{
    state = {
        active : false
    };


    toggleMenuSwitch = () => {
        this.setState((state)=>{
            return{
                active: !state.active
            }
        })
    };
    render() {
        //destructuring
        const {active} = this.state;

        let className = 'toggle__sidebar';

        if(active){
            className += ' active';
        }

        return(
            <header className="header">
                <div className="header__wrapper">
                    <div className="header__cell header__cell--logo opened">
                        <a href="#" className="logo">
                            <img src="https://www.nrgcrm.olezzek.id.lv/images/logo.svg" alt=""/>
                        </a>
                        <a href="#" className={className}
                           onClick={ this.toggleMenuSwitch }
                           data-toggle="sidebar">
                            <i></i>
                        </a>
                    </div>
                    <div className="header__cell">

                    </div>
                </div>
            </header>
        );
    };
};

React-Router External link

Using some of the info here, I came up with the following component which you can use within your route declarations. It's compatible with React Router v4.

It's using typescript, but should be fairly straight-forward to convert to native javascript:

interface Props {
  exact?: boolean;
  link: string;
  path: string;
  sensitive?: boolean;
  strict?: boolean;
}

const ExternalRedirect: React.FC<Props> = (props: Props) => {
  const { link, ...routeProps } = props;

  return (
    <Route
      {...routeProps}
      render={() => {
        window.location.replace(props.link);
        return null;
      }}
    />
  );
};

And use with:

<ExternalRedirect
  exact={true}
  path={'/privacy-policy'}
  link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>

SQL select statements with multiple tables

First select all record from person table, then join all these record with another table 'Address'...now u have record of all the persons who have their address in address table...so finally filter your record by zipcode.

 select * from Person as P inner join Address as A on 
    P.id = A.person_id Where A.zip='97229'

How to order results with findBy() in Doctrine

The second parameter of findBy is for ORDER.

$ens = $em->getRepository('AcmeBinBundle:Marks')
          ->findBy(
             array('type'=> 'C12'), 
             array('id' => 'ASC')
           );

What is the difference between const int*, const int * const, and int const *?

Like pretty much everyone pointed out:

What’s the difference between const X* p, X* const p and const X* const p?

You have to read pointer declarations right-to-left.

  • const X* p means "p points to an X that is const": the X object can't be changed via p.

  • X* const p means "p is a const pointer to an X that is non-const": you can't change the pointer p itself, but you can change the X object via p.

  • const X* const p means "p is a const pointer to an X that is const": you can't change the pointer p itself, nor can you change the X object via p.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Syntax errors is not checked easily in external servers, just runtime errors.

What I do? Just like you, I use

ini_set('display_errors', 'On');
error_reporting(E_ALL);

However, before run I check syntax errors in a PHP file using an online PHP syntax checker.

The best, IMHO is PHP Code Checker

I copy all the source code, paste inside the main box and click the Analyze button.

It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely

'Incorrect SET Options' Error When Building Database Project

For me, just setting the compatibility level to higher level works fine. To see C.Level :

select compatibility_level from sys.databases where name = [your_database]

How can I get all a form's values that would be submitted without submitting

You can get the form using a document.getElementById and returning the elements[] array.

Here is an example.

You can also get each field of the form and get its value using the document.getElementById function and passing in the field's id.

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

Android: Clear Activity Stack

This decision works fine:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

But new activity launch long and you see white screen some time. If this is critical then use this workaround:

public class BaseActivity extends AppCompatActivity {

    private static final String ACTION_FINISH = "action_finish";

    private BroadcastReceiver finisBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        registerReceiver(finisBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                finish();
            }
        }, new IntentFilter(ACTION_FINISH));
    }

    public void clearBackStack() {
        sendBroadcast(new Intent(ACTION_FINISH));
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(finisBroadcastReceiver);
        super.onDestroy();
    }
}

How use it:

public class ActivityA extends BaseActivity {

    // Click any button
    public void startActivityB() {
        startActivity(new Intent(this, ActivityB.class));
        clearBackStack();
    }
}

Disadvantage: all activities that must be closed on the stack must extends BaseActivity

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

 SELECT 
    ...
    REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
            ' ',
            '') AS WORKDATE,
    ...
 INNER JOIN T_EMPLOYEE_MS E
    ...
     LEFT OUTER JOIN T_COMPENSATION C
          ON C.I_COMPENSATEDDATE = A.I_REQDATE
          AND C.I_EMPID = A.I_EMPID
    ...

Measure string size in Bytes in php

Do you mean byte size or string length?

Byte size is measured with strlen(), whereas string length is queried using mb_strlen(). You can use substr() to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr() to trim it to X characters in the encoding of the string.

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

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

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

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

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

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

getApplication() vs. getApplicationContext()

Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.

Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).

So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).

Why does getApplicationContext() exist in the first place ?

getApplication() is only available in the Activity class and the Service class, whereas getApplicationContext() is declared in the Context class.

That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext(). Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.

When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext() delegates it's call to baseContext.getApplicationContext().

One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

I know this is not an exact and precise answer, but still, does that answer your question?

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

In PANDAS, how to get the index of a known value?

There might be more than one index map to your value, it make more sense to return a list:

In [48]: a
Out[48]: 
   c1  c2
0   0   1
1   2   3
2   4   5
3   6   7
4   8   9

In [49]: a.c1[a.c1 == 8].index.tolist()
Out[49]: [4]

How to get current location in Android

First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

Then get the LocationManager and ask for location updates

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

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

For GPS based location, this one

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

qmake: could not find a Qt installation of ''

  • Install qt using:

    sudo apt install qt5-qmake
    
  • Open ~/.bashrc file:

    vim ~/.bashrc
    
  • Added the path below to the ~/.bashrc file:

    export PATH="/opt/Qt/5.15.1/gcc_64/bin/:$PATH"
    
  • Execute/load a ~/.bashrc file in your current shell

    source ~/.bashrc`
    
  • Try now qmake by using the version command below:

    qmake --version
    

Java: Multiple class declarations in one file

My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.

As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)

How to call a Python function from Node.js

You can now use RPC libraries that support Python and Javascript such as zerorpc

From their front page:

Node.js Client

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");

client.invoke("hello", "RPC", function(error, res, more) {
    console.log(res);
});

Python Server

import zerorpc

class HelloRPC(object):
    def hello(self, name):
        return "Hello, %s" % name

s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()

How to get the string size in bytes?

Use strlen to get the length of a null-terminated string.

sizeof returns the length of the array not the string. If it's a pointer (char *s), not an array (char s[]), it won't work, since it will return the size of the pointer (usually 4 bytes on 32-bit systems). I believe an array will be passed or returned as a pointer, so you'd lose the ability to use sizeof to check the size of the array.

So, only if the string spans the entire array (e.g. char s[] = "stuff"), would using sizeof for a statically defined array return what you want (and be faster as it wouldn't need to loop through to find the null-terminator) (if the last character is a null-terminator, you will need to subtract 1). If it doesn't span the entire array, it won't return what you want.

An alternative to all this is actually storing the size of the string.

PuTTY scripting to log onto host

entering a command after you logged in can be done by going through SSH section at the bottom of putty and you should have an option Remote command (data to send to the server) separate the two commands with ;

How Does Modulus Divison Work

I hope these simple steps will help:

20 % 3 = 2 
  1. 20 / 3 = 6; do not include the .6667 – just ignore it
  2. 3 * 6 = 18
  3. 20 - 18 = 2, which is the remainder of the modulo

Creating a new dictionary in Python

You can do this

x = {}
x['a'] = 1

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:

https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload

(the callback URI passed as a parameter must be url-encoded, btw).

When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.

If you visit:

http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow

You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri method to specify your callback path so the default isn't used.

The redirect URIs are in the client_secrets.json file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.

If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.

Fix CSS hover on iPhone/iPad/iPod

The hover pseudo class only functions on iOS when applied to a link tag. They do that because there is no hover on a touch device reall. It acts more like the active class. So they can't have one unless its a link going somewhere for usability reasons. Change your div to a link tag and you will have no problem.

Benefits of using the conditional ?: (ternary) operator

Sometimes it can make the assignment of a bool value easier to read at first glance:

// With
button.IsEnabled = someControl.HasError ? false : true;

// Without
button.IsEnabled = !someControl.HasError;

write newline into a file

if(!file3.exists()){
    file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null) fop.write(nodeValue.getBytes());

fop.write("\n".getBytes());

fop.flush();
fop.close();

You need to add a newline at the end of each write.

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

How to set socket timeout in C when making multiple connections?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

Add a user control to a wpf window

This is how I got it to work:

User Control WPF

<UserControl x:Class="App.ProcessView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>

    </Grid>
</UserControl>

User Control C#

namespace App {
    /// <summary>
    /// Interaction logic for ProcessView.xaml
    /// </summary>
    public partial class ProcessView : UserControl // My custom User Control
    {
        public ProcessView()
        {
            InitializeComponent();
        }
    } }

MainWindow WPF

<Window x:Name="RootWindow" x:Class="App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:app="clr-namespace:App"
        Title="Some Title" Height="350" Width="525" Closing="Window_Closing_1" Icon="bouncer.ico">
    <Window.Resources>
        <app:DateConverter x:Key="dateConverter"/>
    </Window.Resources>
    <Grid>
        <ListView x:Name="listView" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <app:ProcessView />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

How do you clear your Visual Studio cache on Windows Vista?

I had the same issue but when i deleted the cached items from Temp folder the build failed.

In order to make the build work again I had to close the project and reopen it.

Windows recursive grep command-line

Recursive search for import word inside src folder:

> findstr /s import .\src\*

W3WP.EXE using 100% CPU - where to start?

This is a guess at best, but perhaps your development team is building and deploying the application in debug mode, in stead of release mode. This will cause the occurrence of .pdb files. The implication of this is that your application will take up additional resources to collect system state and debugging information during the execution of your system, causing more processor utilization.

So, it would be simple enough to ensure that they are building and deploying in release mode.

Want to make Font Awesome icons clickable

If you don't want it to add it to a link, you can just enclose it within a span and that would work.

<span id='clickableAwesomeFont'><i class="fa fa-behance-square fa-4x"></span>

in your css, then you can:

#clickableAwesomeFont {
     cursor: pointer
}

Then in java script, you can just add a click handler.

In cases where it's actually not a link, I think this is much cleaner and using a link would be changing its semantics and abusing its meaning.

How to execute a Python script from the Django shell?

Try this if you are using virtual enviroment :-

python manage.py shell

for using those command you must be inside virtual enviroment. for this use :-

workon vir_env_name

for example :-

dc@dc-comp-4:~/mysite$ workon jango
(jango)dc@dc-comp-4:~/mysite$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

Note :- Here mysite is my website name and jango is my virtual enviroment name

How to restart a rails server on Heroku?

Just type the following commands from console.

cd /your_project
heroku restart

React prevent event bubbling in nested components on click

The new way to do this is a lot more simple and will save you some time! Just pass the event into the original click handler and call preventDefault();.

clickHandler(e){
    e.preventDefault();
    //Your functionality here
}

compression and decompression of string data in java

The above Answer solves our problem but in addition to that. if we are trying to decompress a uncompressed("not a zip format") byte[] . we will get "Not in GZIP format" exception message.

For solving that we can add addition code in our Class.

public static boolean isCompressed(final byte[] compressed) {
    return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}

My Complete Compression Class with compress/decompress would look like:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPCompression {
  public static byte[] compress(final String str) throws IOException {
    if ((str == null) || (str.length() == 0)) {
      return null;
    }
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.flush();
    gzip.close();
    return obj.toByteArray();
  }

  public static String decompress(final byte[] compressed) throws IOException {
    final StringBuilder outStr = new StringBuilder();
    if ((compressed == null) || (compressed.length == 0)) {
      return "";
    }
    if (isCompressed(compressed)) {
      final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
      final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

      String line;
      while ((line = bufferedReader.readLine()) != null) {
        outStr.append(line);
      }
    } else {
      outStr.append(compressed);
    }
    return outStr.toString();
  }

  public static boolean isCompressed(final byte[] compressed) {
    return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
  }
}

Setting "checked" for a checkbox with jQuery

Plain JavaScript is very simple and much less overhead:

var elements = document.getElementsByClassName('myCheckBox');
for(var i = 0; i < elements.length; i++)
{
    elements[i].checked = true;
}

Example here

Delete a row in Excel VBA

Better yet, use union to grab all the rows you want to delete, then delete them all at once. The rows need not be continuous.

dim rng as range
dim rDel as range

for each rng in {the range you're searching}
   if {Conditions to be met} = true then
      if not rDel is nothing then
         set rDel = union(rng,rDel)
      else
         set rDel = rng
      end if
   end if
 next
 
 rDel.entirerow.delete

That way you don't have to worry about sorting or things being at the bottom.

Postgres: How to do Composite keys?

Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

 CREATE TABLE tags
      (
               question_id INTEGER NOT NULL,
               tag_id SERIAL NOT NULL,
               tag1 VARCHAR(20),
               tag2 VARCHAR(20),
               tag3 VARCHAR(20),
               PRIMARY KEY(question_id, tag_id)
      );

NOTICE:  CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
    CREATE TABLE
    pg=> \d tags
                                         Table "public.tags"
       Column    |         Type          |                       Modifiers       
    -------------+-----------------------+-------------------------------------------------------
     question_id | integer               | not null
     tag_id      | integer               | not null default nextval('tags_tag_id_seq'::regclass)
     tag1        | character varying(20) |
     tag2        | character varying(20) |
     tag3        | character varying(20) |
    Indexes:
        "tags_pkey" PRIMARY KEY, btree (question_id, tag_id)

"Rate This App"-link in Google Play store app on the phone

Java solution (In-app review API by Google in 2020):

You can now use In app review API provided by Google out of the box.

First, in your build.gradle(app) file, add following dependencies (full setup can be found here)

dependencies {
    // This dependency is downloaded from the Google’s Maven repository.
    // So, make sure you also include that repository in your project's build.gradle file.
    implementation 'com.google.android.play:core:1.8.0'
}

Add this method to your Activity:

void askRatings() {
    ReviewManager manager = ReviewManagerFactory.create(this);
    Task<ReviewInfo> request = manager.requestReviewFlow();
    request.addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            // We can get the ReviewInfo object
            ReviewInfo reviewInfo = task.getResult();
            Task<Void> flow = manager.launchReviewFlow(this, reviewInfo);
            flow.addOnCompleteListener(task2 -> {
                // The flow has finished. The API does not indicate whether the user
                // reviewed or not, or even whether the review dialog was shown. Thus, no
                // matter the result, we continue our app flow.
            });
        } else {
            // There was some problem, continue regardless of the result.
        }
    });
}

And then you can simply call it using

askRatings();

Source

enter image description here

python inserting variable string as file name

you can do something like

filename = "%s.csv" % name
f = open(filename , 'wb')

or f = open('%s.csv' % name, 'wb')

Change color and appearance of drop down arrow

We have used YUI, Chosen, and are currently using the jQuery Select2 plugin: https://select2.github.io/

It's pretty robust, the arrow is just the tip of the iceberg.

As soon as stylized selects becomes a requirement, I agree with the others, go with a plugin. Don't kill yourself reinventing the wheel.

How to change the order of DataFrame columns?

In your case,

df = df.reindex(columns=['mean',0,1,2,3,4])

will do exactly what you want.

In my case (general form):

df = df.reindex(columns=sorted(df.columns))
df = df.reindex(columns=(['opened'] + list([a for a in df.columns if a != 'opened']) ))

Merging two images with PHP

You can try my function for merging images horizontally or vertically without changing image ratio. just copy paste will work.

function merge($filename_x, $filename_y, $filename_result, $mergeType = 0) {

    //$mergeType 0 for horizandal merge 1 for vertical merge

 // Get dimensions for specified images
 list($width_x, $height_x) = getimagesize($filename_x);
 list($width_y, $height_y) = getimagesize($filename_y);


$lowerFileName = strtolower($filename_x); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    $image_x = imagecreatefromjpeg($filename_x);    
}else if(substr_count($lowerFileName, '.png')>0){
    $image_x = imagecreatefrompng($filename_x); 
}else if(substr_count($lowerFileName, '.gif')>0){
    $image_x = imagecreatefromgif($filename_x); 
}


$lowerFileName = strtolower($filename_y); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    $image_y = imagecreatefromjpeg($filename_y);    
}else if(substr_count($lowerFileName, '.png')>0){
    $image_y = imagecreatefrompng($filename_y); 
}else if(substr_count($lowerFileName, '.gif')>0){
    $image_y = imagecreatefromgif($filename_y); 
}


if($mergeType==0){
    //for horizandal merge
     if($height_y<$height_x){
        $new_height = $height_y;

        $new_x_height = $new_height;
        $precentageReduced = ($height_x - $new_height)/($height_x/100);
        $new_x_width = ceil($width_x - (($width_x/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_x_width, $new_x_height);
        imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
        $image_x = $tmp;

        $height_x = $new_x_height;
        $width_x = $new_x_width;

     }else{
        $new_height = $height_x;

        $new_y_height = $new_height;
        $precentageReduced = ($height_y - $new_height)/($height_y/100);
        $new_y_width = ceil($width_y - (($width_y/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_y_width, $new_y_height);
        imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
        $image_y = $tmp;

        $height_y = $new_y_height;
        $width_y = $new_y_width;

     }

     $new_width = $width_x + $width_y;

     $image = imagecreatetruecolor($new_width, $new_height);

    imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
    imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);

}else{


    //for verical merge
    if($width_y<$width_x){
        $new_width = $width_y;

        $new_x_width = $new_width;
        $precentageReduced = ($width_x - $new_width)/($width_x/100);
        $new_x_height = ceil($height_x - (($height_x/100) * $precentageReduced));

        $tmp = imagecreatetruecolor($new_x_width, $new_x_height);
        imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
        $image_x = $tmp;

        $width_x = $new_x_width;
        $height_x = $new_x_height;

     }else{
        $new_width = $width_x;

        $new_y_width = $new_width;
        $precentageReduced = ($width_y - $new_width)/($width_y/100);
        $new_y_height = ceil($height_y - (($height_y/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_y_width, $new_y_height);
        imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
        $image_y = $tmp;

        $width_y = $new_y_width;
        $height_y = $new_y_height;

     }

     $new_height = $height_x + $height_y;

     $image = imagecreatetruecolor($new_width, $new_height);

    imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
    imagecopy($image, $image_y, 0, $height_x, 0, 0, $width_y, $height_y);

}





$lowerFileName = strtolower($filename_result); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    imagejpeg($image, $filename_result);
}else if(substr_count($lowerFileName, '.png')>0){
    imagepng($image, $filename_result);
}else if(substr_count($lowerFileName, '.gif')>0){
    imagegif($image, $filename_result); 
}


 // Clean up
 imagedestroy($image);
 imagedestroy($image_x);
 imagedestroy($image_y);

}


merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged_har.jpg',0); //merge horizontally
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged.jpg',1); //merge vertically

Pass a javascript variable value into input type hidden value

Hidden Field :

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

Script :

<script type="text/javascript">
     var year = new Date();
     document.getElementById("year").value=(year.getFullYear());
</script>

Custom pagination view in Laravel 5

Laravel 5 ships with a Bootstrap 4 paginator if anyone needs it.

First create a new service provider.

php artisan make:provider PaginationServiceProvider

In the register method pass a closure to Laravel's paginator class that creates and returns the new presenter.

<?php


namespace App\Providers;

use Illuminate\Pagination\BootstrapFourPresenter;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;

class PaginationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        Paginator::presenter(function($paginator)
        {
            return new BootstrapFourPresenter($paginator);
        });
    }
}

Register the new provider in config/app.php

'providers' => [
    //....
    App\Providers\PaginationServiceProvider::class,
]

I found this example at Bootstrap 4 Pagination With Laravel

how to convert date to a format `mm/dd/yyyy`

Are you looking for something like this?

SELECT CASE WHEN LEFT(created_ts, 1) LIKE '[0-9]' 
            THEN CONVERT(VARCHAR(10), CONVERT(datetime, created_ts,   1), 101)
            ELSE CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 109), 101)
      END created_ts
  FROM table1

Output:

| CREATED_TS |
|------------|
| 02/20/2012 |
| 11/29/2012 |
| 02/20/2012 |
| 11/29/2012 |
| 02/20/2012 |
| 11/29/2012 |
| 11/16/2011 |
| 02/20/2012 |
| 11/29/2012 |

Here is SQLFiddle demo

Writing html form data to a txt file without the use of a webserver

Something like this?

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">Please type in this box. When you 

click the Download button, the contents of this box will be downloaded to 

your machine at the location you specify. Pretty nifty. </textarea>
  <input type="submit" value="Download">
</form>
</body>
</html>

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

Validate date in dd/mm/yyyy format using JQuery Validate

I encountered a similar problem in my project. After struggling a lot, I found this solution:

if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
    // do something

You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.

Int or Number DataType for DataAnnotation validation attribute

You can write a custom validation attribute:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class Numeric : ValidationAttribute
{
    public Numeric(string errorMessage) : base(errorMessage)
    {
    }

    /// <summary>
    /// Check if given value is numeric
    /// </summary>
    /// <param name="value">The input value</param>
    /// <returns>True if value is numeric</returns>
    public override bool IsValid(object value)
    {
        return decimal.TryParse(value?.ToString(), out _);
    }
}

On your property you can then use the following annotation:

[Numeric("Please fill in a valid number.")]
public int NumberOfBooks { get; set; }

Shell script to copy files from one location to another location and rename add the current date to every file

cp --archive home/webapps/project1/folder1/{aaa,bbb,ccc,ddd}.csv home/webapps/project1/folder2
rename 's/\.csv$/'$(date +%m%d%Y).csv'/' home/webapps/project1/folder2/{aaa,bbb,ccc,ddd}.csv

Explanation:

  • --archive ensures that the files are copied with the same ownership and permissions.
  • foo{bar,baz} is expanded into foobar foobaz.
  • rename is a commonly available program to do exactly this kind of substitution.

PS: don't use ls for this.

jQuery first child of "this"

This can be done with a simple magic like this:

$(":first-child", element).toggleClass("redClass");

Reference: http://www.snoopcode.com/jquery/jquery-first-child-selector

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Two ways to do it...

GROUP BY

SELECT RES.[CUSTOMER ID], RES,NAME, SUM(INV.AMOUNT) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
GROUP BY RES.[CUSTOMER ID], RES,NAME

OVER

SELECT RES.[CUSTOMER ID], RES,NAME, 
       SUM(INV.AMOUNT) OVER (PARTITION RES.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

To make it work you have to replace a run this line of code serviceMetadata httpGetEnabled="true"/> http instead of https and security mode="None" />

login to remote using "mstsc /admin" with password

the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e

cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>

i could then use mstsc /v:<server> without getting prompted for the login.

How to plot two histograms together in R?

@Dirk Eddelbuettel: The basic idea is excellent but the code as shown can be improved. [Takes long to explain, hence a separate answer and not a comment.]

The hist() function by default draws plots, so you need to add the plot=FALSE option. Moreover, it is clearer to establish the plot area by a plot(0,0,type="n",...) call in which you can add the axis labels, plot title etc. Finally, I would like to mention that one could also use shading to distinguish between the two histograms. Here is the code:

set.seed(42)
p1 <- hist(rnorm(500,4),plot=FALSE)
p2 <- hist(rnorm(500,6),plot=FALSE)
plot(0,0,type="n",xlim=c(0,10),ylim=c(0,100),xlab="x",ylab="freq",main="Two histograms")
plot(p1,col="green",density=10,angle=135,add=TRUE)
plot(p2,col="blue",density=10,angle=45,add=TRUE)

And here is the result (a bit too wide because of RStudio :-) ):

enter image description here

How to load a resource bundle from a file resource in Java?

This works for me:

File f = new File("some.properties");
Properties props = new Properties();
FileInputStream fis = null;
try {
    fis = new FileInputStream(f);
    props.load(fis);
} catch (FileNotFoundException e) {
    e.printStackTrace();                    
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close();
            fis = null;
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }
}           

How to suppress Pandas Future warning ?

Found this on github...

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

import pandas

How to get VM arguments from inside of Java application?

If you want the entire command line of your java process, you can use: JvmArguments.java (uses a combination of JNA + /proc to cover most unix implementations)

SQL get the last date time record

If you want one row for each filename, reflecting a specific states and listing the most recent date then this is your friend:

select filename ,
       status   ,
       max_date = max( dates )
from some_table t
group by filename , status
having status = '<your-desired-status-here>'

Easy!

Pandas conditional creation of a series/dataframe column

Here's yet another way to skin this cat, using a dictionary to map new values onto the keys in the list:

def map_values(row, values_dict):
    return values_dict[row]

values_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

df = pd.DataFrame({'INDICATOR': ['A', 'B', 'C', 'D'], 'VALUE': [10, 9, 8, 7]})

df['NEW_VALUE'] = df['INDICATOR'].apply(map_values, args = (values_dict,))

What's it look like:

df
Out[2]: 
  INDICATOR  VALUE  NEW_VALUE
0         A     10          1
1         B      9          2
2         C      8          3
3         D      7          4

This approach can be very powerful when you have many ifelse-type statements to make (i.e. many unique values to replace).

And of course you could always do this:

df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)

But that approach is more than three times as slow as the apply approach from above, on my machine.

And you could also do this, using dict.get:

df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]

How do I add button on each row in datatable?

I contribute with my settings for buttons: view, edit and delete. The last column has data: null At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.

//...
columns: [
    { title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
    { title: "Id", "data": "id", defaultContent: '', "visible":false },
    { title: "Nombre", "data": "nombre" },
    { title: "Apellido", "data": "apellido" },
    { title: "Documento", "data": "tipo_documento.siglas" },
    { title: "Numero", "data": "numero_documento" },
    { title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
    { title: "Teléfono", "data": "telefono1" },
    { title: "Email", "data": "email1" }
    , { title: "", "data": null }
],
columnDefs: [
    {
        "searchable": false,
        "orderable": false,
        "targets": 0
    },
    { 
      width: '3%', 
      targets: 0  //la primer columna tendra una anchura del  20% de la tabla
    },
    {
        targets: -1, //-1 es la ultima columna y 0 la primera
        data: null,
        defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button>  <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
    },
    { orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
], 
//...

enter image description here

What are the different NameID format used for?

1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:

Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:

urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:

What is the right way to treat argparse.Namespace() as a dictionary?

Is it proper to "reach into" an object and use its dict property?

In general, I would say "no". However Namespace has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.

On the other hand, Namespace does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__, but the limits of my imagination are not the same as yours.

Swift - How to convert String to Double

For a little more Swift feeling, using NSFormatter() avoids casting to NSString, and returns nil when the string does not contain a Double value (e.g. "test" will not return 0.0).

let double = NSNumberFormatter().numberFromString(myString)?.doubleValue

Alternatively, extending Swift's String type:

extension String {
    func toDouble() -> Double? {
        return NumberFormatter().number(from: self)?.doubleValue
    }
}

and use it like toInt():

var myString = "4.2"
var myDouble = myString.toDouble()

This returns an optional Double? which has to be unwrapped.

Either with forced unwrapping:

println("The value is \(myDouble!)") // prints: The value is 4.2

or with an if let statement:

if let myDouble = myDouble {
    println("The value is \(myDouble)") // prints: The value is 4.2
}

Update: For localization, it is very easy to apply locales to the NSFormatter as follows:

let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "fr_FR")
let double = formatter.numberFromString("100,25")

Finally, you can use NSNumberFormatterCurrencyStyle on the formatter if you are working with currencies where the string contains the currency symbol.

How to get streaming url from online streaming radio station

When you go to a stream url, you get offered a file. feed this file to a parser to extract the contents out of it. the file is (usually) plain text and contains the url to play.

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

What is size_t in C?

size_t and int are not interchangeable. For instance on 64-bit Linux size_t is 64-bit in size (i.e. sizeof(void*)) but int is 32-bit.

Also note that size_t is unsigned. If you need signed version then there is ssize_t on some platforms and it would be more relevant to your example.

As a general rule I would suggest using int for most general cases and only use size_t/ssize_t when there is a specific need for it (with mmap() for example).

extracting days from a numpy.timedelta64 value

Use dt.days to obtain the days attribute as integers.

For eg:

In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))

In [15]: s
Out[15]: 
0    1 days 00:00:00
1    3 days 02:00:00
2    5 days 04:00:00
3    7 days 06:00:00
4    9 days 08:00:00
5   11 days 10:00:00
dtype: timedelta64[ns]

In [16]: s.dt.days
Out[16]: 
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

More generally - You can use the .components property to access a reduced form of timedelta.

In [17]: s.dt.components
Out[17]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     1      0        0        0             0             0            0
1     3      2        0        0             0             0            0
2     5      4        0        0             0             0            0
3     7      6        0        0             0             0            0
4     9      8        0        0             0             0            0
5    11     10        0        0             0             0            0

Now, to get the hours attribute:

In [23]: s.dt.components.hours
Out[23]: 
0     0
1     2
2     4
3     6
4     8
5    10
Name: hours, dtype: int64

How do I force detach Screen from another SSH session?

As Jose answered, screen -d -r should do the trick. This is a combination of two commands, as taken from the man page.

screen -d detaches the already-running screen session, and screen -r reattaches the existing session. By running screen -d -r, you force screen to detach it and then resume the session.

If you use the capital -D -RR, I quote the man page because it's too good to pass up.

Attach here and now. Whatever that means, just do it.

Note: It is always a good idea to check the status of your sessions by means of "screen -list".

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

Find out how much memory is being used by an object in Python

For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare.

This method has many drawbacks but it will give you a very fast estimate for very big objects.

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

data = json.load(urllib2.urlopen('http://someurl/path/to/json'))

Why can't I call a public method in another class?

You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example

class Example {
  public static string NonInstanceMethod() {
    return "static";
  }
  public string InstanceMethod() { 
    return "non-static";
  }
}

static void SomeMethod() {
  Console.WriteLine(Example.NonInstanceMethod());
  Console.WriteLine(Example.InstanceMethod());  // Does not compile
  Example v1 = new Example();
  Console.WriteLine(v1.InstanceMethod());
}

What is the difference between Builder Design pattern and Factory Design pattern?

Both are Creational patterns, to create Object.

1) Factory Pattern - Assume, you have one super class and N number of sub classes. The object is created depends on which parameter/value is passed.

2) Builder pattern - to create complex object.

Ex: Make a Loan Object. Loan could be house loan, car loan ,
    education loan ..etc. Each loan will have different interest rate, amount ,  
    duration ...etc. Finally a complex object created through step by step process.

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

For me it worked like the code below. I made a difference between RouterModule.forRoot and RouterModule.forChild. Then in the child define the parent path and in the children array the childs.

parent-routing.module.ts

RouterModule.forRoot([
  {
    path: 'parent',  //parent path, define the component that you imported earlier..
    component: ParentComponent,
  }
]),
RouterModule.forChild([
  {
    path: 'parent', //parent path
    children: [
      {
        path: '', 
        redirectTo: '/parent/childs', //full child path
        pathMatch: 'full'
      },
      {
        path: 'childs', 
        component: ParentChildsComponent,
      },
    ]
  }
])

Hope this helps.

How to extract closed caption transcript from YouTube video?

Another option is to use youtube-dl:

youtube-dl --skip-download --write-auto-sub $youtube_url

The default format is vtt and the other available format is ttml (--sub-format ttml).

--write-sub
       Write subtitle file

--write-auto-sub
       Write automatically generated subtitle file (YouTube only)

--all-subs
       Download all the available subtitles of the video

--list-subs
       List all available subtitles for the video

--sub-format FORMAT
       Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"

--sub-lang LANGS
       Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags

You can use ffmpeg to convert the subtitle file to another format:

ffmpeg -i input.vtt output.srt

This is what the VTT subtitles look like:

WEBVTT
Kind: captions
Language: en

00:00:01.429 --> 00:00:04.249 align:start position:0%

ladies<00:00:02.429><c> and</c><00:00:02.580><c> gentlemen</c><c.colorE5E5E5><00:00:02.879><c> I'd</c></c><c.colorCCCCCC><00:00:03.870><c> like</c></c><c.colorE5E5E5><00:00:04.020><c> to</c><00:00:04.110><c> thank</c></c>

00:00:04.249 --> 00:00:04.259 align:start position:0%
ladies and gentlemen<c.colorE5E5E5> I'd</c><c.colorCCCCCC> like</c><c.colorE5E5E5> to thank
 </c>

00:00:04.259 --> 00:00:05.930 align:start position:0%
ladies and gentlemen<c.colorE5E5E5> I'd</c><c.colorCCCCCC> like</c><c.colorE5E5E5> to thank
you<00:00:04.440><c> for</c><00:00:04.620><c> coming</c><00:00:05.069><c> tonight</c><00:00:05.190><c> especially</c></c><c.colorCCCCCC><00:00:05.609><c> at</c></c>

00:00:05.930 --> 00:00:05.940 align:start position:0%
you<c.colorE5E5E5> for coming tonight especially</c><c.colorCCCCCC> at
 </c>

00:00:05.940 --> 00:00:07.730 align:start position:0%
you<c.colorE5E5E5> for coming tonight especially</c><c.colorCCCCCC> at
such<00:00:06.180><c> short</c><00:00:06.690><c> notice</c></c>

00:00:07.730 --> 00:00:07.740 align:start position:0%
such short notice


00:00:07.740 --> 00:00:09.620 align:start position:0%
such short notice
I'm<00:00:08.370><c> sure</c><c.colorE5E5E5><00:00:08.580><c> mr.</c><00:00:08.820><c> Irving</c><00:00:09.000><c> will</c><00:00:09.120><c> fill</c><00:00:09.300><c> you</c><00:00:09.389><c> in</c><00:00:09.420><c> on</c></c>

00:00:09.620 --> 00:00:09.630 align:start position:0%
I'm sure<c.colorE5E5E5> mr. Irving will fill you in on
 </c>

00:00:09.630 --> 00:00:11.030 align:start position:0%
I'm sure<c.colorE5E5E5> mr. Irving will fill you in on
the<00:00:09.750><c> circumstances</c><00:00:10.440><c> that's</c><00:00:10.620><c> brought</c><00:00:10.920><c> us</c></c>

00:00:11.030 --> 00:00:11.040 align:start position:0%
<c.colorE5E5E5>the circumstances that's brought us
 </c>

Here are the same subtitles without the part at the top of the file and without tags:

00:00:01.429 --> 00:00:04.249 align:start position:0%

ladies and gentlemen I'd like to thank

00:00:04.249 --> 00:00:04.259 align:start position:0%
ladies and gentlemen I'd like to thank


00:00:04.259 --> 00:00:05.930 align:start position:0%
ladies and gentlemen I'd like to thank
you for coming tonight especially at

00:00:05.930 --> 00:00:05.940 align:start position:0%
you for coming tonight especially at


00:00:05.940 --> 00:00:07.730 align:start position:0%
you for coming tonight especially at
such short notice

00:00:07.730 --> 00:00:07.740 align:start position:0%
such short notice


00:00:07.740 --> 00:00:09.620 align:start position:0%
such short notice
I'm sure mr. Irving will fill you in on

00:00:09.620 --> 00:00:09.630 align:start position:0%
I'm sure mr. Irving will fill you in on


00:00:09.630 --> 00:00:11.030 align:start position:0%
I'm sure mr. Irving will fill you in on
the circumstances that's brought us

You can see that each subtitle text is repeated three times. There is a new subtitle text every eighth line (3rd, 11th, 19th, and 27th).

This converts the VTT subtitles to a simpler format:

sed '1,/^$/d' *.vtt| # remove the part at the top
sed 's/<[^>]*>//g'| # remove tags
awk -F. 'NR%8==1{printf"%s ",$1}NR%8==3' # print each new subtitle text and its start time without milliseconds

This is what the output of the command above looks like:

00:00:01 ladies and gentlemen I'd like to thank
00:00:04 you for coming tonight especially at
00:00:05 such short notice
00:00:07 I'm sure mr. Irving will fill you in on
00:00:09 the circumstances that's brought us

This prints the closed captions of a video in the simplified format:

cap()(cd /tmp;rm -f -- *.vtt;youtube-dl --skip-download --write-auto-sub -- "$1";sed '1,/^$/d' -- *.vtt|sed 's/<[^>]*>//g'|awk -F. 'NR%8==1{printf"%s ",$1}NR%8==3')

The command below downloads the captions of all videos on a channel. When there is an error like Unable to extract video data, -i (--ignore-errors) causes youtube-dl to skip the video instead of exiting with an error.

youtube-dl -i --skip-download --write-auto-sub -o '%(upload_date)s.%(title)s.%(id)s.%(ext)s' https://www.youtube.com/channel/$channelid;for f in *.vtt;do sed '1,/^$/d' "$f"|sed 's/<[^>]*>//g'|awk -F. 'NR%8==1{printf"%s ",$1}NR%8==3'>"${f%.vtt}";done

Authenticating in PHP using LDAP through Active Directory

I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.

Running npm command within Visual Studio Code

On Win10 I had to run VSCode as administrator to npm commands work.

What is the difference between 'E', 'T', and '?' for Java generics?

compiler will make a capture for each wildcard (e.g., question mark in List) when it makes up a function like:

foo(List<?> list) {
    list.put(list.get()) // ERROR: capture and Object are not identical type.
}

However a generic type like V would be ok and making it a generic method:

<V>void foo(List<V> list) {
    list.put(list.get())
}