Programs & Examples On #Hsb

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

From comments:

But, this code never stops (because of integer overflow) !?! Yves Daoust

For many numbers it will not overflow.

If it will overflow - for one of those unlucky initial seeds, the overflown number will very likely converge toward 1 without another overflow.

Still this poses interesting question, is there some overflow-cyclic seed number?

Any simple final converging series starts with power of two value (obvious enough?).

2^64 will overflow to zero, which is undefined infinite loop according to algorithm (ends only with 1), but the most optimal solution in answer will finish due to shr rax producing ZF=1.

Can we produce 2^64? If the starting number is 0x5555555555555555, it's odd number, next number is then 3n+1, which is 0xFFFFFFFFFFFFFFFF + 1 = 0. Theoretically in undefined state of algorithm, but the optimized answer of johnfound will recover by exiting on ZF=1. The cmp rax,1 of Peter Cordes will end in infinite loop (QED variant 1, "cheapo" through undefined 0 number).

How about some more complex number, which will create cycle without 0? Frankly, I'm not sure, my Math theory is too hazy to get any serious idea, how to deal with it in serious way. But intuitively I would say the series will converge to 1 for every number : 0 < number, as the 3n+1 formula will slowly turn every non-2 prime factor of original number (or intermediate) into some power of 2, sooner or later. So we don't need to worry about infinite loop for original series, only overflow can hamper us.

So I just put few numbers into sheet and took a look on 8 bit truncated numbers.

There are three values overflowing to 0: 227, 170 and 85 (85 going directly to 0, other two progressing toward 85).

But there's no value creating cyclic overflow seed.

Funnily enough I did a check, which is the first number to suffer from 8 bit truncation, and already 27 is affected! It does reach value 9232 in proper non-truncated series (first truncated value is 322 in 12th step), and the maximum value reached for any of the 2-255 input numbers in non-truncated way is 13120 (for the 255 itself), maximum number of steps to converge to 1 is about 128 (+-2, not sure if "1" is to count, etc...).

Interestingly enough (for me) the number 9232 is maximum for many other source numbers, what's so special about it? :-O 9232 = 0x2410 ... hmmm.. no idea.

Unfortunately I can't get any deep grasp of this series, why does it converge and what are the implications of truncating them to k bits, but with cmp number,1 terminating condition it's certainly possible to put the algorithm into infinite loop with particular input value ending as 0 after truncation.

But the value 27 overflowing for 8 bit case is sort of alerting, this looks like if you count the number of steps to reach value 1, you will get wrong result for majority of numbers from the total k-bit set of integers. For the 8 bit integers the 146 numbers out of 256 have affected series by truncation (some of them may still hit the correct number of steps by accident maybe, I'm too lazy to check).

Use getElementById on HTMLElement instead of HTMLDocument

I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.

Option Explicit
Public Sub GetInfo()
    Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With
    Set html = New HTMLDocument
    With html
        .body.innerHTML = sResponse
        Set elements = .querySelectorAll(".profile-col1")
        For i = 0 To elements.Length - 1
            Debug.Print String(20, Chr$(61))
            Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
        Next
    End With
End Sub

References:

VBE > Tools > References > Microsoft HTML Object Library

How can I label points in this scatterplot?

For just plotting a vector, you should use the following command:

text(your.vector, labels=your.labels, cex= labels.size, pos=labels.position)

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

Question mark and colon in JavaScript

hsb.s = max != 0 ? 255 * delta / max : 0;

? is a ternary operator. It works like an if in conjunction with the :

!= means not equals

So, the long form of this line would be

if (max != 0) { //if max is not zero
  hsb.s = 255 * delta / max;
} else {
  hsb.s = 0;
}

Exception of type 'System.OutOfMemoryException' was thrown. Why?

It runs successfully the first time, but if I run it again, I keep getting a System.OutOfMemoryException. What are some reasons this could be happening?

Regardless of what the others have said, the error has nothing to do with forgetting to dispose your DBCommand or DBConnection, and you will not fix your error by disposing of either of them.

The error has everything to do with your dataset which contains nearly 600,000 rows of data. Apparently your dataset consumes more than 50% of the available memory on your machine. Clearly, you'll run out of memory when you return another dataset of the same size before the first one has been garbage collected. Simple as that.

You can remedy this problem in a few ways:

  • Consider returning fewer records. I personally can't imagine a time when returning 600K records has ever been useful to a user. To minimize the records returned, try:

    • Limiting your query to the first 1000 records. If there are more than 1000 results returned from the query, inform the user to narrow their search results.

    • If your users really insist on seeing that much data at once, try paging the data. Remember: Google never shows you all 22 bajillion results of a search at once, it shows you 20 or so records at a time. Google probably doesn't hold all 22 bajillion results in memory at once, it probably finds its more memory efficient to requery its database to generate a new page.

  • If you just need to iterate through the data and you don't need random access, try returning a datareader instead. A datareader only loads one record into memory at a time.

If none of those are an option, then you need to force .NET to free up the memory used by the dataset before calling your method using one of these methods:

  • Remove all references to your old dataset. Anything holding on to a refenence of your dataset will prevent it from being reclaimed by memory.

  • If you can't null all the references to your dataset, clear all of the rows from the dataset and any objects bound to those rows instead. This removes references to the datarows and allows them to be eaten by the garbage collector.

I don't believe you'll need to call GC.Collect() to force a gen cycle. Not only is it generally a bad idea to call GC.Collect(), because sufficient memory pressure will cause .NET invoke the garbage collector on its own.

Note: calling Dispose on your dataset does not free any memory, nor does it invoke the garbage collector, nor does it remove a reference to your dataset. Dispose is used to clean up unmanaged resources, but the DataSet does not have any unmanaged resources. It only implements IDispoable because it inherents from MarshalByValueComponent, so the Dispose method on the dataset is pretty much useless.

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

You should use NVARCHAR anytime you have to store multiple languages. I believe you have to use it for the Asian languages but don't quote me on it.

Here's the problem if you take Russian for example and store it in a varchar, you will be fine so long as you define the correct code page. But let's say your using a default english sql install, then the russian characters will not be handled correctly. If you were using NVARCHAR() they would be handled properly.

Edit

Ok let me quote MSDN and maybee I was to specific but you don't want to store more then one code page in a varcar column, while you can you shouldn't

When you deal with text data that is stored in the char, varchar, varchar(max), or text data type, the most important limitation to consider is that only information from a single code page can be validated by the system. (You can store data from multiple code pages, but this is not recommended.) The exact code page used to validate and store the data depends on the collation of the column. If a column-level collation has not been defined, the collation of the database is used. To determine the code page that is used for a given column, you can use the COLLATIONPROPERTY function, as shown in the following code examples:

Here's some more:

This example illustrates the fact that many locales, such as Georgian and Hindi, do not have code pages, as they are Unicode-only collations. Those collations are not appropriate for columns that use the char, varchar, or text data type

So Georgian or Hindi really need to be stored as nvarchar. Arabic is also a problem:

Another problem you might encounter is the inability to store data when not all of the characters you wish to support are contained in the code page. In many cases, Windows considers a particular code page to be a "best fit" code page, which means there is no guarantee that you can rely on the code page to handle all text; it is merely the best one available. An example of this is the Arabic script: it supports a wide array of languages, including Baluchi, Berber, Farsi, Kashmiri, Kazakh, Kirghiz, Pashto, Sindhi, Uighur, Urdu, and more. All of these languages have additional characters beyond those in the Arabic language as defined in Windows code page 1256. If you attempt to store these extra characters in a non-Unicode column that has the Arabic collation, the characters are converted into question marks.

Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h.

All in all with all the issues you have to deal with when dealing with internalitionalization. It is my opinion that is easier to just use Unicode characters from the start, avoid the extra conversions and take the space hit. Hence my statement earlier.

Finding a branch point with Git?

After a lot of research and discussions, it's clear there's no magic bullet that would work in all situations, at least not in the current version of Git.

That's why I wrote a couple of patches that add the concept of a tail branch. Each time a branch is created, a pointer to the original point is created too, the tail ref. This ref gets updated every time the branch is rebased.

To find out the branch point of the devel branch, all you have to do is use devel@{tail}, that's it.

https://github.com/felipec/git/commits/fc/tail

.NET - Get protocol, host, and port

Even though @Rick has the accepted answer for this question, there's actually a shorter way to do this, using the poorly named Uri.GetLeftPart() method.

Uri url = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string output = url.GetLeftPart(UriPartial.Authority);

There is one catch to GetLeftPart(), however. If the port is the default port for the scheme, it will strip it out. Since port 80 is the default port for http, the output of GetLeftPart() in my example above will be http://www.mywebsite.com.

If the port number had been something other than 80, it would be included in the result.

What is the Oracle equivalent of SQL Server's IsNull() function?

coalesce is supported in both Oracle and SQL Server and serves essentially the same function as nvl and isnull. (There are some important differences, coalesce can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull matches the type of the first argument, that is not true for coalesce, at least on SQL Server.)

Pandas dataframe groupby plot

Similar to Julien's answer above, I had success with the following:

fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
    ax.plot(grp['Date'], grp['adj_close'], label=key)

ax.legend()
plt.show()

This solution might be more relevant if you want more control in matlab.

Solution inspired by: https://stackoverflow.com/a/52526454/10521959

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

Disable all dialog boxes in Excel while running VB script?

From Excel Macro Security - www.excelfunctions.net:

Macro Security in Excel 2007, 2010 & 2013:

.....

The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :

'Disable all macros without notification'

  • This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Disable all macros with notification'

  • This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.

'Disable all macros except digitally signed macros'

  • This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Enable all macros'

  • This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.

If you trust the macros and are ok with enabling them, select this option:

'Enable all macros'

and this dialog box should not show up for macros.

As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.

Android EditText Max Length

I had the same problem. It works perfectly fine when you add this:

android:inputType="textFilter"

to your EditText.

What does the @Valid annotation indicate in Spring?

I think I know where your question is headed. And since this question is the one that pop ups in google's search main results, I can give a plain answer on what the @Valid annotation does.

I'll present 3 scenarios on how I've used @Valid

Model:

public class Employee{
private String name;
@NotNull(message="cannot be null")
@Size(min=1, message="cannot be blank")
private String lastName;
 //Getters and Setters for both fields.
 //...
}

JSP:

...
<form:form action="processForm" modelAttribute="employee">
 <form:input type="text" path="name"/>
 <br>
 <form:input type="text" path="lastName"/>
<form:errors path="lastName"/>
<input type="submit" value="Submit"/>
</form:form>
...

Controller for scenario 1:

     @RequestMapping("processForm")
        public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
        return "employee-confirmation-page";
    }

In this scenario, after submitting your form with an empty lastName field, you'll get an error page since you're applying validation rules but you're not handling it whatsoever.

Example of said error: Exception page

Controller for scenario 2:

 @RequestMapping("processForm")
    public String processFormData(@Valid @ModelAttribute("employee") Employee employee,
BindingResult bindingResult){
                return bindingResult.hasErrors() ? "employee-form" : "employee-confirmation-page";
            }

In this scenario, you're passing all the results from that validation to the bindingResult, so it's up to you to decide what to do with the validation results of that form.

Controller for scenario 3:

@RequestMapping("processForm")
    public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
                return "employee-confirmation-page";
            }
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> invalidFormProcessor(MethodArgumentNotValidException ex){
  //Your mapping of the errors...etc
}

In this scenario you're still not handling the errors like in the first scenario, but you pass that to another method that will take care of the exception that @Valid triggers when processing the form model. Check this see what to do with the mapping and all that.

To sum up: @Valid on its own with do nothing more that trigger the validation of validation JSR 303 annotated fields (@NotNull, @Email, @Size, etc...), you still need to specify a strategy of what to do with the results of said validation.

Hope I was able to clear something for people that might stumble with this.

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

Here is my version of the implementation. It checks and throws an error, if the objects in list doesnt implement INotifyPropertyChanged, so can't forget that issue while developing. On the outside you use the ListItemChanged Event do determine whether the list or the list item itself has changed.

public class SpecialObservableCollection<T> : ObservableCollection<T>
{
    public SpecialObservableCollection()
    {
        this.CollectionChanged += OnCollectionChanged;
    }

    void OnCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        AddOrRemoveListToPropertyChanged(e.NewItems,true); 
        AddOrRemoveListToPropertyChanged(e.OldItems,false); 
    }

    private void AddOrRemoveListToPropertyChanged(IList list, Boolean add)
    {
        if (list == null) { return; }
        foreach (object item in list)
        {
            INotifyPropertyChanged o = item as INotifyPropertyChanged;
            if (o != null)
            {
                if (add)  { o.PropertyChanged += ListItemPropertyChanged; }
                if (!add) { o.PropertyChanged -= ListItemPropertyChanged; }
            }
            else
            {
                throw new Exception("INotifyPropertyChanged is required");
            }
        }
    }

    void ListItemPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        OnListItemChanged(this, e);
    }

    public delegate void ListItemChangedEventHandler(object sender, PropertyChangedEventArgs e);

    public event ListItemChangedEventHandler ListItemChanged;

    private void OnListItemChanged(Object sender, PropertyChangedEventArgs e)
    {
        if (ListItemChanged != null) { this.ListItemChanged(this, e); }
    }


}

Not equal <> != operator on NULL

We use

SELECT * FROM MyTable WHERE ISNULL(MyColumn, ' ') = ' ';

to return all rows where MyColumn is NULL or all rows where MyColumn is an empty string. To many an "end user", the NULL vs. empty string issue is a distinction without a need and point of confusion.

Regular expressions in C: examples?

While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.

I made an answer for this already, but I think it can help here too..

Regex In C To Search For Credit Card Numbers

// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h

#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>

int main(){

bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;


char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";

pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX 
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked. 
subject_length = strlen((char *)subject);




  re = pcre2_compile(
  pattern,               /* the pattern */
  PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  0,                     /* default options */
  &errornumber,          /* for error number */
  &erroroffset,          /* for error offset */
  NULL);                 /* use default compile context */

/* Compilation failed: print the error message and exit. */
if (re == NULL)
  {
  PCRE2_UCHAR buffer[256];
  pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
  return 1;
  }


match_data = pcre2_match_data_create_from_pattern(re, NULL);

rc = pcre2_match(
  re,
  subject,              /* the subject string */
  subject_length,       /* the length of the subject */
  0,                    /* start at offset 0 in the subject */
  0,                    /* default options */
  match_data,           /* block for storing the result */
  NULL);

if (rc < 0)
  {
  switch(rc)
    {
    case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
    pcre2_match_data_free(match_data);
    pcre2_code_free(re);
    Found = 0;
    return Found;
    //  break;
    /*
    Handle other special cases if you like
    */
    default: printf("Matching error %d\n", rc); //break;
    }
  pcre2_match_data_free(match_data);   /* Release memory used for the match */
  pcre2_code_free(re);
  Found = 0;                /* data and the compiled pattern. */
  return Found;
  }


if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);

if (rc == 0)
  printf("ovector was not big enough for all the captured substrings\n");


if (ovector[0] > ovector[1])
  {
  printf("\\K was used in an assertion to set the match start after its end.\n"
    "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
      (char *)(subject + ovector[1]));
  printf("Run abandoned\n");
  pcre2_match_data_free(match_data);
  pcre2_code_free(re);
  return 0;
}

for (i = 0; i < rc; i++)
  {
  PCRE2_SPTR substring_start = subject + ovector[2*i];
  size_t substring_length = ovector[2*i+1] - ovector[2*i];
  printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  }
}

else{
  if(rc > 0){
    Found = true;

    } 
} 
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;

}

Install PCRE using:

wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make 
sudo make install 
sudo ldconfig

Compile using :

gcc foo.c -lpcre2-8 -o foo

Check my answer for more details.

Why doesn't C++ have a garbage collector?

One of the biggest reasons that C++ doesn't have built in garbage collection is that getting garbage collection to play nice with destructors is really, really hard. As far as I know, nobody really knows how to solve it completely yet. There are alot of issues to deal with:

  • deterministic lifetimes of objects (reference counting gives you this, but GC doesn't. Although it may not be that big of a deal).
  • what happens if a destructor throws when the object is being garbage collected? Most languages ignore this exception, since theres really no catch block to be able to transport it to, but this is probably not an acceptable solution for C++.
  • How to enable/disable it? Naturally it'd probably be a compile time decision but code that is written for GC vs code that is written for NOT GC is going to be very different and probably incompatible. How do you reconcile this?

These are just a few of the problems faced.

What's the best way to join on the same table twice?

My problem was to display the record even if no or only one phone number exists (full address book). Therefore I used a LEFT JOIN which takes all records from the left, even if no corresponding exists on the right. For me this works in Microsoft Access SQL (they require the parenthesis!)

SELECT t.PhoneNumber1, t.PhoneNumber2, t.PhoneNumber3
   t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2, t3.someOtherFieldForPhone3
FROM 
(
 (
  Table1 AS t LEFT JOIN Table2 AS t3 ON t.PhoneNumber3 = t3.PhoneNumber
 )
 LEFT JOIN Table2 AS t2 ON t.PhoneNumber2 = t2.PhoneNumber
)
LEFT JOIN Table2 AS t1 ON t.PhoneNumber1 = t1.PhoneNumber;

How to get a path to a resource in a Java JAR file

if netclient.p is inside a JAR file, it won't have a path because that file is located inside other file. in that case, the best path you can have is really file:/path/to/jarfile/bot.jar!/config/netclient.p.

What's the proper way to "go get" a private repository?

That looks like the GitLab issue 5769.

In GitLab, since the repositories always end in .git, I must specify .git at the end of the repository name to make it work, for example:

import "example.org/myuser/mygorepo.git"

And:

$ go get example.org/myuser/mygorepo.git

Looks like GitHub solves this by appending ".git".

It is supposed to be resolved in “Added support for Go's repository retrieval. #5958”, provided the right meta tags are in place.
Although there is still an issue for Go itself: “cmd/go: go get cannot discover meta tag in HTML5 documents”.

What is the proper way to check if a string is empty in Perl?

For string comparisons in Perl, use eq or ne:

if ($str eq "")
{
  // ...
}

The == and != operators are numeric comparison operators. They will attempt to convert both operands to integers before comparing them.

See the perlop man page for more information.

Call Python script from bash with argument

Embedded option:

Wrap python code in a bash function.

#!/bin/bash

function current_datetime {
python - <<END
import datetime
print datetime.datetime.now()
END
}

# Call it
current_datetime

# Call it and capture the output
DT=$(current_datetime)
echo Current date and time: $DT

Use environment variables, to pass data into to your embedded python script.

#!/bin/bash

function line {
PYTHON_ARG="$1" python - <<END
import os
line_len = int(os.environ['PYTHON_ARG'])
print '-' * line_len
END
}

# Do it one way
line 80

# Do it another way
echo $(line 80)

http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html

ORACLE IIF Statement

In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE function.

SET SERVEROUTPUT ON

DECLARE
    x   VARCHAR2(10);
BEGIN
    x := owa_util.ite('a' = 'b','T','F');
    dbms_output.put_line(x);
END;
/

F

PL/SQL procedure successfully completed.

What is the command to truncate a SQL Server log file?

For SQL 2008 you can backup log to nul device:

BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10

And then use DBCC SHRINKFILE to truncate the log file.

Track a new remote branch created on GitHub

If you don't have an existing local branch, it is truly as simple as:

git fetch
git checkout <remote-branch-name>

For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page, just do this:

git checkout feature/Main_Page

This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:

git checkout -t <remote>/<remote-branch-name>

If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.

SQL query return data from multiple tables

Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)

I'll be posting some of the frequently asked questions in MySQL tag.


Trick No. 1 (rows that matches to multiple conditions)

Given this schema

CREATE TABLE MovieList
(
    ID INT,
    MovieName VARCHAR(25),
    CONSTRAINT ml_pk PRIMARY KEY (ID),
    CONSTRAINT ml_uq UNIQUE (MovieName)
);

INSERT INTO MovieList VALUES (1, 'American Pie');
INSERT INTO MovieList VALUES (2, 'The Notebook');
INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
INSERT INTO MovieList VALUES (4, 'Mr. Bean');
INSERT INTO MovieList VALUES (5, 'Expendables 2');

CREATE TABLE CategoryList
(
    MovieID INT,
    CategoryName VARCHAR(25),
    CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
    CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
);

INSERT INTO CategoryList VALUES (1, 'Comedy');
INSERT INTO CategoryList VALUES (1, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Drama');
INSERT INTO CategoryList VALUES (3, 'Documentary');
INSERT INTO CategoryList VALUES (4, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Action');

QUESTION

Find all movies that belong to at least both Comedy and Romance categories.

Solution

This question can be very tricky sometimes. It may seem that a query like this will be the answer:-

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName = 'Comedy' AND
        b.CategoryName = 'Romance'

SQLFiddle Demo

which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND operator, both condition should be true; otherwise, it will be false. Another query is like this,

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')

SQLFiddle Demo

and the result is still incorrect because it matches to record that has at least one match on the categoryName. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.

SELECT  a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')
GROUP BY a.MovieName
HAVING COUNT(*) = 2

SQLFiddle Demo (the answer)


Trick No. 2 (maximum record for each entry)

Given schema,

CREATE TABLE Software
(
    ID INT,
    SoftwareName VARCHAR(25),
    Descriptions VARCHAR(150),
    CONSTRAINT sw_pk PRIMARY KEY (ID),
    CONSTRAINT sw_uq UNIQUE (SoftwareName)  
);

INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');

CREATE TABLE VersionList
(
    SoftwareID INT,
    VersionNo INT,
    DateReleased DATE,
    CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
    CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
);

INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 4, '2012-12-01');

QUESTION

Find the latest version on each software. Display the following columns: SoftwareName,Descriptions,LatestVersion (from VersionNo column),DateReleased

Solution

Some SQL developers mistakenly use MAX() aggregate function. They tend to create like this,

SELECT  a.SoftwareName, a.Descriptions,
        MAX(b.VersionNo) AS LatestVersion, b.DateReleased
FROM    Software a
        INNER JOIN VersionList b
            ON a.ID = b.SoftwareID
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo

(most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by clause) the result produces the correct LatestVersion on each software but obviously the DateReleased are incorrect. MySQL doesn't support Window Functions and Common Table Expression yet as some RDBMS do already. The workaround on this problem is to create a subquery which gets the individual maximum versionNo on each software and later on be joined on the other tables.

SELECT  a.SoftwareName, a.Descriptions,
        b.LatestVersion, c.DateReleased
FROM    Software a
        INNER JOIN
        (
            SELECT  SoftwareID, MAX(VersionNO) LatestVersion
            FROM    VersionList
            GROUP BY SoftwareID
        ) b ON a.ID = b.SoftwareID
        INNER JOIN VersionList c
            ON  c.SoftwareID = b.SoftwareID AND
                c.VersionNO = b.LatestVersion
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo (the answer)


So that was it. I'll be posting another soon as I recall any other FAQ on MySQL tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.

UPDATE 1


Trick No. 3 (Finding the latest record between two IDs)

Given Schema

CREATE TABLE userList
(
    ID INT,
    NAME VARCHAR(20),
    CONSTRAINT us_pk PRIMARY KEY (ID),
    CONSTRAINT us_uq UNIQUE (NAME)  
);

INSERT INTO userList VALUES (1, 'Fluffeh');
INSERT INTO userList VALUES (2, 'John Woo');
INSERT INTO userList VALUES (3, 'hims056');

CREATE TABLE CONVERSATION
(
    ID INT,
    FROM_ID INT,
    TO_ID INT,
    MESSAGE VARCHAR(250),
    DeliveryDate DATE
);

INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');

QUESTION

Find the latest conversation between two users.

Solution

SELECT    b.Name SenderName,
          c.Name RecipientName,
          a.Message,
          a.DeliveryDate
FROM      Conversation a
          INNER JOIN userList b
            ON a.From_ID = b.ID
          INNER JOIN userList c
            ON a.To_ID = c.ID
WHERE     (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
IN
(
    SELECT  LEAST(FROM_ID, TO_ID) minFROM,
            GREATEST(FROM_ID, TO_ID) maxTo,
            MAX(DeliveryDate) maxDate
    FROM    Conversation
    GROUP BY minFROM, maxTo
)

SQLFiddle Demo

How do you update a DateTime field in T-SQL?

If you aren't interested in specifying a time, you can also use the format 'DD/MM/YYYY', however I would stick to a Conversion method, and its relevant ISO format, as you really should avoid using default values.

Here's an example:

SET startDate = CONVERT(datetime,'2015-03-11T23:59:59.000',126) WHERE custID = 'F24'

Hibernate: flush() and commit()

One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.

Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.

function to remove duplicate characters in a string

char[] chars = s.toCharArray();
    HashSet<Character> charz = new HashSet<Character>();

    for(Character c : s.toCharArray() )
    {
        if(!charz.contains(c))
        {
            charz.add(c);
            //System.out.print(c);
        }
    }

    for(Character c : charz)
    {
        System.out.print(c);
    }

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

I was facing the same issue. After many tries below solution worked for me.

Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.

After that you can follow the below steps.

@ABHI KUMAR

Download the Visual C++ Redistributable 2015

Visual C++ Redistributable for Visual Studio 2015 (64-bit)

Visual C++ Redistributable for Visual Studio 2015 (32-bit)

(Reinstal if already installed) then restart your computer or use windows updates for download auto.

For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.

Good examples using java.util.logging

Should declare logger like this:

private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());

so if you refactor your class name it follows.

I wrote an article about java logger with examples here.

Description Box using "onmouseover"

I'd try doing this with jQuery's .hover() event handler system, it makes it easy to show a div with the tooltip when the mouse is over the text, and hide it once it's gone.

Here's a simple example.

HTML:

?<p id="testText">Some Text</p>
<div id="tooltip">Tooltip Hint Text</div>???????????????????????????????????????????

Basic CSS:

?#?tooltip {
display:none;
border:1px solid #F00;
width:150px;
}?

jQuery:

$("#testText").hover(
   function(e){
       $("#tooltip").show();
   },
   function(e){
       $("#tooltip").hide();
  });??????????

Is there a way to reset IIS 7.5 to factory settings?

What worked for me was going to the article someone else had already mentioned, but keying on this piece:

application.config.backup is not created by automatic backup. The backup files are in %systemdrive%\inetpub\history directory. Automatic backup is also a Vista SP1 and above feature. More information can be found in this blog post, http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx

I was able to find backups of my settings from when I had first installed IIS, and just copy and replace the files in the inetsrv\config directory.

Source: http://forums.iis.net/t/1085990.aspx

Align <div> elements side by side

Beware float: left

…there are many ways to align elements side-by-side.

Below are the most common ways to achieve two elements side-by-side…

Demo: View/edit all the below examples on Codepen


Basic styles for all examples below…

Some basic css styles for parent and child elements in these examples:

.parent {
  background: mediumpurple;
  padding: 1rem;
}
.child {
  border: 1px solid indigo;
  padding: 1rem;
}

float:left

Using the float solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)

html

<div class='parent'>
  <div class='child float-left-child'>A</div>
  <div class='child float-left-child'>B</div>
</div>

css

.float-left-child {
  float: left;
}

display:inline-block

html

<div class='parent'>
  <div class='child inline-block-child'>A</div>
  <div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

Note: the space between these two child elements can be removed, by removing the space between the div tags:

display:inline-block (no space)

html

<div class='parent'>
  <div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>

css

.inline-block-child {
  display: inline-block;
}

display:flex

html

<div class='parent flex-parent'>
  <div class='child flex-child'>A</div>
  <div class='child flex-child'>B</div>
</div>

css

.flex-parent {
  display: flex;
}
.flex-child {
  flex: 1;
}

display:inline-flex

html

<div class='parent inline-flex-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.inline-flex-parent {
  display: inline-flex;
}

display:grid

html

<div class='parent grid-parent'>
  <div class='child'>A</div>
  <div class='child'>B</div>
</div>

css

.grid-parent {
  display: grid;
  grid-template-columns: 1fr 1fr
}

How can I get a channel ID from YouTube?

I just found the simplest way to find the channel ID of any YouTube channel !!

Step 1: Play a video of that channel.

Step 2: Click the channel name under that video.

Step 3: Look at the browser address bar.

How to split a string in shell and get the last field

For those that comfortable with Python, https://github.com/Russell91/pythonpy is a nice choice to solve this problem.

$ echo "a:b:c:d:e" | py -x 'x.split(":")[-1]'

From the pythonpy help: -x treat each row of stdin as x.

With that tool, it is easy to write python code that gets applied to the input.

Edit (Dec 2020): Pythonpy is no longer online. Here is an alternative:

$ echo "a:b:c:d:e" | python -c 'import sys; sys.stdout.write(sys.stdin.read().split(":")[-1])'

it contains more boilerplate code (i.e. sys.stdout.read/write) but requires only std libraries from python.

HTTP Basic Authentication - what's the expected web browser experience?

You can use Postman a plugin for chrome. It gives the ability to choose the authentication type you need for each of the requests. In that menu you can configure user and password. Postman will automatically translate the config to a authentication header that will be sent with your request.

How can I do an UPDATE statement with JOIN in SQL Server?

This should work in SQL Server:

update ud 
set assid = sale.assid
from sale
where sale.udid = id

Add padding on view programmatically

Using TypedValue is a much cleaner way of converting to pixels compared to manually calculating:

float paddingDp = 10f;
// Convert to pixels
int paddingPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingDp, context.getResources().getDisplayMetrics());
view.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);

Essentially, TypedValue.applyDimension converts the desired padding into pixels appropriately depending on the current device's display properties.

For more info see: TypedValue.applyDimension Docs.

What is SuppressWarnings ("unchecked") in Java?

It could also mean that the current Java type system version isn't good enough for your case. There were several JSR propositions / hacks to fix this: Type tokens, Super Type Tokens, Class.cast().

If you really need this supression, narrow it down as much as possible (e.g. don't put it onto the class itself or onto a long method). An example:

public List<String> getALegacyListReversed() {
   @SuppressWarnings("unchecked") List<String> list =
       (List<String>)legacyLibrary.getStringList();

   Collections.reverse(list);
   return list;
}

ImportError: No module named pip

I think none of these answers above can fix your problem.

I was also confused by this problem once. You should manually install pip following the official guide pip installation (which currently involves running a single get-pip.py Python script)

after that, just sudo pip install Django. The error will be gone.

Annotations from javax.validation.constraints not working

You need to add @Valid to each member variable, which was also an object that contained validation constraints.

Executing Javascript from Python

You can use requests-html which will download and use chromium underneath.

from requests_html import HTML

html = HTML(html="<a href='http://www.example.com/'>")

script = """
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
"""

val = html.render(script=script, reload=False)
print(val)
# +1 425-984-7450

More on this read here

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

is there a tool to create SVG paths from an SVG file?

Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.

  1. First download Gimp: https://www.gimp.org/downloads/
  2. Export your SVG as a .svg file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it up
  3. Import the SVG file into Gimp with File -> Open, and the following (or similar) dialog should show up:

Gimp SVG Open Dialog

Check both the Import Paths and Merge imported paths options

  1. Then go to Windows->Dockable Dialogues->Paths
  2. Right-click on the single path which says Imported Path and you should see the following dialog:

enter image description here

  1. Click Export Path... and save this text file to a location of your choice
  2. Locate and open up this file with a text editor of your choice e.g Notepad, TextEdit
  3. Copy the text within the <path d="copy this text here" />
  4. Since Gimp formats the text with lots of spaces, you may need to re-format it, by removing some of the spaces to paste it into your HTML in a single line

exclude @Component from @ComponentScan

In case of excluding test component or test configuration, Spring Boot 1.4 introduced new testing annotations @TestComponent and @TestConfiguration.

How to initialize/instantiate a custom UIView class with a XIB file in Swift

Sam's solution is already great, despite it doesn't take different bundles into account (NSBundle:forClass comes to the rescue) and requires manual loading, a.k.a typing code.

If you want full support for your Xib Outlets, different Bundles (use in frameworks!) and get a nice preview in Storyboard try this:

// NibLoadingView.swift
import UIKit

/* Usage: 
- Subclass your UIView from NibLoadView to automatically load an Xib with the same name as your class
- Set the class name to File's Owner in the Xib file
*/

@IBDesignable
class NibLoadingView: UIView {

    @IBOutlet weak var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        nibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        nibSetup()
    }

    private func nibSetup() {
        backgroundColor = .clearColor()

        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        view.translatesAutoresizingMaskIntoConstraints = true

        addSubview(view)
    }

    private func loadViewFromNib() -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)
        let nibView = nib.instantiateWithOwner(self, options: nil).first as! UIView

        return nibView
    }

}

Use your xib as usual, i.e. connect Outlets to File Owner and set File Owner class to your own class.

Usage: Just subclass your own View class from NibLoadingView & Set the class name to File's Owner in the Xib file

No additional code required anymore.

Credits where credit's due: Forked this with minor changes from DenHeadless on GH. My Gist: https://gist.github.com/winkelsdorf/16c481f274134718946328b6e2c9a4d8

Autocompletion of @author in Intellij

One more option, not exactly what you asked, but can be useful:

Go to Settings -> Editor -> File and code templates -> Includes tab (on the right). There is a template header for the new files, you can use the username here:

/**
 * @author myname
 */

For system username use:

/**
 * @author ${USER}
 */

Screen shot from Intellij 2016.02

How can I tell how many objects I've stored in an S3 bucket?

If you are using AWS CLI on Windows, you can use the Measure-Object from PowerShell to get the total counts of files, just like wc -l on *nix.

PS C:\> aws s3 ls s3://mybucket/ --recursive | Measure-Object

Count    : 25
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

Hope it helps.

Cross-platform way of getting temp directory in Python

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

In my case, the issue was caused by a connection problem to the SQL database. I just disconnected and then reconnected the SQL datasource from the design view. I am back up and running. Hope this works for everyone.

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

What do the return values of Comparable.compareTo mean in Java?

It can be used for sorting, and 0 means "equal" while -1, and 1 means "less" and "more (greater)".

Any return value that is less than 0 means that left operand is lesser, and if value is bigger than 0 then left operand is bigger.

How to find duplicate records in PostgreSQL

You can join to the same table on the fields that would be duplicated and then anti-join on the id field. Select the id field from the first table alias (tn1) and then use the array_agg function on the id field of the second table alias. Finally, for the array_agg function to work properly, you will group the results by the tn1.id field. This will produce a result set that contains the the id of a record and an array of all the id's that fit the join conditions.

select tn1.id,
       array_agg(tn2.id) as duplicate_entries, 
from table_name tn1 join table_name tn2 on 
    tn1.year = tn2.year 
    and tn1.sid = tn2.sid 
    and tn1.user_id = tn2.user_id 
    and tn1.cid = tn2.cid
    and tn1.id <> tn2.id
group by tn1.id;

Obviously, id's that will be in the duplicate_entries array for one id, will also have their own entries in the result set. You will have to use this result set to decide which id you want to become the source of 'truth.' The one record that shouldn't get deleted. Maybe you could do something like this:

with dupe_set as (
select tn1.id,
       array_agg(tn2.id) as duplicate_entries, 
from table_name tn1 join table_name tn2 on 
    tn1.year = tn2.year 
    and tn1.sid = tn2.sid 
    and tn1.user_id = tn2.user_id 
    and tn1.cid = tn2.cid
    and tn1.id <> tn2.id
group by tn1.id
order by tn1.id asc)
select ds.id from dupe_set ds where not exists 
 (select de from unnest(ds.duplicate_entries) as de where de < ds.id)

Selects the lowest number ID's that have duplicates (assuming the ID is increasing int PK). These would be the ID's that you would keep around.

How do I find the difference between two values without knowing which is larger?

abs function is definitely not what you need as it is not calculating the distance. Try abs (-25+15) to see that it's not working. A distance between the numbers is 40 but the output will be 10. Because it's doing the math and then removing "minus" in front. I am using this custom function:


def distance(a, b):
    if (a < 0) and (b < 0) or (a > 0) and (b > 0):
        return abs( abs(a) - abs(b) )
    if (a < 0) and (b > 0) or (a > 0) and (b < 0):
        return abs( abs(a) + abs(b) )

print distance(-25, -15) print distance(25, -15) print distance(-25, 15) print distance(25, 15)

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

Remember to set the locale to en_US_POSIX as described in Technical Q&A1480. In Swift 3:

let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
print(formatter.string(from: date))

The issue is that if you're on a device which is using a non-Gregorian calendar, the year will not conform to RFC3339/ISO8601 unless you specify the locale as well as the timeZone and dateFormat string.

Or you can use ISO8601DateFormatter to get you out of the weeds of setting locale and timeZone yourself:

let date = Date()
let formatter = ISO8601DateFormatter()
formatter.formatOptions.insert(.withFractionalSeconds)  // this is only available effective iOS 11 and macOS 10.13
print(formatter.string(from: date))

For Swift 2 rendition, see previous revision of this answer.

Why do we need C Unions?

In school, I used unions like this:

typedef union
{
  unsigned char color[4];
  int       new_color;
}       u_color;

I used it to handle colors more easily, instead of using >> and << operators, I just had to go through the different index of my char array.

What is VanillaJS?

This word, hence, VanillaJS is a just damn joke that changed my life. I had gone to a German company for an interview, I was very poor in JavaScript and CSS, very poor, so the Interviewer said to me: We're working here with VanillaJs, So you should know this framework.

Definitely, I understood that I'was rejected, but for one week I seek for VanillaJS, After all, I found THIS LINK.

What I am just was because of that joke.

VanillaJS === plain `JavaScript`

Rolling back bad changes with svn in Eclipse

The svnbook has a section on how Subversion allows you to revert the changes from a particular revision without affecting the changes that occured in subsequent revisions:

http://svnbook.red-bean.com/en/1.4/svn.branchmerge.commonuses.html#svn.branchmerge.commonuses.undo

I don't use Eclipse much, but in TortoiseSVN you can do this from the from the log dialogue; simply right-click on the revision you want to revert and select "Revert changes from this revision".

In the case that the files for which you want to revert "bad changes" had "good changes" in subsequent revisions, then the process is the same. The changes from the "bad" revision will be reverted leaving the changes from "good" revisions untouched, however you might get conflicts.

Converting a char to uppercase

You can apply the .toUpperCase() directly on String variables or as an attribute to text fields. Ex: -

String str;
TextView txt;

str.toUpperCase();// will change it to all upper case OR
txt.append(str.toUpperCase());
txt.setText(str.toUpperCase());

How do I initialize Kotlin's MutableList to empty MutableList?

I do like below to :

var book: MutableList<Books> = mutableListOf()

/** Returns a new [MutableList] with the given elements. */

public fun <T> mutableListOf(vararg elements: T): MutableList<T>
    = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

Warning: this can introduce security issues that SSL is designed to protect against, rendering your entire codebase insecure. It goes against every recommended practice.

But a really simple fix that worked for me was to call:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

before calling:

curl_exec():

in the php file.

I believe that this disables all verification of SSL certificates.

Browser Caching of CSS files

It does depend on the HTTP headers sent with the CSS files as both of the previous answers state - as long as you don't append any cachebusting stuff to the href. e.g.

<link href="/stylesheets/mycss.css?some_var_to_bust_cache=24312345" rel="stylesheet" type="text/css" />

Some frameworks (e.g. rails) put these in by default.

However If you get something like firebug or fiddler, you can see exactly what your browser is downloading on each request - which is expecially useful for finding out what your browser is doing, as opposed to just what it should be doing.

All browsers should respect the cache headers in the same way, unless configured to ignore them (but there are bound to be exceptions)

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

Why does typeof array with objects return "object" and not "array"?

Quoting the spec

15.4 Array Objects

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

And here's a table for typeof

enter image description here


To add some background, there are two data types in JavaScript:

  1. Primitive Data types - This includes null, undefined, string, boolean, number and object.
  2. Derived data types/Special Objects - These include functions, arrays and regular expressions. And yes, these are all derived from "Object" in JavaScript.

An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.

An array can be considered to be an object with the following properties/keys:

  1. Length - This can be 0 or above (non-negative).
  2. The array indices. By this, I mean "0", "1", "2", etc are all properties of array object.

Hope this helped shed more light on why typeof Array returns an object. Cheers!

How to use jQuery Plugin with Angular 4?

ngOnInit() {
     const $ = window["$"];
     $('.flexslider').flexslider({
        animation: 'slide',
        start: function (slider) {
          $('body').removeClass('loading')
        }
     })
}

Use of String.Format in JavaScript?

Adapt the code from MsAjax string.

Just remove all of the _validateParams code and you are most of the way to a full fledged .NET string class in JavaScript.

Okay, I liberated the msajax string class, removing all the msajax dependencies. It Works great, just like the .NET string class, including trim functions, endsWith/startsWith, etc.

P.S. - I left all of the Visual Studio JavaScript IntelliSense helpers and XmlDocs in place. They are innocuous if you don't use Visual Studio, but you can remove them if you like.

<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
    var a = String.format("Hello {0}!", "world");
    alert(a);

</script>

String.js

// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
// permalink: http://stackoverflow.com/a/2534834/2343

/*
    Copyright (c) 2009, CodePlex Foundation
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted
    provided that the following conditions are met:

    *   Redistributions of source code must retain the above copyright notice, this list of conditions
        and the following disclaimer.

    *   Redistributions in binary form must reproduce the above copyright notice, this list of conditions
        and the following disclaimer in the documentation and/or other materials provided with the distribution.

    *   Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
        promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
    IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
*/

(function(window) {

    $type = String;
    $type.__typeName = 'String';
    $type.__class = true;

    $prototype = $type.prototype;
    $prototype.endsWith = function String$endsWith(suffix) {
        /// <summary>Determines whether the end of this instance matches the specified string.</summary>
        /// <param name="suffix" type="String">A string to compare to.</param>
        /// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
        return (this.substr(this.length - suffix.length) === suffix);
    }

    $prototype.startsWith = function String$startsWith(prefix) {
        /// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
        /// <param name="prefix" type="String">The String to compare.</param>
        /// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
        return (this.substr(0, prefix.length) === prefix);
    }

    $prototype.trim = function String$trim() {
        /// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
        return this.replace(/^\s+|\s+$/g, '');
    }

    $prototype.trimEnd = function String$trimEnd() {
        /// <summary >Removes all trailing white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
        return this.replace(/\s+$/, '');
    }

    $prototype.trimStart = function String$trimStart() {
        /// <summary >Removes all leading white spaces from the current String object.</summary>
        /// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
        return this.replace(/^\s+/, '');
    }

    $type.format = function String$format(format, args) {
        /// <summary>Replaces the format items in a specified String with the text equivalents of the values of   corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
        /// <param name="format" type="String">A format string.</param>
        /// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
        /// <returns type="String">A copy of format in which the format items have been replaced by the   string equivalent of the corresponding instances of object arguments.</returns>
        return String._toFormattedString(false, arguments);
    }

    $type._toFormattedString = function String$_toFormattedString(useLocale, args) {
        var result = '';
        var format = args[0];

        for (var i = 0; ; ) {
            // Find the next opening or closing brace
            var open = format.indexOf('{', i);
            var close = format.indexOf('}', i);
            if ((open < 0) && (close < 0)) {
                // Not found: copy the end of the string and break
                result += format.slice(i);
                break;
            }
            if ((close > 0) && ((close < open) || (open < 0))) {

                if (format.charAt(close + 1) !== '}') {
                    throw new Error('format stringFormatBraceMismatch');
                }

                result += format.slice(i, close + 1);
                i = close + 2;
                continue;
            }

            // Copy the string before the brace
            result += format.slice(i, open);
            i = open + 1;

            // Check for double braces (which display as one and are not arguments)
            if (format.charAt(i) === '{') {
                result += '{';
                i++;
                continue;
            }

            if (close < 0) throw new Error('format stringFormatBraceMismatch');


            // Find the closing brace

            // Get the string between the braces, and split it around the ':' (if any)
            var brace = format.substring(i, close);
            var colonIndex = brace.indexOf(':');
            var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;

            if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');

            var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);

            var arg = args[argNumber];
            if (typeof (arg) === "undefined" || arg === null) {
                arg = '';
            }

            // If it has a toFormattedString method, call it.  Otherwise, call toString()
            if (arg.toFormattedString) {
                result += arg.toFormattedString(argFormat);
            }
            else if (useLocale && arg.localeFormat) {
                result += arg.localeFormat(argFormat);
            }
            else if (arg.format) {
                result += arg.format(argFormat);
            }
            else
                result += arg.toString();

            i = close + 1;
        }

        return result;
    }

})(window);

Android Spinner: Get the selected item change event

For kotlin you can use:

spinner.onItemSelectedListener =  object : AdapterView.OnItemSelectedListener {
    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        
    }

    override fun onNothingSelected(p0: AdapterView<*>?) {
        
    }
}

Note: for parameters of onItemSelected method I use custom variable names

numpy: most efficient frequency counts for unique values in an array

As of Numpy 1.9, the easiest and fastest method is to simply use numpy.unique, which now has a return_counts keyword argument:

import numpy as np

x = np.array([1,1,1,2,2,2,5,25,1,1])
unique, counts = np.unique(x, return_counts=True)

print np.asarray((unique, counts)).T

Which gives:

 [[ 1  5]
  [ 2  3]
  [ 5  1]
  [25  1]]

A quick comparison with scipy.stats.itemfreq:

In [4]: x = np.random.random_integers(0,100,1e6)

In [5]: %timeit unique, counts = np.unique(x, return_counts=True)
10 loops, best of 3: 31.5 ms per loop

In [6]: %timeit scipy.stats.itemfreq(x)
10 loops, best of 3: 170 ms per loop

Is it better in C++ to pass by value or pass by constant reference?

Edit: New article by Dave Abrahams on cpp-next:

Want speed? Pass by value.


Pass by value for structs where the copying is cheap has the additional advantage that the compiler may assume that the objects don't alias (are not the same objects). Using pass-by-reference the compiler cannot assume that always. Simple example:

foo * f;

void bar(foo g) {
    g.i = 10;
    f->i = 2;
    g.i += 5;
}

the compiler can optimize it into

g.i = 15;
f->i = 2;

since it knows that f and g doesn't share the same location. if g was a reference (foo &), the compiler couldn't have assumed that. since g.i could then be aliased by f->i and have to have a value of 7. so the compiler would have to re-fetch the new value of g.i from memory.

For more pratical rules, here is a good set of rules found in Move Constructors article (highly recommended reading).

  • If the function intends to change the argument as a side effect, take it by non-const reference.
  • If the function doesn't modify its argument and the argument is of primitive type, take it by value.
  • Otherwise take it by const reference, except in the following cases
    • If the function would then need to make a copy of the const reference anyway, take it by value.

"Primitive" above means basically small data types that are a few bytes long and aren't polymorphic (iterators, function objects, etc...) or expensive to copy. In that paper, there is one other rule. The idea is that sometimes one wants to make a copy (in case the argument can't be modified), and sometimes one doesn't want (in case one wants to use the argument itself in the function if the argument was a temporary anyway, for example). The paper explains in detail how that can be done. In C++1x that technique can be used natively with language support. Until then, i would go with the above rules.

Examples: To make a string uppercase and return the uppercase version, one should always pass by value: One has to take a copy of it anyway (one couldn't change the const reference directly) - so better make it as transparent as possible to the caller and make that copy early so that the caller can optimize as much as possible - as detailed in that paper:

my::string uppercase(my::string s) { /* change s and return it */ }

However, if you don't need to change the parameter anyway, take it by reference to const:

bool all_uppercase(my::string const& s) { 
    /* check to see whether any character is uppercase */
}

However, if you the purpose of the parameter is to write something into the argument, then pass it by non-const reference

bool try_parse(T text, my::string &out) {
    /* try to parse, write result into out */
}

What are the safe characters for making URLs?

I had a similar problem. I wanted to have pretty URLs and reached the conclusion that I have to allow only letters, digits, - and _ in URLs.

That is fine, but then I wrote some nice regex and I realized that it recognizes all UTF-8 characters are not letters in .NET and was screwed. This appears to be a know problem for the .NET regex engine. So I got to this solution:

private static string GetTitleForUrlDisplay(string title)
{
    if (!string.IsNullOrEmpty(title))
    {
        return Regex.Replace(Regex.Replace(title, @"[^A-Za-z0-9_-]", new MatchEvaluator(CharacterTester)).Replace(' ', '-').TrimStart('-').TrimEnd('-'), "[-]+", "-").ToLower();
    }
    return string.Empty;
}


/// <summary>
/// All characters that do not match the patter, will get to this method, i.e. useful for Unicode characters, because
/// .NET implementation of regex do not handle Unicode characters. So we use char.IsLetterOrDigit() which works nicely and we
/// return what we approve and return - for everything else.
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string CharacterTester(Match m)
{
    string x = m.ToString();
    if (x.Length > 0 && char.IsLetterOrDigit(x[0]))
    {
        return x.ToLower();
    }
    else
    {
        return "-";
    }
}

Jquery function BEFORE form submission

You can use the onsubmit function.

If you return false the form won't get submitted. Read up about it here.

$('#myform').submit(function() {
  // your code here
});

struct.error: unpack requires a string argument of length 4

By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.

JAXB: how to marshall map into <key>value</key>

I didn't see anything that really answered this very well. I found something that worked pretty well here:

Use JAXB XMLAnyElement type of style to return dynamic element names

I modified it a bit to support hashmap trees. You could add other collections.

public class MapAdapter extends XmlAdapter<MapWrapper, Map<String, Object>> {
    @Override
    public MapWrapper marshal(Map<String, Object> m) throws Exception {
        MapWrapper wrapper = new MapWrapper();
        List elements = new ArrayList();
        for (Map.Entry<String, Object> property : m.entrySet()) {

            if (property.getValue() instanceof Map)
                elements.add(new JAXBElement<MapWrapper>(new QName(getCleanLabel(property.getKey())),
                        MapWrapper.class, marshal((Map) property.getValue())));
            else
                elements.add(new JAXBElement<String>(new QName(getCleanLabel(property.getKey())),
                        String.class, property.getValue().toString()));
        }
        wrapper.elements = elements;
        return wrapper;
    }

    @Override
    public Map<String, Object> unmarshal(MapWrapper v) throws Exception {
        // TODO
        throw new OperationNotSupportedException();
    }

    // Return a XML-safe attribute.  Might want to add camel case support
    private String getCleanLabel(String attributeLabel) {
        attributeLabel = attributeLabel.replaceAll("[()]", "").replaceAll("[^\\w\\s]", "_").replaceAll(" ", "_");
        return attributeLabel;
    }
}
class MapWrapper {
    @XmlAnyElement
    List elements;
}

Then to implement it:

static class myxml {
    String name = "Full Name";
    String address = "1234 Main St";
    // I assign values to the map elsewhere, but it's just a simple
    // hashmap with a hashmap child as an example.
    @XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, Object> childMap;
}

Feeding this through a simple Marshaller gives output that looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myxml>
    <name>Full Name</name>
    <address>1234 Main St</address>
    <childMap>
        <key2>value2</key2>
        <key1>value1</key1>
        <childTree>
            <childkey1>childvalue1</childkey1>
        </childTree>
    </childMap>
</myxml>

Javascript Regexp dynamic generation from variables?

You have to use RegExp:

str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));

When I'm concatenating strings, all slashes are gone.

If you have a backslash in your pattern to escape a special regex character, (like \(), you have to use two backslashes in the string (because \ is the escape character in a string): new RegExp('\\(') would be the same as /\(/.

So your patterns have to become:

var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';

Get size of a View in React Native

You can directly use the Dimensions module and calc your views sizes. Actually, Dimensions give to you the main window sizes.

import { Dimensions } from 'Dimensions';

Dimensions.get('window').height;
Dimensions.get('window').width;

Hope to help you!

Update: Today using native StyleSheet with Flex arranging on your views help to write clean code with elegant layout solutions in wide cases instead computing your view sizes...

Although building a custom grid components, which responds to main window resize events, could produce a good solution in simple widget components

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Code:

private static void RegisterServices(IKernel kernel)
{
    Mock<IProductRepository> mock=new Mock<IProductRepository>();
    mock.Setup(x => x.Products).Returns(new List<Product>
    {
        new Product {Name = "Football", Price = 23},
        new Product {Name = "Surf board", Price = 179},
        new Product {Name = "Running shose", Price = 95}
    });

    kernel.Bind<IProductRepository>().ToConstant(mock.Object);
}        

but see exception.

Get div's offsetTop positions in React

I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.

Example code:

import { useRef } from 'react'

function Component() {
  const inputRef = useRef()

  return (
    <input ref={inputRef} />
    <div
      onScroll={() => {
        const { offsetTop } = inputRef.current
        ...
      }}
    >
  )
}

How to know when a web page was last updated?

In general, there is no way to know when something on another site has been changed. If the site offers an RSS feed, you should try that. If the site does not offer an RSS feed (or if the RSS feed doesn't include the information you're looking for), then you have to scrape and compare.

What is the most efficient way of finding all the factors of a number in Python?

agf's answer is really quite cool. I wanted to see if I could rewrite it to avoid using reduce(). This is what I came up with:

import itertools
flatten_iter = itertools.chain.from_iterable
def factors(n):
    return set(flatten_iter((i, n//i) 
                for i in range(1, int(n**0.5)+1) if n % i == 0))

I also tried a version that uses tricky generator functions:

def factors(n):
    return set(x for tup in ([i, n//i] 
                for i in range(1, int(n**0.5)+1) if n % i == 0) for x in tup)

I timed it by computing:

start = 10000000
end = start + 40000
for n in range(start, end):
    factors(n)

I ran it once to let Python compile it, then ran it under the time(1) command three times and kept the best time.

  • reduce version: 11.58 seconds
  • itertools version: 11.49 seconds
  • tricky version: 11.12 seconds

Note that the itertools version is building a tuple and passing it to flatten_iter(). If I change the code to build a list instead, it slows down slightly:

  • iterools (list) version: 11.62 seconds

I believe that the tricky generator functions version is the fastest possible in Python. But it's not really much faster than the reduce version, roughly 4% faster based on my measurements.

How to Compare two strings using a if in a stored procedure in sql server 2008?

Two things:

  1. Only need one (1) equals sign to evaluate
  2. You need to specify a length on the VARCHAR - the default is a single character.

Use:

DECLARE @temp VARCHAR(10)
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

VARCHAR(10) means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -

DECLARE @temp VARCHAR
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "yes"

DECLARE @temp VARCHAR
    SET @temp = 'mtest'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "no".

2 "style" inline css img tags?

You don't need 2 style attributes - just use one:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                     style="height:100px;width:100px;" alt="25"/>

Consider, however, using a CSS class instead:

CSS:

.100pxSquare
{
  width: 100px;
  height: 100px;
}

HTML:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                          class="100pxSquare" alt="25"/>

What is the most efficient way to check if a value exists in a NumPy array?

To check multiple values, you can use numpy.in1d(), which is an element-wise function version of the python keyword in. If your data is sorted, you can use numpy.searchsorted():

import numpy as np
data = np.array([1,4,5,5,6,8,8,9])
values = [2,3,4,6,7]
print np.in1d(values, data)

index = np.searchsorted(data, values)
print data[index] == values

iframe refuses to display

For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:

Content-Security-Policy: frame-ancestors 'self'

Or, add this to your web server's CSP configuration.

pros and cons between os.path.exists vs os.path.isdir

os.path.exists will also return True if there's a regular file with that name.

os.path.isdir will only return True if that path exists and is a directory, or a symbolic link to a directory.

How to put a component inside another component in Angular2?

If you remove directives attribute it should work.

@Component({
    selector: 'parent',
    template: `
            <h1>Parent Component</h1>
            <child></child>
        `
    })
    export class ParentComponent{}


@Component({
    selector: 'child',    
    template: `
            <h4>Child Component</h4>
        `
    })
    export class ChildComponent{}

Directives are like components but they are used in attributes. They also have a declarator @Directive. You can read more about directives Structural Directives and Attribute Directives.

There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.

A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.


Also if you are open the glossary you can find that components are also directives.

Directives fall into one of the following categories:

  • Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.

  • Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.

  • Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.


The difference that components have a template. See Angular Architecture overview.

A directive is a class with a @Directive decorator. A component is a directive-with-a-template; a @Component decorator is actually a @Directive decorator extended with template-oriented features.


The @Component metadata doesn't have directives attribute. See Component decorator.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

How do I set vertical space between list items?

Add a margin to your li tags. That will create space between the li and you can use line-height to set the spacing to the text within the li tags.

JSON.parse unexpected token s

What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.

so something is not a valid JSON but "something" is.

A valid JSON is -

JSON = null
    /* boolean literal */
    or true or false
    /* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/
    or JSONNumber
    /* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/
    or JSONString

    /* Property names must be double-quoted strings; trailing commas are forbidden. */
    or JSONObject
    or JSONArray

Examples -

JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null 
JSON.parse("'foo'"); // error since string should be wrapped by double quotes

You may want to look JSON.

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

Converting string to number in javascript/jQuery

var string = 123 (is string),

parseInt(parameter is string);

var string = '123';

var int= parseInt(string );

console.log(int);  //Output will be 123.

Good Java graph algorithm library?

I don't know if I'd call it production-ready, but there's jGABL.

How to find children of nodes using BeautifulSoup

try this:

li = soup.find("li", { "class" : "test" })
children = li.find_all("a") # returns a list of all <a> children of li

other reminders:

The find method only gets the first occurring child element. The find_all method gets all descendant elements and are stored in a list.

Capturing window.onbeforeunload

you just cant do alert() in onbeforeunload, anything else works

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

public static String readClob(Clob clob) throws SQLException, IOException {
    StringBuilder sb = new StringBuilder((int) clob.length());
    Reader r = clob.getCharacterStream();
    char[] cbuf = new char[2048];
    int n;
    while ((n = r.read(cbuf, 0, cbuf.length)) != -1) {
        sb.append(cbuf, 0, n);
    }
    return sb.toString();
}

The above approach is also very efficient.

How to take MySQL database backup using MySQL Workbench?

In workbench 6.0 Connect to any of the database. You will see two tabs.

1.Management 2. Schemas

By default Schemas tab is selected. Select Management tab then select Data Export . You will get list of all databases. select the desired database and and the file name and ther options you wish and start export. You are done with backup.

How do you count the number of occurrences of a certain substring in a SQL varchar?

Perhaps you should not store data that way. It is a bad practice to ever store a comma delimited list in a field. IT is very inefficient for querying. This should be a related table.

Swift GET request with parameters

Swift 3:

extension URL {
    func getQueryItemValueForKey(key: String) -> String? {
        guard let components = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else {
              return nil
        }

        guard let queryItems = components.queryItems else { return nil }
     return queryItems.filter {
                 $0.name.lowercased() == key.lowercased()
                 }.first?.value
    }
}

I used it to get the image name for UIImagePickerController in func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]):

var originalFilename = ""
if let url = info[UIImagePickerControllerReferenceURL] as? URL, let imageIdentifier = url.getQueryItemValueForKey(key: "id") {
    originalFilename = imageIdentifier + ".png"
    print("file name : \(originalFilename)")
}

The import javax.servlet can't be resolved

If not done yet, you need to integrate Tomcat in your Servers view. Rightclick there and choose New > Server. Select the appropriate Tomcat version from the list and complete the wizard.

When you create a new Dynamic Web Project, you should select the integrated server from the list as Targeted Runtime in the 1st wizard step.

Or when you have an existing Dynamic Web Project, you can set/change it in Targeted Runtimes entry in project's properties. Eclipse will then automagically add all its libraries to the build path (without having a copy of them in the project!).

How to rename array keys in PHP?

Talking about functional PHP, I have this more generic answer:

    array_map(function($arr){
        $ret = $arr;
        $ret['value'] = $ret['url'];
        unset($ret['url']);
        return $ret;
    }, $tag);
}

How do I get the value of a textbox using jQuery?

Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.

How can I match on an attribute that contains a certain string?

I came here searching solution for Ranorex Studio 9.0.1. There is no contains() there yet. Instead we can use regex like:

div[@class~'atag']

MySQL select query with multiple conditions

Lets suppose there is a table with following describe command for table (hello)- name char(100), id integer, count integer, city char(100).

we have following basic commands for MySQL -

select * from hello;
select name, city from hello;
etc 

select name from hello where id = 8;
select id from hello where name = 'GAURAV';

now lets see multiple where condition -

select name from hello where id = 3 or id = 4 or id = 8 or id = 22;

select name from hello where id =3 and count = 3 city = 'Delhi';

This is how we can use multiple where commands in MySQL.

Hibernate Criteria Query to get specific columns

You can map another entity based on this class (you should use entity-name in order to distinct the two) and the second one will be kind of dto (dont forget that dto has design issues ). you should define the second one as readonly and give it a good name in order to be clear that this is not a regular entity. by the way select only few columns is called projection , so google with it will be easier.

alternative - you can create named query with the list of fields that you need (you put them in the select ) or use criteria with projection

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

How to determine the current iPhone/device model?

All the answers are great. After getting some bits I have created THIS GIST

It contains DeviceModel which is part and of the 'Core' (No UIKit dependency) Module. It can even be used as a model.

It can be used from another 'Core' module component like that:

struct DeviceHelper {
    static var specificModelType: DeviceModel {
        var systemInfo = utsname()
            uname(&systemInfo)
            let modelCode = withUnsafePointer(to: &systemInfo.machine) {
                $0.withMemoryRebound(to: CChar.self, capacity: 1) {
                    ptr in String.init(validatingUTF8: ptr)
                }
            }

        let modelType = DeviceModel(modelCode: modelCode ?? "")
        if modelType == .simulator {
            return .simulator
            // UP TO YOU
//            if let simModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
//                return DeviceModel(modelCode: simModelCode)
//            }
        } else {
            return modelType
        }
}

Or from a 'UI' Module component like that:

extension UIDevice {
    static var specificModelType: DeviceModel {
        DeviceHelper.specificModelType
    }
}

Why is Maven downloading the maven-metadata.xml every time?

Maven does this because your dependency is in a SNAPSHOT version and maven has no way to detect any changes made to that snapshot version in the repository. Release your artifact and change the version in pom.xml to that version and maven will no longer fetch the metadata file.

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

This solution worked for me :

I preinstalled the environnement with anaconda (here is the code)

conda create -n YOURENVNAME python=3.6 // 3.6> incompatible with keras
conda activate YOURENVNAME
conda install tensorflow-gpu
conda install -c anaconda keras
conda install -c anaconda scikit-learn
conda install matplotlib

but after I had still these warnings

2020-02-23 13:31:44.910213: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found

2020-02-23 13:31:44.925815: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cublas64_10.dll

2020-02-23 13:31:44.941384: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cufft64_10.dll

2020-02-23 13:31:44.947427: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library curand64_10.dll

2020-02-23 13:31:44.965893: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusolver64_10.dll

2020-02-23 13:31:44.982990: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusparse64_10.dll

2020-02-23 13:31:44.990036: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudnn64_7.dll'; dlerror: cudnn64_7.dll not found

How I solved the first warning : I just download a zip file wich contained all the cudnn files (dll, etc) here : https://developer.nvidia.com/cudnn

How I solved the second warning : I looked the last missing file (cudart64_101.dll) in my virtual env created by conda and I just copy/pasted it in the same lib folder than for the .dll cudnn

jQuery Scroll to Div

Something like this would let you take over the click of each internal link and scroll to the position of the corresponding bookmark:

$(function(){
  $('a[href^=#]').click(function(e){
    var name = $(this).attr('href').substr(1);
    var pos = $('a[name='+name+']').offset();
    $('body').animate({ scrollTop: pos.top });
    e.preventDefault();
  });
});

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

Converting Stream to String and back...what are we missing?

This is so common but so profoundly wrong. Protobuf data is not string data. It certainly isn't ASCII. You are using the encoding backwards. A text encoding transfers:

  • an arbitrary string to formatted bytes
  • formatted bytes to the original string

You do not have "formatted bytes". You have arbitrary bytes. You need to use something like a base-n (commonly: base-64) encode. This transfers

  • arbitrary bytes to a formatted string
  • a formatted string to the original bytes

look at Convert.ToBase64String and Convert. FromBase64String

Change the "From:" address in Unix "mail"

On Debian 7 I was still unable to correctly set the sender address using answers from this question, (would always be the hostname of the server) but resolved it this way.

Install heirloom-mailx

apt-get install heirloom-mailx

ensure it's the default.

update-alternatives --config mailx

Compose a message.

mail -s "Testing from & replyto" -r "sender <[email protected]>" -S replyto="[email protected]" [email protected] < <(echo "Test message")

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

After endless searching and trying the already supplied answers (adding the PUT,DELETE verbs and remove WEBdav) it just didn't work.

I went to IIS logging settings: > View Log Files. In my case W3SVC4 was the folder with the latest date, opened the folder, looked up the latest log file and saw this entry: GET /Rejected-By-UrlScan ~/MYDOMAIN/API/ApiName/UpdateMETHOD

The Update method was listed with verb GET, weird right? So I Googled for Rejected-By-UrlScan and found this link: UrlScan Broke My Blog.

I went to here: %windir%\system32\inetsrv\urlscan\UrlScan.ini

Basically, the UrlScan blocked PUT and DELETE verbs. I opened this INI file, added the PUT and DELETE to the AllowVerbs and removed them from the DenyVerbs listings. I saved the INI file and it worked! So for me these steps were necessary next to the ExtensionlessUrlHandler hints.

Windows Webserver 2008 R2 (64 bit), IIS 7.5. I'm using this in combination with DotNetNuke (DNN) WebAPI. ASP.Net 4.0 My update method:

[HttpPut]
[DnnAuthorize(StaticRoles = "MyRoleNames")]
public HttpResponseMessage UpdateMETHOD(DTO.MyObject myData)

XMLHttpRequest status 0 (responseText is empty)

The cause of your problems is that you are trying to do a cross-domain call and it fails.

If you're doing localhost development you can make cross-domain calls - I do it all the time.

For Firefox, you have to enable it in your config settings

signed.applets.codebase_principal_support = true

Then add something like this to your XHR open code:

  if (isLocalHost()){
    if (typeof(netscape) != 'undefined' && typeof(netscape.security) != 'undefined'){
      netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
    }
  }

For IE, if I remember right, all you have to do is enable the browser's Security setting under "Miscellaneous → Access data sources across domains" to get it to work with ActiveX XHRs.

IE8 and above also added cross-domain capabilities to the native XmlHttpRequest objects, but I haven't played with those yet.

Updating to latest version of CocoaPods?

If you got System Integrity Protection enabled or any other permission write error, which is enabled by default since macOS Sierra release, you should update CocoaPods, running this line in terminal:

sudo gem install cocoapods -n/usr/local/bin

After installing, check your pod version:

pod --version

You will get rid of this error:

ERROR:  While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /usr/bin directory

And it will install latest CocoaPods:

Successfully installed cocoapods-x.x.x
Parsing documentation for cocoapods-x.x.x
Installing ri documentation for cocoapods-x.x.x
Done installing documentation for cocoapods after 4 seconds
1 gem installed

JSON - Iterate through JSONArray

Change

JSONObject objects = getArray.getJSONArray(i);

to

JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.


I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
    {
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
      {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
      }
      System.out.println();
    }
  }
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/

Wordpress plugin install: Could not create directory

The user that is running your web server does not have permissions to write to the directory that Wordpress is intending to create the plugin directory in. You should chown the directory in question to the user that is running Wordpress. It is most likely not root.

In short, this is a permissions issue. Your touch command is working because you're using it as root, and root has global permissions to write wherever it wants.

Extracting Nupkg files using command line

With PowerShell 5.1 (PackageManagement module)

Install-Package -Name MyPackage -Source (Get-Location).Path -Destination C:\outputdirectory

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

Understanding MongoDB BSON Document size limit

According to https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1

If you expect that a blog post may exceed the 16Mb document limit, you should extract the comments into a separate collection and reference the blog post from the comment and do an application-level join.

// posts
[
  {
    _id: ObjectID('AAAA'),
    text: 'a post',
    ...
  }
]

// comments
[
  {
    text: 'a comment'
    post: ObjectID('AAAA')
  },
  {
    text: 'another comment'
    post: ObjectID('AAAA')
  }
]

maxReceivedMessageSize and maxBufferSize in app.config

You need to do that on your binding, but you'll need to do it on both Client and Server. Something like:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding maxBufferSize="64000000" maxReceivedMessageSize="64000000" />
        </basicHttpBinding>
    </bindings>
</system.serviceModel>

Setting maxlength of textbox with JavaScript or jQuery

$('#yourTextBoxId').live('change keyup paste', function(){
    if ($('#yourTextBoxId').val().length > 11) {
        $('#yourTextBoxId').val($('#yourTextBoxId').val().substr(0,10));
    }
});

I Used this along with vars and selectors caching for performance and that did the trick ..

Detecting a redirect in ajax request?

While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:

I configured my server app to set a custom response header (X-Response-Url) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url") is defined, in which case it compares it to the url that it originally requested via $.ajax(). If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.

This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.


On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:

import pyramid.events

@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
    request = event.request
    if request.is_xhr:
        event.response.headers['X-Response-URL'] = request.url

Meaning of ${project.basedir} in pom.xml

${project.basedir} is the root directory of your project.

${project.build.directory} is equivalent to ${project.basedir}/target

as it is defined here: https://github.com/apache/maven/blob/trunk/maven-model-builder/src/main/resources/org/apache/maven/model/pom-4.0.0.xml#L53

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

How to select <td> of the <table> with javascript?

try document.querySelectorAll("#table td");

Checking network connection

Make sure your pip is up to date by running

pip install --upgrade pip

Install the requests package using

pip install requests  
    import requests
    import webbrowser
    url = "http://www.youtube.com"

    timeout = 6
    try:
        request = requests.get(url, timeout=timeout)
        print("Connected to the Internet")
        print("browser is loading url")
        webbrowser.open(url)
    except (requests.ConnectionError, requests.Timeout) as exception:
       print("poor or no internet connection.")

There are No resources that can be added or removed from the server

if your project maven based, you can also try updating your project maven config by selecting project. Right click project> Maven>Update Project option. it will update your project config.

JavaScript dictionary with names

Try:

var myMappings = {
    "Name":     "10%",
    "Phone":    "10%",
    "Address":  "50%",
    "Zip":      "10%",
    "Comments": "20%"
}

// Access is like this
myMappings["Name"] // Returns "10%"
myMappings.Name // The same thing as above

// To loop through...
for(var title in myMappings) {
    // Do whatever with myMappings[title]
}

How to Update Date and Time of Raspberry Pi With out Internet

Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.

This is how it works:

  1. Type sudo raspi-config in the Raspberry Pi command line
  2. Internationalization options
  3. Change Time Zone
  4. Select geographical area
  5. Select city or region
  6. Reboot your pi

Next thing you can set time using this command

sudo date -s "Mon Aug  12 20:14:11 UTC 2014"

More about data and time

man date

When Pi is connected to computer should have to manually set data and time

Display all post meta keys and meta values of the same post ID in wordpress

Default Usage

Get the meta for all keys:

<?php $meta = get_post_meta($post_id); ?>

Get the meta for a single key:

<?php $key_1_values = get_post_meta( 76, 'key_1' ); ?>

for example:

$myvals = get_post_meta($post_id);

foreach($myvals as $key=>$val)
{
    echo $key . ' : ' . $val[0] . '<br/>';
}

Note: some unwanted meta keys starting with "underscore(_)" will also come, so you will need to filter them out.

For reference: See Codex

HTML form with side by side input fields

You should put the input for the last name into the same div where you have the first name.

<div>
    <label for="username">First Name</label>
    <input id="user_first_name" name="user[first_name]" size="30" type="text" />
    <input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>

Then, in your CSS give your #user_first_name and #user_last_name height and float them both to the left. For example:

#user_first_name{
    max-width:100px; /*max-width for responsiveness*/
    float:left;
}

#user_lastname_name{
    max-width:100px;
    float:left;
}

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

As for now Eclipse Neon service release is available. So if someone is still encounters this trouble, just go to

Help ? Check for Updates

and install provided updates.

Easiest way to compare arrays in C#

For some applications may be better:

string.Join(",", arr1) == string.Join(",", arr2)

Open links in new window using AngularJS

this is the code of your button

<a href="AddNewUserAdmin" 
   class="btn btn-info " 
   ng-click="showaddnewuserpage()">
  <span class="glyphicon glyphicon-plus-sign"></span> Add User</a>

in the controller just add this function.

 var app = angular.module('userAPP', []);

app.controller('useraddcontroller', function ($scope, $http, $window) {

$scope.showaddnewuserpage = function () {

    $window.location.href = ('/AddNewUserAdmin');
}

});

What is the best way to add a value to an array in state

handleValueChange = (value) => {
      let myArr= [...this.state.myArr]
      myArr.push(value)
      this.setState({
         myArr
     })

This might do the work.

Is there a limit on an Excel worksheet's name length?

I use the following vba code where filename is a string containing the filename I want, and Function RemoveSpecialCharactersAndTruncate is defined below:

worksheet1.Name = RemoveSpecialCharactersAndTruncate(filename)

'Function to remove special characters from file before saving

Private Function RemoveSpecialCharactersAndTruncate$(ByVal FormattedString$)
    Dim IllegalCharacterSet$
    Dim i As Integer
'Set of illegal characters
    IllegalCharacterSet$ = "*." & Chr(34) & "//\[]:;|=,"
    'Iterate through illegal characters and replace any instances
    For i = 1 To Len(IllegalCharacterSet) - 1
        FormattedString$ = Replace(FormattedString$, Mid(IllegalCharacterSet, i, 1), "")
    Next
    'Return the value capped at 31 characters (Excel limit)
    RemoveSpecialCharactersAndTruncate$ = Left(FormattedString$, _
                           Application.WorksheetFunction.Min(Len(FormattedString), 31))
End Function

javascript variable reference/alias

In JavaScript, primitive types such as integers and strings are passed by value whereas objects are passed by reference. So in order to achieve this you need to use an object:

// declare an object with property x
var obj = { x: 1 };
var aliasToObj = obj;
aliasToObj.x ++;
alert( obj.x ); // displays 2

How do I keep CSS floats in one line?

Another option: Do not float your right column; just give it a left margin to move it beyond the float. You'll need a hack or two to fix IE6, but that's the basic idea.

ICommand MVVM implementation

I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.

Teaser:

public class SampleViewModel: BaseViewModelStub
{
    public string Name { get; set; }

    [UiCommand]
    public void HelloWorld()
    {
        MessageBox.Show("Hello World!");
    }

    [UiCommand]
    public void Print()
    {
        MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
    }

    public bool CanPrint()
    {
        return !String.IsNullOrEmpty(Name);
    }
}

}

UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.

How do I assign ls to an array in Linux Bash?

This would print the files in those directories line by line.

array=(ww/* ee/* qq/*)
printf "%s\n" "${array[@]}"

How to add hours to current time in python

Import datetime and timedelta:

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'

But the better way is:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'

You can refer strptime and strftime behavior to better understand how python processes dates and time field

PHP Check for NULL

How about using

if (empty($result['column']))

What is the difference between display: inline and display: inline-block?

A visual answer

Imagine a <span> element inside a <div>. If you give the <span> element a height of 100px and a red border for example, it will look like this with

display: inline

display: inline

display: inline-block

display: inline-block

display: block

enter image description here

Code: http://jsfiddle.net/Mta2b/

Elements with display:inline-block are like display:inline elements, but they can have a width and a height. That means that you can use an inline-block element as a block while flowing it within text or other elements.

Difference of supported styles as summary:

  • inline: only margin-left, margin-right, padding-left, padding-right
  • inline-block: margin, padding, height, width

"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');

How to view AndroidManifest.xml from APK file?

There is an online tool that lets you upload an APK It decompiles it and finally lets you to download a zip with all sources, manifest XML file and so on decompiled, all of that without having to install any program on your computer: http://www.javadecompilers.com/apk

Also if you wish just to check on some params you can, by their UI

IIS_IUSRS and IUSR permissions in IIS8

When I added IIS_IUSRS permission to site folder - resources, like js and css, still were unaccessible (error 401, forbidden). However, when I added IUSR - it became ok. So for sure "you CANNOT remove the permissions for IUSR without worrying", dear @Travis G@

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

After enabling "SQL Server and Windows Authentication mode"(check above answers on how to), navigate to the following.

  1. Computer Mangement(in Start Menu)
  2. Services And Applications
  3. SQL Server Configuration Manager
  4. SQL Server Network Configuration
  5. Protocols for MSSQLSERVER
  6. Right click on TCP/IP and Enable it.

Finally restart the SQL Server.

Android Endless List

Just wanted to contribute a solution that I used for my app.

It is also based on the OnScrollListener interface, but I found it to have a much better scrolling performance on low-end devices, since none of the visible/total count calculations are carried out during the scroll operations.

  1. Let your ListFragment or ListActivity implement OnScrollListener
  2. Add the following methods to that class:

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        //leave this empty
    }
    
    @Override
    public void onScrollStateChanged(AbsListView listView, int scrollState) {
        if (scrollState == SCROLL_STATE_IDLE) {
            if (listView.getLastVisiblePosition() >= listView.getCount() - 1 - threshold) {
                currentPage++;
                //load more list items:
                loadElements(currentPage);
            }
        }
    }
    

    where currentPage is the page of your datasource that should be added to your list, and threshold is the number of list items (counted from the end) that should, if visible, trigger the loading process. If you set threshold to 0, for instance, the user has to scroll to the very end of the list in order to load more items.

  3. (optional) As you can see, the "load-more check" is only called when the user stops scrolling. To improve usability, you may inflate and add a loading indicator to the end of the list via listView.addFooterView(yourFooterView). One example for such a footer view:

    <?xml version="1.0" encoding="utf-8"?>
    
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/footer_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp" >
    
        <ProgressBar
            android:id="@+id/progressBar1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_gravity="center_vertical" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/progressBar1"
            android:padding="5dp"
            android:text="@string/loading_text" />
    
    </RelativeLayout>
    
  4. (optional) Finally, remove that loading indicator by calling listView.removeFooterView(yourFooterView) if there are no more items or pages.

Formula to check if string is empty in Crystal Reports

If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}

Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.

How to configure static content cache per folder and extension in IIS7?

You can do it on a per file basis. Use the path attribute to include the filename

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <location path="YourFileNameHere.xml">
        <system.webServer>
            <staticContent>
                <clientCache cacheControlMode="DisableCache" />
            </staticContent>
        </system.webServer>
    </location>
</configuration>

Android emulator failed to allocate memory 8

This error fires if you set the AVD RAM to anything that is larger then the single largest block of continuous memory the emulator is able to allocate. Close anything RAM heavy, start your emulator, start everything else you need. In a previous answer I have limited this to x86 images with IntelHAXM, but this actually is the case for all types of emulator instances.

Simulator or Emulator? What is the difference?

If a flight-simulator could transport you from A to B then it would be a flight-emulator.

An emulator can replace the original for real use.
A Virtual PC emulates a PC.

A simulator is a model for study and analysis.

An emulator will always have to operate close to real-time. For a simulator that is not always the case. A geological simulation could do 1000 years/second or more.

Remove table row after clicking table row delete button

you can do it like this:

<script>
    function SomeDeleteRowFunction(o) {
     //no clue what to put here?
     var p=o.parentNode.parentNode;
         p.parentNode.removeChild(p);
    }
    </script>

    <table>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
    </table>

How to initialize a JavaScript Date to a particular time zone

Try using ctoc from npm. https://www.npmjs.com/package/ctoc_timezone

It has got simple functionality to change timezones (most timezones around 400) and all custom formats u want it to display.

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

You have entered wrong port number 3360 instead of 3306. You dont need to write database port number if you are using daefault (3306 in case of MySQL)

MessageBox Buttons?

  1. Your call to MessageBox.Show needs to pass MessageBoxButtons.YesNo to get the Yes/No buttons instead of the OK button.

  2. Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    // user clicked yes
}
else
{
    // user clicked no
}

Change selected value of kendo ui dropdownlist

The Simplest way to do this is:

$("#Instrument").data('kendoDropDownList').value("A value");

Here is the JSFiddle example.

object==null or null==object?

This is not of much value in Java (1.5+) except when the type of object is Boolean. In which case, this can still be handy.

if (object = null) will not cause compilation failure in Java 1.5+ if object is Boolean but would throw a NullPointerException at runtime.

How do I obtain a Query Execution Plan in SQL Server?

In addition to the comprehensive answer already posted sometimes it is useful to be able to access the execution plan programatically to extract information. Example code for this is below.

DECLARE @TraceID INT
EXEC StartCapture @@SPID, @TraceID OUTPUT
EXEC sp_help 'sys.objects' /*<-- Call your stored proc of interest here.*/
EXEC StopCapture @TraceID

Example StartCapture Definition

CREATE PROCEDURE StartCapture
@Spid INT,
@TraceID INT OUTPUT
AS
DECLARE @maxfilesize BIGINT = 5
DECLARE @filepath NVARCHAR(200) = N'C:\trace_' + LEFT(NEWID(),36)

EXEC sp_trace_create @TraceID OUTPUT, 0, @filepath, @maxfilesize, NULL 

exec sp_trace_setevent @TraceID, 122, 1, 1
exec sp_trace_setevent @TraceID, 122, 22, 1
exec sp_trace_setevent @TraceID, 122, 34, 1
exec sp_trace_setevent @TraceID, 122, 51, 1
exec sp_trace_setevent @TraceID, 122, 12, 1
-- filter for spid
EXEC sp_trace_setfilter @TraceID, 12, 0, 0, @Spid
-- start the trace
EXEC sp_trace_setstatus @TraceID, 1

Example StopCapture Definition

CREATE  PROCEDURE StopCapture
@TraceID INT
AS
WITH  XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' as sql), 
      CTE
     as (SELECT CAST(TextData AS VARCHAR(MAX)) AS TextData,
                ObjectID,
                ObjectName,
                EventSequence,
                /*costs accumulate up the tree so the MAX should be the root*/
                MAX(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
         FROM   fn_trace_getinfo(@TraceID) fn
                CROSS APPLY fn_trace_gettable(CAST(value AS NVARCHAR(200)), 1)
                CROSS APPLY (SELECT CAST(TextData AS XML) AS xPlan) x
                CROSS APPLY (SELECT T.relop.value('@EstimatedTotalSubtreeCost',
                                            'float') AS EstimatedTotalSubtreeCost
                             FROM   xPlan.nodes('//sql:RelOp') T(relop)) ca
         WHERE  property = 2
                AND TextData IS NOT NULL
                AND ObjectName not in ( 'StopCapture', 'fn_trace_getinfo' )
         GROUP  BY CAST(TextData AS VARCHAR(MAX)),
                   ObjectID,
                   ObjectName,
                   EventSequence)
SELECT ObjectName,
       SUM(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCost
FROM   CTE
GROUP  BY ObjectID,
          ObjectName  

-- Stop the trace
EXEC sp_trace_setstatus @TraceID, 0
-- Close and delete the trace
EXEC sp_trace_setstatus @TraceID, 2
GO

how to change onclick event with jquery?

@Amirali

console.log(document.getElementById("SAVE_FOOTER"));
document.getElementById("SAVE_FOOTER").attribute("onclick","console.log('c')");

throws:

Uncaught TypeError: document.getElementById(...).attribute is not a function

in chrome.

Element exists and is dumped in console;

What does the "+=" operator do in Java?

devtop += Math.pow(x[i] - mean, 2); adds Math.pow(x[i] - mean, 2) to devtop.

jQuery.active function

For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:

jQuery.ajaxPrefilter(function( options ) {
    options.global = true;
});

Keep in mind that you'll need a timeout on your JSONP request to catch failures.

Angular 1.6.0: "Possibly unhandled rejection" error

I had this same notice appear after making some changes. It turned out to be because I had changed between a single $http request to multiple requests using angularjs $q service.

I hadn't wrapped them in an array. e.g.

$q.all(request1, request2).then(...) 

rather than

$q.all([request1, request2]).then(...)

I hope this might save somebody some time.

What's the difference between “mod” and “remainder”?

Does '%' mean either "mod" or "rem" in C?

In C, % is the remainder1.

..., the result of the / operator is the algebraic quotient with any fractional part discarded ... (This is often called "truncation toward zero".) C11dr §6.5.5 6

The operands of the % operator shall have integer type. C11dr §6.5.5 2

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder ... C11dr §6.5.5 5


What's the difference between “mod” and “remainder”?

C does not define "mod", such as the integer modulus function used in Euclidean division or other modulo. "Euclidean mod" differs from C's a%b operation when a is negative.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1   

Modulo as Euclidean division

 7 modulo  3 -->  1  
 7 modulo -3 -->  1  
-7 modulo  3 -->  2  
-7 modulo -3 -->  2   

Candidate modulo code:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

Note about floating point: double fmod(double x, double y), even though called "fmod", it is not the same as Euclidean division "mod", but similar to C integer remainder:

The fmod functions compute the floating-point remainder of x/y. C11dr §7.12.10.1 2

fmod( 7,  3) -->  1.0  
fmod( 7, -3) -->  1.0  
fmod(-7,  3) --> -1.0  
fmod(-7, -3) --> -1.0   

Disambiguation: C also has a similar named function double modf(double value, double *iptr) which breaks the argument value into integral and fractional parts, each of which has the same type and sign as the argument. This has little to do with the "mod" discussion here except name similarity.


[Edit Dec 2020]

For those who want proper functionality in all cases, an improved modulo_Euclidean() that 1) detects mod(x,0) and 2) a good and no UB result with modulo_Euclidean2(INT_MIN, -1). Inspired by 4 different implementations of modulo with fully defined behavior.

int modulo_Euclidean2(int a, int b) {
  if (b == 0) TBD_Code(); // perhaps return -1 to indicate failure?
  if (b == -1) return 0; // This test needed to prevent UB of `INT_MIN % -1`.
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

1 Prior to C99, C's definition of % was still the remainder from division, yet then / allowed negative quotients to round down rather than "truncation toward zero". See Why do you get different values for integer division in C89?. Thus with some pre-C99 compilation, % code can act just like the Euclidean division "mod". The above modulo_Euclidean() will work with this alternate old-school remainder too.

React: why child component doesn't update when prop changes

You should use setState function. If not, state won't save your change, no matter how you use forceUpdate.

Container {
    handleEvent= () => { // use arrow function
        //this.props.foo.bar = 123
        //You should use setState to set value like this:
        this.setState({foo: {bar: 123}});
    };

    render() {
        return <Child bar={this.state.foo.bar} />
    }
    Child {
        render() {
            return <div>{this.props.bar}</div>
        }
    }
}

Your code seems not valid. I can not test this code.

Shrink a YouTube video to responsive width

See full gist here and live example here.

#hero { width:100%;height:100%;background:url('{$img_ps_dir}cms/how-it-works/hero.jpg') no-repeat top center; }
.videoWrapper { position:relative;padding-bottom:56.25%;padding-top:25px;max-width:100%; }

<div id="hero">
    <div class="container">
        <div class="row-fluid">
            <script src="https://www.youtube.com/iframe_api"></script>
            <center>
            <div class="videoWrapper">
                 <div id="player"></div>
            </div>
            </center>
            <script>
            function onYouTubeIframeAPIReady() { 
                player = new YT.Player('player', {
                   videoId:'xxxxxxxxxxx',playerVars: {  controls:0,autoplay:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,showinfo:0,rel:0,theme:'light' }
                } );
                resizeHeroVideo();
             }
             </script>
        </div>
    </div>
</div>

var player = null;
$( document ).ready(function() {
    resizeHeroVideo();
} );

$(window).resize(function() {
    resizeHeroVideo();
});

function resizeHeroVideo() {
    var content = $('#hero');
    var contentH = viewportSize.getHeight();
    contentH -= 158;
    content.css('height',contentH);

    if(player != null) {
        var iframe = $('.videoWrapper iframe');
        var iframeH = contentH - 150;
        if (isMobile) {
            iframeH = 163; 
        }
        iframe.css('height',iframeH);
        var iframeW = iframeH/9 * 16;
        iframe.css('width',iframeW);
    }
}

resizeHeroVideo is called only after the Youtube player has fully loaded (on page load does not work), and whenever the browser window is resized. When it runs, it calculates the height and width of the iframe and assigns the appropriate values maintaining the correct aspect ratio. This works whether the window is resized horizontally or vertically.

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

GridLayout and Row/Column Span Woe

It feels pretty hacky, but I managed to get the correct look by adding an extra column and row beyond what is needed. Then I filled the extra column with a Space in each row defining a height and filled the extra row with a Space in each col defining a width. For extra flexibility, I imagine these Space sizes could be set in code to provide something similar to weights. I tried to add a screenshot, but I do not have the reputation necessary.

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnCount="9"
android:orientation="horizontal"
android:rowCount="8" >

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill"
    android:layout_rowSpan="2"
    android:text="1" />

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill_horizontal"
    android:text="2" />

<Button
    android:layout_gravity="fill_vertical"
    android:layout_rowSpan="4"
    android:text="3" />

<Button
    android:layout_columnSpan="3"
    android:layout_gravity="fill"
    android:layout_rowSpan="2"
    android:text="4" />

<Button
    android:layout_columnSpan="3"
    android:layout_gravity="fill_horizontal"
    android:text="5" />

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill_horizontal"
    android:text="6" />

<Space
    android:layout_width="36dp"
    android:layout_column="0"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="1"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="2"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="3"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="4"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="5"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="6"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="7"
    android:layout_row="7" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="0" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="1" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="2" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="3" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="4" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="5" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="6" />

</GridLayout>

screenshot

Graphviz's executables are not found (Python 3.4)

I tried setting up Environment variable. Didn't work.I am in Windows environment Combining above methods worked for me :

  1. Downloaded graphviz-2.38.zip from https://graphviz.gitlab.io/_pages/Download/Download_windows.html

  2. Copied the extracted folder into C:\Users\\AppData\Local\Continuum\anaconda3\pkgs\Graphviz2.38

  3. I called the Graphviz location in my code

    Build the classifier

    import sklearn.datasets as datasets
    import pandas as pd
    from sklearn.tree import DecisionTreeClassifier
    iris=datasets.load_iris()
    df=pd.DataFrame(iris.data, columns=iris.feature_names)
    y=iris.target
    
    dtree=DecisionTreeClassifier()
    dtree.fit(df,y)
    

    Build the tree

    from sklearn.externals.six import StringIO  
    from IPython.display import Image  
    from sklearn.tree import export_graphviz
    import pydotplus
    import graphviz
    import os
    os.environ\["PATH"\] += os.pathsep + 'C:/Users/tstusr/AppData/Local/Continuum/anaconda3/pkgs/Graphviz2.38/bin'
    
    dot_data = StringIO()
    export_graphviz(dtree, out_file=dot_data,  
                    filled=True, rounded=True,
                    special_characters=True)
    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())  
    Image(graph.create_png())
    

    Here is how the tree looks:

enter image description here

Eclipse error ... cannot be resolved to a type

Easy Solution:
Go to

Project property -> java builder path -> maven -> find c3p0-0.9.5.2.jar

and see the location where the file is stored in the local repository and go to this location and delete the repository manually.

G

How to find common elements from multiple vectors?

A good answer already, but there are a couple of other ways to do this:

unique(c[c%in%a[a%in%b]])

or,

tst <- c(unique(a),unique(b),unique(c))
tst <- tst[duplicated(tst)]
tst[duplicated(tst)]

You can obviously omit the unique calls if you know that there are no repeated values within a, b or c.

CSS background-size: cover replacement for Mobile Safari

@media (max-width: @iphone-screen) {
  background-attachment:inherit;    
  background-size:cover;
  -webkit-background-size:cover;
}

Get type of a generic parameter in Java with reflection

Because of type erasure the only way to know the type of the list would be to pass in the type as a parameter to the method:

public class Main {

    public static void main(String[] args) {
        doStuff(new LinkedList<String>(), String.class);

    }

    public static <E> void doStuff(List<E> list, Class<E> clazz) {

    }

}

How to use SQL Select statement with IF EXISTS sub query?

SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;

Parsing domain from a URL

If you want extract host from string http://google.com/dhasjkdas/sadsdds/sdda/sdads.html, usage of parse_url() is acceptable solution for you.

But if you want extract domain or its parts, you need package that using Public Suffix List. Yes, you can use string functions arround parse_url(), but it will produce incorrect results sometimes.

I recomend TLDExtract for domain parsing, here is sample code that show diff:

$extract = new LayerShifter\TLDExtract\Extract();

# For 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'

$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';

parse_url($url, PHP_URL_HOST); // will return google.com

$result = $extract->parse($url);
$result->getFullHost(); // will return 'google.com'
$result->getRegistrableDomain(); // will return 'google.com'
$result->getSuffix(); // will return 'com'

# For 'http://search.google.com/dhasjkdas/sadsdds/sdda/sdads.html'

$url = 'http://search.google.com/dhasjkdas/sadsdds/sdda/sdads.html';

parse_url($url, PHP_URL_HOST); // will return 'search.google.com'

$result = $extract->parse($url);
$result->getFullHost(); // will return 'search.google.com'
$result->getRegistrableDomain(); // will return 'google.com'

How to label each equation in align environment?

You can label each line separately, in your case:

\begin{align}
  \lambda_i + \mu_i = 0 \label{eq:1}\\
  \mu_i \xi_i = 0 \label{eq:2}\\
  \lambda_i [y_i( w^T x_i + b) - 1 + \xi_i] = 0 \label{eq:3}
\end{align} 

Note that this only works for AMS environments that are designed for multiple equations (as opposed to multiline single equations).

Finding rows that don't contain numeric data in Oracle

After doing some testing, i came up with this solution, let me know in case it helps.

Add this below 2 conditions in your query and it will find the records which don't contain numeric data

 and REGEXP_LIKE(<column_name>, '\D') -- this selects non numeric data
 and not REGEXP_LIKE(column_name,'^[-]{1}\d{1}') -- this filters out negative(-) values

Check if the number is integer

Here's a solution using simpler functions and no hacks:

all.equal(a, as.integer(a))

What's more, you can test a whole vector at once, if you wish. Here's a function:

testInteger <- function(x){
  test <- all.equal(x, as.integer(x), check.attributes = FALSE)
  if(test == TRUE){ return(TRUE) }
  else { return(FALSE) }
}

You can change it to use *apply in the case of vectors, matrices, etc.

Permissions for /var/www/html

log in as root user:

sudo su

password:

then go and do what you want to do in var/www

Java - sending HTTP parameters via POST method easily

I had the same issue. I wanted to send data via POST. I used the following code:

    URL url = new URL("http://example.com/getval.php");
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("param1", param1);
    params.put("param2", param2);

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    String urlParameters = postData.toString();
    URLConnection conn = url.openConnection();

    conn.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(urlParameters);
    writer.flush();

    String result = "";
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    while ((line = reader.readLine()) != null) {
        result += line;
    }
    writer.close();
    reader.close()
    System.out.println(result);

I used Jsoup for parse:

    Document doc = Jsoup.parseBodyFragment(value);
    Iterator<Element> opts = doc.select("option").iterator();
    for (;opts.hasNext();) {
        Element item = opts.next();
        if (item.hasAttr("value")) {
            System.out.println(item.attr("value"));
        }
    }

How to get the selected date of a MonthCalendar control in C#

For those who are still trying, this link helped me out, too; it just puts it all together:

http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx

private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);

//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;

//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}

What is the difference between concurrent programming and parallel programming?

Concurrency and Parallelism Source

In a multithreaded process on a single processor, the processor can switch execution resources between threads, resulting in concurrent execution.

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run on a separate processor at the same time, resulting in parallel execution.

When the process has fewer or as many threads as there are processors, the threads support system in conjunction with the operating environment ensure that each thread runs on a different processor.

For example, in a matrix multiplication that has the same number of threads and processors, each thread (and each processor) computes a row of the result.

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

XPath with multiple conditions

Here, we can do this way as well:

//category [@name='category name']/author[contains(text(),'authorname')]

OR

//category [@name='category name']//author[contains(text(),'authorname')]

To Learn XPATH in detail please visit- selenium xpath in detail

How do I fix "Expected to return a value at the end of arrow function" warning?

The warning indicates that you're not returning something at the end of your map arrow function in every case.

A better approach to what you're trying to accomplish is first using a .filter and then a .map, like this:

this.props.comments
  .filter(commentReply => commentReply.replyTo === comment.id)
  .map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);

How can I get the Google cache age of any URL or web page?

You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website

Why does Maven have such a bad rep?

My take here, based on the pitfalls of convention over configuration:

http://chriswongdevblog.blogspot.com/2011/01/trouble-with-being-conventional.html

My issue with Maven is the difficulty in discovery and limitless complexity. That, and watching colleagues waste half a work day day fighting Maven build issues. Also IMHO, the Maven integration with Eclipse makes things worse, because you have multiplied the number of places where things go wrong.

Add event handler for body.onload by javascript within <body> part

Simply wrap the code you want to execute into the onload event of the window object:

window.onload = function(){ 
   // your code here
}

Spark Kill Running Application

  • copy past the application Id from the spark scheduler, for instance application_1428487296152_25597
  • connect to the server that have launch the job
  • yarn application -kill application_1428487296152_25597

Using Mockito with multiple calls to the same method with the same arguments

You can use a LinkedList and an Answer. Eg

MyService mock = mock(MyService.class);
LinkedList<String> results = new LinkedList<>(List.of("A", "B", "C"));
when(mock.doSomething(any())).thenAnswer(invocation -> results.removeFirst());

How to cin Space in c++?

I have the same problem and I just used cin.getline(input,300);.

noskipws and cin.get() sometimes are not easy to use. Since you have the right size of your array try using cin.getline() which does not care about any character and read the whole line in specified character count.

Swift Bridging Header import issue

I experienced that kind of error, when I was adding a Today Extension to my app. The build target for the extension was generated with the same name of bridging header as my app's build target. This was leading to the error, because the extension does not see the files listed in the bridging header of my app.

The only thing You need to to is delete or change the name of the bridging header for the extension and all will be fine.

Hope that this will help.

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

How to make type="number" to positive numbers only

Try this:

Yii2 : Validation rule 

    public function rules() {
    return [
['location_id', 'compare', 'compareValue' => 0', 'operator' => '>'],
        ];
}

Howto? Parameters and LIKE statement SQL

try also this way

Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE CONCAT('%',@query,'%')  OR  title LIKE CONCAT('%',@query,'%') )")
cmd.Parameters.Add("@query", searchString)
cmd.ExecuteNonQuery()

Used Concat instead of +