Programs & Examples On #Pathing

Fixing npm path in Windows 8 and 10

Go to control panel -> System -> Advanced System Settings then environment variables.

From here find the path variable, Go to the end of the line and paste "C:\Program Files\nodejs\node_modules\npm\bin" (change the path to the directory to where ever you installed it e.g. if you specifically installed it anywhere change it)

PHP header(Location: ...): Force URL change in address bar

you may want to put a break; after your location:

header("HTTP/1.1 301 Moved Permanently");
header('Location:  '.  $YourArrayName["YourURL"]  );
break;

When do you use Java's @Override annotation and why?

If you find yourself overriding (non-abstract) methods very often, you probably want to take a look at your design. It is very useful when the compiler would not otherwise catch the error. For instance trying to override initValue() in ThreadLocal, which I have done.

Using @Override when implementing interface methods (1.6+ feature) seems a bit overkill for me. If you have loads of methods some of which override and some don't, that probably bad design again (and your editor will probably show which is which if you don't know).

How do I change UIView Size?

Assigning questionFrame.frame.size.height= screenSize.height * 0.30 will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.

questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)

Unable to install boto3

I had a similar problem, but the accepted answer did not resolve it - I was not using a virtual environment. This is what I had to do:

sudo python -m pip install boto3

I do not know why this behaved differently from sudo pip install boto3.

How do I kill a VMware virtual machine that won't die?

Similar, but using WMIC command line to obtain the process ID and path:

WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid

This will create a text file with each process and its parameters. You can search in the file for your VM File Path, and get the correct Process ID to end task with.

Thanks to http://windowsxp.mvps.org/listproc.htm for the correct command line parameters.

"break;" out of "if" statement?

I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if inside. So, I'll try to answer this question with this particular interpretation.

If you have if inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if or was it ended "naturally"? So, your sample code can be modified in this way:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; break;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

The problem with this code is that the if statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break statement) variant will be:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; continue;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.

UPDATE:

Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break to exit from both loops and switch.

Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.

Modifying a query string without reloading the page

I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.

function insertUrlParam(key, value) {
    if (history.pushState) {
        let searchParams = new URLSearchParams(window.location.search);
        searchParams.set(key, value);
        let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
        window.history.pushState({path: newurl}, '', newurl);
    }
}

What is the "continue" keyword and how does it work in Java?

Let's see an example:

int sum = 0;
for(int i = 1; i <= 100 ; i++){
    if(i % 2 == 0)
         continue;
    sum += i;
}

This would get the sum of only odd numbers from 1 to 100.

Add context path to Spring Boot application

In Spring Boot 1.5:

Add the following property in application.properties:

server.context-path=/demo

Note: /demo is your context path URL.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Try to change this: <csrf /> to this : <csrf disabled="true"/>. It should disable csfr.

How to validate phone number using PHP?

Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.

php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.

An example

$phone = '000-0000-0000';

if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
  // $phone is valid
}

How to call a method after bean initialization is complete?

You can use something like:

<beans>
    <bean id="myBean" class="..." init-method="init"/>
</beans>

This will call the "init" method when the bean is instantiated.

How to add a hook to the application context initialization event?

Spring has some standard events which you can handle.

To do that, you must create and register a bean that implements the ApplicationListener interface, something like this:

package test.pack.age;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class ApplicationListenerBean implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
            // now you can do applicationContext.getBean(...)
            // ...
        }
    }
}

You then register this bean within your servlet.xml or applicationContext.xml file:

<bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />

and Spring will notify it when the application context is initialized.

In Spring 3 (if you are using this version), the ApplicationListener class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:

public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        // now you can do applicationContext.getBean(...)
        // ...
    }
}

Find all matches in workbook using Excel VBA

Using the Range.Find method, as pointed out above, along with a loop for each worksheet in the workbook, is the fastest way to do this. The following, for example, locates the string "Question?" in each worksheet and replaces it with the string "Answered!".

Sub FindAndExecute()

Dim Sh As Worksheet
Dim Loc As Range

For Each Sh In ThisWorkbook.Worksheets
    With Sh.UsedRange
        Set Loc = .Cells.Find(What:="Question?")
        If Not Loc Is Nothing Then
            Do Until Loc Is Nothing
                Loc.Value = "Answered!"
                Set Loc = .FindNext(Loc)
            Loop
        End If
    End With
    Set Loc = Nothing
Next

End Sub

if-else statement inside jsx: ReactJS

What about switch case instead of if-else

  render() {
    switch (this.state.route) {
      case 'loginRoute':
        return (
            <Login changeRoute={this.changeRoute}
              changeName={this.changeName}
              changeRole={this.changeRole} />
        );
      case 'adminRoute':
        return (
            <DashboardAdmin
              role={this.state.role}
              name={this.state.name}
              changeRoute={this.changeRoute}
            />
        );
      default: 
        return <></>;
    }

Rotate and translate

There is no need for that, as you can use css 'writing-mode' with values 'vertical-lr' or 'vertical-rl' as desired.

.item {
  writing-mode: vertical-rl;
}

CSS:writing-mode

css h1 - only as wide as the text

You could use a <span> instead of an <h1>.

CSS :selected pseudo class similar to :checked, but for <select> elements

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

_x000D_
_x000D_
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
  background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Works on gecko/webkit.

Program to find prime numbers

People have mentioned a couple of the building blocks toward doing this efficiently, but nobody's really put the pieces together. The sieve of Eratosthenes is a good start, but with it you'll run out of memory long before you reach the limit you've set. That doesn't mean it's useless though -- when you're doing your loop, what you really care about are prime divisors. As such, you can start by using the sieve to create a base of prime divisors, then use those in the loop to test numbers for primacy.

When you write the loop, however, you really do NOT want to us sqrt(i) in the loop condition as a couple of answers have suggested. You and I know that the sqrt is a "pure" function that always gives the same answer if given the same input parameter. Unfortunately, the compiler does NOT know that, so if use something like '<=Math.sqrt(x)' in the loop condition, it'll re-compute the sqrt of the number every iteration of the loop.

You can avoid that a couple of different ways. You can either pre-compute the sqrt before the loop, and use the pre-computed value in the loop condition, or you can work in the other direction, and change i<Math.sqrt(x) to i*i<x. Personally, I'd pre-compute the square root though -- I think it's clearer and probably a bit faster--but that depends on the number of iterations of the loop (the i*i means it's still doing a multiplication in the loop). With only a few iterations, i*i will typically be faster. With enough iterations, the loss from i*i every iteration outweighs the time for executing sqrt once outside the loop.

That's probably adequate for the size of numbers you're dealing with -- a 15 digit limit means the square root is 7 or 8 digits, which fits in a pretty reasonable amount of memory. On the other hand, if you want to deal with numbers in this range a lot, you might want to look at some of the more sophisticated prime-checking algorithms, such as Pollard's or Brent's algorithms. These are more complex (to put it mildly) but a lot faster for large numbers.

There are other algorithms for even bigger numbers (quadratic sieve, general number field sieve) but we won't get into them for the moment -- they're a lot more complex, and really only useful for dealing with really big numbers (the GNFS starts to be useful in the 100+ digit range).

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

How can I catch a ctrl-c event?

For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.

See here for an example.

How to use SortedMap interface in Java?

A TreeMap is probably the most straightforward way of doing this. You use it exactly like a normal Map. i.e.

Map<Float,String> mySortedMap = new TreeMap<Float,MyObject>();
// Put some values in it
mySortedMap.put(1.0f,"One");
mySortedMap.put(0.0f,"Zero");
mySortedMap.put(3.0f,"Three");

// Iterate through it and it'll be in order!
for(Map.Entry<Float,String> entry : mySortedMap.entrySet()) {
    System.out.println(entry.getValue());
} // outputs Zero One Three 

It's worth taking a look at the API docs, http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html to see what else you can do with it.

Pretty graphs and charts in Python

You didn't mention what output format you need but reportlab is good at creating charts both in pdf and bitmap (e.g. png) format.

Here is a simple example of a barchart in png and pdf format:

from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart

d = Drawing(300, 200)

chart = VerticalBarChart()
chart.width = 260
chart.height = 160
chart.x = 20
chart.y = 20
chart.data = [[1,2], [3,4]]
chart.categoryAxis.categoryNames = ['foo', 'bar']
chart.valueAxis.valueMin = 0

d.add(chart)
d.save(fnRoot='test', formats=['png', 'pdf'])

alt text http://i40.tinypic.com/2j677tl.jpg

Note: the image has been converted to jpg by the image host.

what is the multicast doing on 224.0.0.251?

I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone

How to convert 2D float numpy array to 2D int numpy array?

Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.

>>> x = np.array([[1.0,2.3],[1.3,2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> y = np.trunc(x)
>>> y
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> z = np.ceil(x)
>>> z
array([[ 1.,  3.],
       [ 2.,  3.]])
>>> t = np.floor(x)
>>> t
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> a = np.rint(x)
>>> a
array([[ 1.,  2.],
       [ 1.,  3.]])

To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):

a.astype(int)
array([[1, 2],
       [1, 3]])

>>> y.astype(int)
array([[1, 2],
       [1, 2]])

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

You could try this registry hack:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000

If it works, just keep increasing the KeepAliveTime. It is currently set for 2 minutes.

Can I find events bound on an element with jQuery?

Note that events may be attached to the document itself rather than the element in question. In that case, you'll want to use:

$._data( $(document)[0], "events" );

And find the event with the correct selector:

enter image description here

And then look at the handler > [[FunctionLocation]]

enter image description here

How to show x and y axes in a MATLAB graph?

@Martijn your order of function calls is slightly off. Try this instead:

x=-3:0.1:3;
y = x.^3;
plot(x,y), hold on
plot([-3 3], [0 0], 'k:')
hold off

Get the contents of a table row with a button click

Find element with id in row using jquery

$(document).ready(function () {
$("button").click(function() {
    //find content of different elements inside a row.
    var nameTxt = $(this).closest('tr').find('.name').text();
    var emailTxt = $(this).closest('tr').find('.email').text();
    //assign above variables text1,text2 values to other elements.
    $("#name").val( nameTxt );
    $("#email").val( emailTxt );
    });
});

Force GUI update from UI Thread

I've just stumbled over the same problem and found some interesting information and I wanted to put in my two cents and add it here.

First of all, as others have already mentioned, long-running operations should be done by a thread, which can be a background worker, an explicit thread, a thread from the threadpool or (since .Net 4.0) a task: Stackoverflow 570537: update-label-while-processing-in-windows-forms, so that the UI keeps responsive.

But for short tasks there is no real need for threading although it doesn't hurt of course.

I have created a winform with one button and one label to analyze this problem:

System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
  label1->Text = "Start 1";
  label1->Update();
  System::Threading::Thread::Sleep(5000); // do other work
}

My analysis was stepping over the code (using F10) and seeing what happened. And after reading this article Multithreading in WinForms I have found something interesting. The article says at the bottom of the first page, that the UI thread can not repaint the UI until the currently executed function finishes and the window is marked by Windows as "not responding" instead after a while. I have also noticed that on my test application from above while stepping through it, but only in certain cases.

(For the following test it is important to not have Visual Studio set to fullscreen, you must be able to see your little application window at the same time next to it, You must not have to switch between the Visual Studio window for debugging and your application window to see what happens. Start the application, set a breakpoint at label1->Text ..., put the application window beside the VS window and place the mouse cursor over the VS window.)

  1. When I click once on VS after app start (to put the focues there and enable stepping) and step through it WITHOUT moving the mouse, the new text is set and the label is updated in the update() function. This means, the UI is repainted obviously.

  2. When I step over the first line, then move the mouse around a lot and click somewhere, then step further, the new text is likely set and the update() function is called, but the UI is not updated/repainted and the old text remains there until the button1_click() function finishes. Instead of repainting, the window is marked as "not responsive"! It also doesn't help to add this->Update(); to update the whole form.

  3. Adding Application::DoEvents(); gives the UI a chance to update/repaint. Anyway you have to take care that the user can not press buttons or perform other operations on the UI that are not permitted!! Therefore: Try to avoid DoEvents()!, better use threading (which I think is quite simple in .Net).
    But (@Jagd, Apr 2 '10 at 19:25) you can omit .refresh() and .invalidate().

My explanations is as following: AFAIK winform still uses the WINAPI function. Also MSDN article about System.Windows.Forms Control.Update method refers to WINAPI function WM_PAINT. The MSDN article about WM_PAINT states in its first sentence that the WM_PAINT command is only sent by the system when the message queue is empty. But as the message queue is already filled in the 2nd case, it is not send and thus the label and the application form are not repainted.

<>joke> Conclusion: so you just have to keep the user from using the mouse ;-) <>/joke>

How do I sort a dictionary by value?

Starting from Python 3.6, dict objects are now ordered by insertion order. It's officially in the specs of Python 3.7.

>>> words = {"python": 2, "blah": 4, "alice": 3}
>>> dict(sorted(words.items(), key=lambda x: x[1]))
{'python': 2, 'alice': 3, 'blah': 4}

Before that, you had to use OrderedDict.

Python 3.7 documentation says:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.

Android difference between Two Dates

When you use Date() to calculate the difference in hours is necessary configure the SimpleDateFormat() in UTC otherwise you get one hour error due to Daylight SavingTime.

C# Form.Close vs Form.Dispose

This forum on MSDN tells you.

Form.Close() sends the proper Windows messages to shut down the win32 window. During that process, if the form was not shown modally, Dispose is called on the form. Disposing the form frees up the unmanaged resources that the form is holding onto.

If you do a form1.Show() or Application.Run(new Form1()), Dispose will be called when Close() is called.

However, if you do form1.ShowDialog() to show the form modally, the form will not be disposed, and you'll need to call form1.Dispose() yourself. I believe this is the only time you should worry about disposing the form yourself.

$(form).ajaxSubmit is not a function

I'm guessing you don't have a jquery form plugin included. ajaxSubmit isn't a core jquery function, I believe.

Something like this : http://jquery.malsup.com/form/

UPD

<script src="http://malsup.github.com/jquery.form.js"></script> 

Automatic creation date for Django model form objects?

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

Is there a way to ignore a single FindBugs warning?

As others Mentioned, you can use the @SuppressFBWarnings Annotation. If you don't want or can't add another Dependency to your code, you can add the Annotation to your Code yourself, Findbugs dosn't care in which Package the Annotation is.

@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
    /**
     * The set of FindBugs warnings that are to be suppressed in
     * annotated element. The value can be a bug category, kind or pattern.
     *
     */
    String[] value() default {};

    /**
     * Optional documentation of the reason why the warning is suppressed
     */
    String justification() default "";
}

Source: https://sourceforge.net/p/findbugs/feature-requests/298/#5e88

Reading CSV files using C#

I recommend CsvHelper from Nuget.

PS: Regarding other more upvoted answers, I'm sorry but adding a reference to Microsoft.VisualBasic is:

  • Ugly
  • Not cross-platform, because it's not available in .NETCore/.NET5 (and Mono never had very good support of Visual Basic, so it may be buggy).

What is an Android PendingIntent?

In an easy language,
1. A description of an Intent and Target action to perform. First you have to create an intent and then you have to pass an specific java class which you want to execute, to the Intent.
2. You can call those java class which is your class action class by PendingIntent.getActivity, PendingIntent.getActivities(Context, int, Intent[], int), PendingIntent.getBroadcast(Context, int, Intent, int), and PendingIntent.getService(Context, int, Intent, int); Here you see that Intent which is comes from the step 1
3. You should keep in mind that...By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified.

That is what I learned after a long reading.

Number of occurrences of a character in a string

Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.

string test = "key1=value1&key2=value2&key3=value3";

var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
                     .Cast<Match>()
                     .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

var count = keyValues.Count - 1;

Running Groovy script from the command line

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

Instant run in Android Studio 2.0 (how to turn off)

I tried all above but nothing helps, at last i just figured out that under setting >> apps, device still has an entry for uninstalled application as disabled, i just uninstalled from there and it starts working.

:) might be useful for someone

How to read the post request parameters using JavaScript

POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.

How to throw a C++ exception

Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:

Use std::nested_exception and std::throw_with_nested

It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

generate a random number between 1 and 10 in c

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid()) (_getpid() on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random (Linux) or CryptGenRandom() (Windows), or from a service like random.org.

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

I am using mysql and below syntax worked well for me,

ALTER TABLE table_name MODIFY col_name VARCHAR(12);

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

If you want the editor to work with git operations, setting the $EDITOR environment variable may not be enough, at least not in the case of Sublime - e.g. if you want to rebase, it will just say that the rebase was successful, but you won't have a chance to edit the file in any way, git will just close it straight away:

git rebase -i HEAD~
Successfully rebased and updated refs/heads/master.

If you want Sublime to work correctly with git, you should configure it using:

git config --global core.editor "sublime -n -w"

I came here looking for this and found the solution in this gist on github.

Bootstrap 4 responsive tables won't take up 100% width

None of these answers are working (date today 9th Dec 2018). The correct resolution here is to add .table-responsive-sm to your table:

<table class='table table-responsive-sm'>
[Your table]
</table>

This applies the responsiveness aspect only to the SM view (mobile). So in mobile view you get the scrolling as desired and in larger views the table is not responsive and thus displayed full width, as desired.

Docs: https://getbootstrap.com/docs/4.0/content/tables/#breakpoint-specific

SQL left join vs multiple tables on FROM line?

Basically, when your FROM clause lists tables like so:

SELECT * FROM
  tableA, tableB, tableC

the result is a cross product of all the rows in tables A, B, C. Then you apply the restriction WHERE tableA.id = tableB.a_id which will throw away a huge number of rows, then further ... AND tableB.id = tableC.b_id and you should then get only those rows you are really interested in.

DBMSs know how to optimise this SQL so that the performance difference to writing this using JOINs is negligible (if any). Using the JOIN notation makes the SQL statement more readable (IMHO, not using joins turns the statement into a mess). Using the cross product, you need to provide join criteria in the WHERE clause, and that's the problem with the notation. You are crowding your WHERE clause with stuff like

    tableA.id = tableB.a_id 
AND tableB.id = tableC.b_id 

which is only used to restrict the cross product. WHERE clause should only contain RESTRICTIONS to the resultset. If you mix table join criteria with resultset restrictions, you (and others) will find your query harder to read. You should definitely use JOINs and keep the FROM clause a FROM clause, and the WHERE clause a WHERE clause.

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

select data up to a space?

select left(col, charindex(' ', col) - 1)

Accessing a local website from another computer inside the local network in IIS 7

Add two bindings to your website, one for local access and another for LAN access like so:

Open IIS and select your local website (that you want to access from your local network) from the left panel:

Connections > server (user-pc) > sites > local site

Open Bindings on the right panel under Actions tab add these bindings:

  1. Local:

    Type: http
    Ip Address: All Unassigned
    Port: 80
    Host name: samplesite.local
    
  2. LAN:

    Type: http
    Ip Address: <Network address of the hosting machine ex. 192.168.0.10>
    Port: 80
    Host name: <Leave it blank>
    

Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.

NOTE:

if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):

192.168.0.10 samplesite.local

Error: unmappable character for encoding UTF8 during maven compilation

I came across this problem just now and ended up resolving it like so: I opened up the offending .java file in Notepad++ and from the Encoding menu I selected "Convert to UTF-8 without BOM". Saved. Re-ran maven, all went through ok.

If the offending resource was not encoded in UTF-8 - as you have configured for your maven compiler plugin - you would see in the Encoding menu of Np++ a bullet mark next to the file's current encoding (in my case I saw it was set to "Encode in ANSI").

So your maven compiler plugin invoked the Java compiler with the -encoding option set to UTF-8, but the compiler encountered a ANSI-encoded source file and reported this as an error. This used to be a warning previously in Java 5 but is treated as an error in Java 6+

How to make Bitmap compress without change the bitmap size?

Are you sure it is smaller?

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

Gives

12-07 17:43:36.333: E/Original   dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768

Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

12-07 17:43:38.733: E/Dimensions(278): 768 576

Can you style an html radio button to look like a checkbox?

So I have been lurking on stack for so many years. This is actually my first time posting on here.

Anyhow, this might seem insane but I came across this post while struggling with the same issue and came up with a dirty solution. I know there are more elegant ways to perhaps set this as a property value but:

if you look at lines 12880-12883 in tcpdf.php :

$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][`110`])) / 2) * $this->k);
$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
$popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`110`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`111`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);

and lines 13135-13138 :

$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][`108`])) / 2) * $this->k);
$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
$popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`108`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`109`).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);

Those widgets are rendered from the zapfdingbats font set... just swap the character codes and voila... checks are radios and/or vice versa. This also opens up ideas to make a custom font set to use here and add some nice styling to your form elements.

Anyhow, just figured I would offer my two cents ... it worked awesome for me.

Changing minDate and maxDate on the fly using jQuery DatePicker

You have a couple of options...

1) You need to call the destroy() method not remove() so...

$('#date').datepicker('destroy');

Then call your method to recreate the datepicker object.

2) You can update the property of the existing object via

$('#date').datepicker('option', 'minDate', new Date(startDate));
$('#date').datepicker('option', 'maxDate', new Date(endDate));

or...

$('#date').datepicker('option', { minDate: new Date(startDate),
                                  maxDate: new Date(endDate) });

Column count doesn't match value count at row 1

  1. you missed the comma between two values or column name
  2. you put extra values or an extra column name

Sort & uniq in Linux shell

sort -u will be slightly faster, because it does not need to pipe the output between two commands

also see my question on the topic: calling uniq and sort in different orders in shell

Using WGET to run a cronjob PHP

You could tell wget to not download the contents in a couple of different ways:

wget --spider http://www.example.com/cronit.php

which will just perform a HEAD request but probably do what you want

wget -O /dev/null http://www.example.com/cronit.php

which will save the output to /dev/null (a black hole)

You might want to look at wget's -q switch too which prevents it from creating output

I think that the best option would probably be:

wget -q --spider http://www.example.com/cronit.php

that's unless you have some special logic checking the HTTP method used to request the page

Examples of GoF Design Patterns in Java's core libraries

You can find an overview of a lot of design patterns in Wikipedia. It also mentions which patterns are mentioned by GoF. I'll sum them up here and try to assign as many pattern implementations as possible, found in both the Java SE and Java EE APIs.


Creational patterns

Abstract factory (recognizeable by creational methods returning the factory itself which in turn can be used to create another abstract/interface type)

Builder (recognizeable by creational methods returning the instance itself)

Factory method (recognizeable by creational methods returning an implementation of an abstract/interface type)

Prototype (recognizeable by creational methods returning a different instance of itself with the same properties)

Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)


Structural patterns

Adapter (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own/another abstract/interface type which decorates/overrides the given instance)

Bridge (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own abstract/interface type which delegates/uses the given instance)

  • None comes to mind yet. A fictive example would be new LinkedHashMap(LinkedHashSet<K>, List<V>) which returns an unmodifiable linked map which doesn't clone the items, but uses them. The java.util.Collections#newSetFromMap() and singletonXXX() methods however comes close.

Composite (recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure)

Decorator (recognizeable by creational methods taking an instance of same abstract/interface type which adds additional behaviour)

Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)

Flyweight (recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)

Proxy (recognizeable by creational methods which returns an implementation of given abstract/interface type which in turn delegates/uses a different implementation of given abstract/interface type)


Behavioral patterns

Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method in another implementation of same abstract/interface type in a queue)

Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)

Interpreter (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)

Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue)

Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)

Memento (recognizeable by behavioral methods which internally changes the state of the whole instance)

Observer (or Publish/Subscribe) (recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)

State (recognizeable by behavioral methods which changes its behaviour depending on the instance's state which can be controlled externally)

Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)

Template method (recognizeable by behavioral methods which already have a "default" behaviour defined by an abstract type)

Visitor (recognizeable by two different abstract/interface types which has methods defined which takes each the other abstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)

Why are Python's 'private' methods not actually private?

The phrase commonly used is "we're all consenting adults here". By prepending a single underscore (don't expose) or double underscore (hide), you're telling the user of your class that you intend the member to be 'private' in some way. However, you're trusting everyone else to behave responsibly and respect that, unless they have a compelling reason not to (e.g. debuggers, code completion).

If you truly must have something that is private, then you can implement it in an extension (e.g. in C for CPython). In most cases, however, you simply learn the Pythonic way of doing things.

All possible array initialization syntaxes

These are the current declaration and initialization methods for a simple array.

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2

Note that other techniques of obtaining arrays exist, such as the Linq ToArray() extensions on IEnumerable<T>.

Also note that in the declarations above, the first two could replace the string[] on the left with var (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. So if you're into the whole brevity thing, the above could be written as

var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2 

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

how to update the multiple rows at a time using linq to sql?

To update one column here are some syntax options:

Option 1

var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>a.status=true);
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
     db.SomeTable
       .Where(x=>ls.Contains(x.friendid))
       .ToList()
       .ForEach(a=>a.status=true);

     db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
    }
    db.SubmitChanges();
}

Update

As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status at ones. We want to update name and status where the friendid is matching. Here are some syntax options for that:

Option 1

var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
    db.SomeTable
        .Where(x=>ls.Contains(x.friendid))
        .ToList()
        .ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
        some.name=name;
    }
    db.SubmitChanges();
}

Update 2

In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:

db.SubmitChanges();

But for Entity Framework to commit the changes it is:

db.SaveChanges()

What's the difference between echo, print, and print_r in PHP?

The difference between echo, print, print_r and var_dump is very simple.

echo

echo is actually not a function but a language construct which is used to print output. It is marginally faster than the print.

echo "Hello World";    // this will print Hello World
echo "Hello ","World"; // Multiple arguments - this will print Hello World

$var_1=55;
echo "$var_1";               // this will print 55
echo "var_1=".$var_1;        // this will print var_1=55
echo 45+$var_1;              // this will print 100

$var_2="PHP";
echo "$var_2";                   // this will print PHP

$var_3=array(99,98,97)           // Arrays are not possible with echo (loop or index  value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with echo (loop or index  value required)

You can also use echo statement with or without parenthese

echo ("Hello World");   // this will print Hello World

print

Just like echo construct print is also a language construct and not a real function. The differences between echo and print is that print only accepts a single argument and print always returns 1. Whereas echo has no return value. So print statement can be used in expressions.

print "Hello World";    // this will print Hello World
print "Hello ","World"; // Multiple arguments - NOT POSSIBLE with print
$var_1=55;
print "$var_1";               // this will print 55
print "var_1=".$var_1;        // this will print var_1=55
print 45+$var_1;              // this will print 100

$var_2="PHP";
print "$var_2";                   // this will print PHP

$var_3=array(99,98,97)           // Arrays are not possible with print (loop or index  value required)
$var_4=array("P"=>"3","J"=>"4"); // Arrays are not possible with print (loop or index  value required)

Just like echo, print can be used with or without parentheses.

print ("Hello World");   // this will print Hello World

print_r

The print_r() function is used to print human-readable information about a variable. If the argument is an array, print_r() function prints its keys and elements (same for objects).

print_r ("Hello World");    // this will print Hello World

$var_1=55;
print_r ("$var_1");               // this will print 55
print_r ("var_1=".$var_1);        // this will print var_1=55
print_r (45+$var_1);              // this will print 100

$var_2="PHP";
print_r ("$var_2");                // this will print PHP

$var_3=array(99,98,97)             // this will print Array ( [0] => 1 [1] => 2 [2] => 3 ) 
$var_4=array("P"=>"3","J"=>"4");   // this will print  Array ( [P] => 3 [J] => 4 ) 

var_dump

var_dump function usually used for debugging and prints the information ( type and value) about a variable/array/object.

var_dump($var_1);     // this will print  int(5444) 
var_dump($var_2);     // this will print  string(5) "Hello" 
var_dump($var_3);     // this will print  array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } 
var_dump($var_4);     // this will print  array(2) { ["P"]=> string(1) "3" ["J"]=> string(1) "4" }

jQuery - Appending a div to body, the body is the object?

    $('body').append($('<div/>', {
        id: 'holdy' 
    }));

Get UserDetails object from Security Context in Spring MVC controller

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

    ModelAndView mv = new ModelAndView("index");

    String userName = "not logged in"; // Any default user  name
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        userName = principal.getName();
    }

    mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

    return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

Calculating how many minutes there are between two times

Try this

DateTime startTime = varValue
DateTime endTime = varTime

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );

Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.

What is the difference between call and apply?

Call and apply both are used to force the this value when a function is executed. The only difference is that call takes n+1 arguments where 1 is this and 'n' arguments. apply takes only two arguments, one is this the other is argument array.

The advantage I see in apply over call is that we can easily delegate a function call to other function without much effort;

function sayHello() {
  console.log(this, arguments);
}

function hello() {
  sayHello.apply(this, arguments);
}

var obj = {name: 'my name'}
hello.call(obj, 'some', 'arguments');

Observe how easily we delegated hello to sayHello using apply, but with call this is very difficult to achieve.

How do I handle the window close event in Tkinter?

Matt has shown one classic modification of the close button.
The other is to have the close button minimize the window.
You can reproduced this behavior by having the iconify method
be the protocol method's second argument.

Here's a working example, tested on Windows 7 & 10:

# Python 3
import tkinter
import tkinter.scrolledtext as scrolledtext

root = tkinter.Tk()
# make the top right close button minimize (iconify) the main window
root.protocol("WM_DELETE_WINDOW", root.iconify)
# make Esc exit the program
root.bind('<Escape>', lambda e: root.destroy())

# create a menu bar with an Exit command
menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)

# create a Text widget with a Scrollbar attached
txt = scrolledtext.ScrolledText(root, undo=True)
txt['font'] = ('consolas', '12')
txt.pack(expand=True, fill='both')

root.mainloop()

In this example we give the user two new exit options:
the classic File ? Exit, and also the Esc button.

Get max and min value from array in JavaScript

if you have "scattered" (not inside an array) values you can use:

var max_value = Math.max(val1, val2, val3, val4, val5);

How to return JSON with ASP.NET & jQuery

Try to use this , it works perfectly for me

  // 

   varb = new List<object>();

 // Example 

   varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});

 // JSON  + Serializ

public string Json()
        {  
            return (new JavaScriptSerializer()).Serialize(varb);
        }


//  Jquery SIDE 

  var datasets = {
            "Products": {
                label: "Products",
                data: <%= getJson() %> 
            }

How can I exclude all "permission denied" messages from "find"?

I had to use:

find / -name expect 2>/dev/null

specifying the name of what I wanted to find and then telling it to redirect all errors to /dev/null

expect being the location of the expect program I was searching for.

Creating your own header file in C

header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.

client.h

#ifndef CLIENT_H
#define CLIENT_H

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);


#endif /** CLIENT_H */

Then you'd implement the .h in a .c file like so:

client.c

#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}

Split string in C every white space

Consider using strtok_r, as others have suggested, or something like:

void printWords(const char *string) {
    // Make a local copy of the string that we can manipulate.
    char * const copy = strdup(string);
    char *space = copy;
    // Find the next space in the string, and replace it with a newline.
    while (space = strchr(space,' ')) *space = '\n';
    // There are no more spaces in the string; print out our modified copy.
    printf("%s\n", copy);
    // Free our local copy
    free(copy);
}

Google Authenticator available as a public service?

For C# user, run this simple Console App to understand how to verify the one time token code. Note that we need to install library Otp.Net from Nuget package first.

static string secretKey = "JBSWY3DPEHPK3PXP"; //add this key to your Google Authenticator app  

private static void Main(string[] args)
{
        var bytes = Base32Encoding.ToBytes(secretKey);

        var totp = new Totp(bytes);

        while (true)
        {
            Console.Write("Enter your code from Google Authenticator app: ");
            string userCode = Console.ReadLine();

            //Generate one time token code
            string tokenInApp = totp.ComputeTotp();
            int remainingSeconds = totp.RemainingSeconds();

            if (userCode.Equals(tokenInApp)
                && remainingSeconds > 0)
            {
                Console.WriteLine("Success!");
            }
            else
            {
                Console.WriteLine("Failed. Try again!");
            }
        }
}

Immediate exit of 'while' loop in C++

cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}

You don't need a break, in that case.

Where to put default parameter value in C++?

You can do either, but never both. Usually you do it at function declaration and then all callers can use that default value. However you can do that at function definition instead and then only those who see the definition will be able to use the default value.

is there a function in lodash to replace matched item

If you're looking for a way to immutably change the collection (as I was when I found your question), you might take a look at immutability-helper, a library forked from the original React util. In your case, you would accomplish what you mentioned via the following:

var update = require('immutability-helper')
var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}]
var newArray = update(arr, { 0: { name: { $set: 'New Name' } } })
//=> [{id: 1, name: "New Name"}, {id:2, name:"Person 2"}]

How do I check if file exists in jQuery or pure JavaScript?

With jQuery:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

EDIT:

Here is the code for checking 404 status, without using jQuery

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

Small changes and it could check for status HTTP status code 200 (success), instead.

EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:

function executeIfFileExist(src, callback) {
    var xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function() {
        if (this.readyState === this.DONE) {
            callback()
        }
    }
    xhr.open('HEAD', src)
}

How to call multiple JavaScript functions in onclick event?

You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.

So the best to do is add them by code as in:

_x000D_
_x000D_
var element = document.getElementById("multiple_onclicks");_x000D_
element.addEventListener("click", function(){console.log("click3 triggered")}, false);_x000D_
element.addEventListener("click", function(){console.log("click4 triggered")}, false);
_x000D_
<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");'  > Click me</button>
_x000D_
_x000D_
_x000D_

You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.

Clear all fields in a form upon going back with browser back button

I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.

In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.

I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:

$(window).bind("pageshow", function() {
    var form = $('form'); 
    // let the browser natively reset defaults
    form[0].reset();
});

If you are not handling the input events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change event yourself (or whatever event you care to handle, including a custom one):

form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');

That must be added after the reset to do any good.

DataTable: How to get item value with row name and column name? (VB)

Try:

DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()

(This is C# code. Change this to VB equivalent)

how to add background image to activity?

We can easily place the background image in PercentFrameLayout using the ImageView. We have to set the scaleType attribute value="fitXY" and in the foreground we can also display other view's like textview or button.

 <android.support.percent.PercentFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        >
        <ImageView
            android:src="@drawable/logo"
            android:id="@+id/im1"
            android:scaleType="fitXY"
            android:layout_height="match_parent"
            android:layout_width="match_parent"/>
<EditText android:layout_gravity="center_horizontal"
        android:hint="Enter Username"
        android:id="@+id/et1"
        android:layout_height="wrap_content"
        app:layout_widthPercent="50%"
        app:layout_marginTopPercent="30%"
        />
<Button
    android:layout_gravity="center_horizontal"
    android:text="Login"
    android:id="@+id/b1"
    android:layout_height="wrap_content"
    app:layout_widthPercent="50%"
    app:layout_marginTopPercent="40%"/>
</android.support.percent.PercentFrameLayout>

Java resource as file

Here is a bit of code from one of my applications... Let me know if it suits your needs. You can use this if you know the file you want to use.

URL defaultImage = ClassA.class.getResource("/packageA/subPackage/image-name.png");
File imageFile = new File(defaultImage.toURI());

Hope that helps.

LEFT JOIN in LINQ to entities?

You can use this not only in entities but also store procedure or other data source:

var customer = (from cus in _billingCommonservice.BillingUnit.CustomerRepository.GetAll()  
                          join man in _billingCommonservice.BillingUnit.FunctionRepository.ManagersCustomerValue()  
                          on cus.CustomerID equals man.CustomerID  
                          // start left join  
                          into a  
                          from b in a.DefaultIfEmpty(new DJBL_uspGetAllManagerCustomer_Result() )  
                          select new { cus.MobileNo1,b.ActiveStatus });  

equivalent of rm and mv in windows .cmd

move in windows is equivalent of mv command in Linux

del in windows is equivalent of rm command in Linux

jQuery ui datepicker with Angularjs

onSelect doesn't work well in ng-repeat, so I made another version using event bind

html

<tr ng-repeat="product in products">
<td>
    <input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>

script

angular.module('app', []).directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker();
            element.bind('blur keyup change', function(){
                var model = attrs.ngModel;
                if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
                else scope[model] = element.val();
            });
        }
    };
});

What are the differences between the urllib, urllib2, urllib3 and requests module?

To get the content of a url:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

It's hard to write Python2 and Python3 and request dependencies code for the responses because they urlopen() functions and requests.get() function return different types:

  • Python2 urllib.request.urlopen() returns a http.client.HTTPResponse
  • Python3 urllib.urlopen(url) returns an instance
  • Request request.get(url) returns a requests.models.Response

How to set time to 24 hour format in Calendar

Replace this:

c1.set(Calendar.HOUR, d1.getHours());

with this:

c1.set(Calendar.HOUR_OF_DAY, d1.getHours());

Calendar.HOUR is strictly for 12 hours.

Keras model.summary() result - Understanding the # of Parameters

For Dense Layers:

output_size * (input_size + 1) == number_parameters 

For Conv Layers:

output_channels * (input_channels * window_size + 1) == number_parameters

Consider following example,

model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
Conv2D(128, (3, 3), activation='relu'),
Dense(num_classes, activation='softmax')
])

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 222, 222, 32)      896       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 220, 220, 64)      18496     
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 218, 218, 128)     73856     
_________________________________________________________________
dense_9 (Dense)              (None, 218, 218, 10)      1290      
=================================================================

Calculating params,

assert 32 * (3 * (3*3) + 1) == 896
assert 64 * (32 * (3*3) + 1) == 18496
assert 128 * (64 * (3*3) + 1) == 73856
assert num_classes * (128 + 1) == 1290

How to get the selected radio button’s value?

    var value = $('input:radio[name="radiogroupname"]:checked').val();

In Python, how do I read the exif data for an image?

import sys
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS



class Worker(object):
    def __init__(self, img):
        self.img = img
        self.exif_data = self.get_exif_data()
        self.lat = self.get_lat()
        self.lon = self.get_lon()
        self.date =self.get_date_time()
        super(Worker, self).__init__()

    @staticmethod
    def get_if_exist(data, key):
        if key in data:
            return data[key]
        return None

    @staticmethod
    def convert_to_degress(value):
        """Helper function to convert the GPS coordinates
        stored in the EXIF to degress in float format"""
        d0 = value[0][0]
        d1 = value[0][1]
        d = float(d0) / float(d1)
        m0 = value[1][0]
        m1 = value[1][1]
        m = float(m0) / float(m1)

        s0 = value[2][0]
        s1 = value[2][1]
        s = float(s0) / float(s1)

        return d + (m / 60.0) + (s / 3600.0)

    def get_exif_data(self):
        """Returns a dictionary from the exif data of an PIL Image item. Also
        converts the GPS Tags"""
        exif_data = {}
        info = self.img._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        return exif_data

    def get_lat(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_latitude = self.get_if_exist(gps_info, "GPSLatitude")
            gps_latitude_ref = self.get_if_exist(gps_info, 'GPSLatitudeRef')
            if gps_latitude and gps_latitude_ref:
                lat = self.convert_to_degress(gps_latitude)
                if gps_latitude_ref != "N":
                    lat = 0 - lat
                lat = str(f"{lat:.{5}f}")
                return lat
        else:
            return None

    def get_lon(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_longitude = self.get_if_exist(gps_info, 'GPSLongitude')
            gps_longitude_ref = self.get_if_exist(gps_info, 'GPSLongitudeRef')
            if gps_longitude and gps_longitude_ref:
                lon = self.convert_to_degress(gps_longitude)
                if gps_longitude_ref != "E":
                    lon = 0 - lon
                lon = str(f"{lon:.{5}f}")
                return lon
        else:
            return None

    def get_date_time(self):
        if 'DateTime' in self.exif_data:
            date_and_time = self.exif_data['DateTime']
            return date_and_time 

if __name__ == '__main__':
    try:
        img = PILimage.open(sys.argv[1])
        image = Worker(img)
        lat = image.lat
        lon = image.lon
        date = image.date
        print(date, lat, lon)

    except Exception as e:
        print(e)

How do I programmatically "restart" an Android app?

Here is an example to restart your app in a generic way by using the PackageManager:

Intent i = getBaseContext().getPackageManager()
             .getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

Add/Delete table rows dynamically using JavaScript

1 & 2: innerHTML can take HTML as well as text. You could do something like:

c1.innerHTML = "<input size=25 type=\"text\" id='newID' readonly=true/>";

May or may not be the best way to do it, but you could do it that way.

3: I would just use a global variable that holds the number of POIs and increment/decrement it each time.

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

Java Compare Two Lists

EDIT

Here are two versions. One using ArrayList and other using HashSet

Compare them and create your own version from this, until you get what you need.

This should be enough to cover the:

P.S: It is not a school assignment :) So if you just guide me it will be enough

part of your question.

continuing with the original answer:

You may use a java.util.Collection and/or java.util.ArrayList for that.

The retainAll method does the following:

Retains only the elements in this collection that are contained in the specified collection

see this sample:

import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;

public class Repeated {
    public static void main( String  [] args ) {
        Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta"));
        Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo"));

        listOne.retainAll( listTwo );
        System.out.println( listOne );
    }
}

EDIT

For the second part ( similar values ) you may use the removeAll method:

Removes all of this collection's elements that are also contained in the specified collection.

This second version gives you also the similar values and handles repeated ( by discarding them).

This time the Collection could be a Set instead of a List ( the difference is, the Set doesn't allow repeated values )

import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;

class Repeated {
      public static void main( String  [] args ) {

          Collection<String> listOne = Arrays.asList("milan","iga",
                                                    "dingo","iga",
                                                    "elpha","iga",
                                                    "hafil","iga",
                                                    "meat","iga", 
                                                    "neeta.peeta","iga");

          Collection<String> listTwo = Arrays.asList("hafil",
                                                     "iga",
                                                     "binga", 
                                                     "mike", 
                                                     "dingo","dingo","dingo");

          Collection<String> similar = new HashSet<String>( listOne );
          Collection<String> different = new HashSet<String>();
          different.addAll( listOne );
          different.addAll( listTwo );

          similar.retainAll( listTwo );
          different.removeAll( similar );

          System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
      }
}

Output:

$ java Repeated
One:[milan, iga, dingo, iga, elpha, iga, hafil, iga, meat, iga, neeta.peeta, iga]

Two:[hafil, iga, binga, mike, dingo, dingo, dingo]

Similar:[dingo, iga, hafil]

Different:[mike, binga, milan, meat, elpha, neeta.peeta]

If it doesn't do exactly what you need, it gives you a good start so you can handle from here.

Question for the reader: How would you include all the repeated values?

When to use If-else if-else over switch statements and vice versa

Let's say you have decided to use switch as you are only working on a single variable which can have different values. If this would result in a small switch statement (2-3 cases), I'd say that is fine. If it seems you will end up with more I would recommend using polymorphism instead. An AbstractFactory pattern could be used here to create an object that would perform whatever action you were trying to do in the switches. The ugly switch statement will be abstracted away and you end up with cleaner code.

What is "pom" packaging in maven?

pom is basically a container of submodules, each submodule is represented by a subdirectory in the same directory as pom.xml with pom packaging.

Somewhere, nested within the project structure you will find artifacts (modules) with war packaging. Maven generally builds everything into /target subdirectories of each module. So after mvn install look into target subdirectory in a module with war packaging.

Of course:

$ find . -iname "*.war"

works equally well ;-).

How to start mongodb shell?

bat command to start mongodb

create one folder for database like in this example r0

start /d "{path}\bin" mongod.exe --replSet foo --port 27017 --dbpath {path}mongoDataBase\r0

start /d "{path}\bin" mongo.exe 127.0.0.1:27017

How to prevent caching of my Javascript file?

You can add a random (or datetime string) as query string to the url that points to your script. Like so:

<script type="text/javascript" src="test.js?q=123"></script> 

Every time you refresh the page you need to make sure the value of 'q' is changed.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

In my case the problem was - I had my app_folder and settings.py in it. Then I decided to make Settings folder inside app_folder - and that made a collision with settings.py. Just renamed that Settings folder - and everything worked.

Angular 2 'component' is not a known element

These are the 5 steps I perform when I got such an error.

  • Are you sure the name is correct? (also check the selector defined in the component)
  • Declare the component in a module?
  • If it is in another module, export the component?
  • If it is in another module, import that module?
  • Restart the cli?

When the error eccors during unit testing, make sure your declared the component or imported the module in TestBed.configureTestingModule

I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.

You can't declare a component twice. You should declare and export your component in a new separate module. Next you should import this new module in every module you want to use your component.

It is hard to tell when you should create new module and when you shouldn't. I usually create a new module for every component I reuse. When I have some components that I use almost everywhere I put them in a single module. When I have a component that I don't reuse I won't create a separate module until I need it somewhere else.

Though it might be tempting to put all you components in a single module, this is bad for the performance. While developing, a module has to recompile every time changes are made. The bigger the module (more components) the more time it takes. Making a small change to big module takes more time than making a small change in a small module.

JavaScript implementation of Gzip

You can use a 1 pixel per 1 pixel Java applet embedded in the page and use that for compression.

It's not JavaScript and the clients will need a Java runtime but it will do what you need.

SyntaxError: unexpected EOF while parsing

Here is one of my mistakes that produced this exception: I had a try block without any except or finally blocks. This will not work:

try:
    lets_do_something_beneficial()

To fix this, add an except or finally block:

try:
    lets_do_something_beneficial()
finally:
    lets_go_to_sleep()

How to display with n decimal places in Matlab

You can convert a number to a string with n decimal places using the SPRINTF command:

>> x = 1.23;
>> sprintf('%0.6f', x)

ans =

1.230000

>> x = 1.23456789;
>> sprintf('%0.6f', x)

ans =

1.234568

XPath to select multiple tags

Not sure if this helps, but with XSL, I'd do something like:

<xsl:for-each select="a/b">
    <xsl:value-of select="c"/>
    <xsl:value-of select="d"/>
    <xsl:value-of select="e"/>
</xsl:for-each>

and won't this XPath select all children of B nodes:

a/b/*

How to change the project in GCP using CLI commands

For what its worth if you have a more than a handful of projects, which I do, use:

gcloud init

This will list all your projects and give you the option to change current project settings, add a new project configuration or switch:

Pick configuration to use:
 [1] Re-initialize this configuration [esqimo-preprod] with new settings
 [2] Create a new configuration
 [3] Switch to and re-initialize existing configuration: [default]
 [4] Switch to and re-initialize existing configuration: [project 1]
 [5] Switch to and re-initialize existing configuration: [project 2]
Please enter your numeric choice:

It will always ask you to login and display options for different google accounts that you may have.

Given that I manage multiple organisations and projects this approach lets' me to simply switch between them.

Bat file to run a .exe at the command prompt

A bat file has no structure...it is how you would type it on the command line. So just open your favourite editor..copy the line of code you want to run..and save the file as whatever.bat or whatever.cmd

What is the best way to get all the divisors of a number?

Old question, but here is my take:

def divs(n, m):
    if m == 1: return [1]
    if n % m == 0: return [m] + divs(n, m - 1)
    return divs(n, m - 1)

You can proxy with:

def divisorGenerator(n):
    for x in reversed(divs(n, n)):
        yield x

NOTE: For languages that support, this could be tail recursive.

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

Two options (at least):

  1. Add the commons-logging jar to your file by copying it into a local folder.

Note: linking the jar can lead to problems with the server and maybe the reason why it's added to the build path but not solving the server startup problem.

So don't point the jar to an external folder.

OR...

  1. If you really don't want to add it locally because you're sharing the jar between projects, then...

If you're using a tc server instance, then you need to add the jar as an external jar to the server instance run configurations.

go to run as, run configurations..., {your tc server instance}, and then the Class Path tab.

Then add the commons-logging jar.

String comparison in bash. [[: not found

If you know you're on bash, and still get this error, make sure you write the if with spaces.

[[1==1]] # This outputs error

[[ 1==1 ]] # OK

Reading a simple text file

try this,

package example.txtRead;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class txtRead extends Activity {
    String labels="caption";
    String text="";
    String[] s;
    private Vector<String> wordss;
    int j=0;
    private StringTokenizer tokenizer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wordss = new Vector<String>();
        TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
        helloTxt.setText(readTxt());
 }

    private String readTxt(){

     InputStream inputStream = getResources().openRawResource(R.raw.toc);
//     InputStream inputStream = getResources().openRawResource(R.raw.internals);
     System.out.println(inputStream);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

     int i;
  try {
   i = inputStream.read();
   while (i != -1)
      {
       byteArrayOutputStream.write(i);
       i = inputStream.read();
      }
      inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

     return byteArrayOutputStream.toString();
    }
}

MySQL INNER JOIN select only one row from second table

Matei Mihai given a simple and efficient solution but it will not work until put a MAX(date) in SELECT part so this query will become:

SELECT u.*, p.*, max(date)
FROM payments p
JOIN users u ON u.id=p.user_id AND u.package = 1
GROUP BY u.id

And order by will not make any difference in grouping but it can order the final result provided by group by. I tried it and it worked for me.

Losing scope when using ng-include

As @Renan mentioned, ng-include creates a new child scope. This scope prototypically inherits (see dashed lines below) from the HomeCtrl scope. ng-model="lineText" actually creates a primitive scope property on the child scope, not HomeCtrl's scope. This child scope is not accessible to the parent/HomeCtrl scope:

ng-include scope

To store what the user typed into HomeCtrl's $scope.lines array, I suggest you pass the value to the addLine function:

 <form ng-submit="addLine(lineText)">

In addition, since lineText is owned by the ngInclude scope/partial, I feel it should be responsible for clearing it:

 <form ng-submit="addLine(lineText); lineText=''">

Function addLine() would thus become:

$scope.addLine = function(lineText) {
    $scope.chat.addLine(lineText);
    $scope.lines.push({
        text: lineText
    });
};

Fiddle.

Alternatives:

  • define an object property on HomeCtrl's $scope, and use that in the partial: ng-model="someObj.lineText; fiddle
  • not recommended, this is more of a hack: use $parent in the partial to create/access a lineText property on the HomeCtrl $scope:  ng-model="$parent.lineText"; fiddle

It is a bit involved to explain why the above two alternatives work, but it is fully explained here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I don't recommend using this in the addLine() function. It becomes much less clear which scope is being accessed/manipulated.

Reportviewer tool missing in visual studio 2017 RC

Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:

  1. If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:

    • Microsoft.DataTools.ReportingServices.vsix, and
    • Microsoft.RdlcDesigner.vsix
  2. Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:

    • Microsoft.ReportViewer.Common.dll
    • Microsoft.ReportViewer.DataVisualization.dll
    • Microsoft.ReportViewer.Design.dll
    • Microsoft.ReportViewer.ProcessingObjectModel.dll
    • Microsoft.ReportViewer.WinForms.dll
  3. Install the 2 components from 1 above

  4. Add the dlls from 2 above as references (Project>References>Add...)
  5. (Optional) Add Reporting tab to the toolbar
  6. Add Items to Reporting tab
  7. Browse to the bin folder or where you have the above dlls and add them

You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project

NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!

SQL to search objects, including stored procedures, in Oracle

i reached this question while trying to find all procedures which use a certain table

Oracle SQL Developer offers this capability, as pointed out in this article : https://www.thatjeffsmith.com/archive/2012/09/search-and-browse-database-objects-with-oracle-sql-developer/

From the View menu, choose Find DB Object. Choose a DB connection. Enter the name of the table. At Object Types, keep only functions, procedures and packages. At Code section, check All source lines.

enter image description here

How to set locale in DatePipe in Angular 2?

I was struggling with the same issue and didn't work for me using this

{{dateObj | date:'ydM'}}

So, I've tried a workaround, not the best solution but it worked:

{{dateObj | date:'d'}}/{{dateObj | date:'M'}}/{{dateObj | date:'y'}}

I can always create a custom pipe.

Can I use Homebrew on Ubuntu?

The following steps worked for me:

  • Clone it from github

    git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew
    
  • Open your .bash_profile file using vi ~/.bash_profile

  • Add these lines

    export PATH="$HOME/.linuxbrew/bin:$PATH"
    export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
    export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"
    
  • Then type the following lines in your terminal

    export PATH=$HOME/.linuxbrew/bin:$PATH
    hash -r
    

Yes, it is done. Type brew in your terminal to check its existence.

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

Remember to pipe Observables to async, like *ngFor item of items$ | async, where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair>, and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T.

Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty

PostgreSQL wildcard LIKE for any of a list of words

All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE.

Reference: https://www.postgresql.org/docs/current/functions-matching.html

Default password of mysql in ubuntu server 16.04

Early versions allowed root password to be blank but, in Newer versions set the root password is the admin(main) user login password during the installation.

Shorten string without cutting words in JavaScript

'Pasta with tomato and spinach'

if you do not want to cut the word in half

first iteration:

acc:0 / acc +cur.length = 5 / newTitle = ['Pasta'];

second iteration:

acc:5 / acc + cur.length = 9 / newTitle = ['Pasta', 'with'];

third iteration:

acc:9 / acc + cur.length = 15 / newTitle = ['Pasta', 'with', 'tomato'];

fourth iteration:

acc:15 / acc + cur.length = 18(limit bound) / newTitle = ['Pasta', 'with', 'tomato'];

const limitRecipeTitle = (title, limit=17)=>{
    const newTitle = [];
    if(title.length>limit){
        title.split(' ').reduce((acc, cur)=>{
            if(acc+cur.length <= limit){
                newTitle.push(cur);
            }
            return acc+cur.length;
        },0);
    }

    return `${newTitle.join(' ')} ...`
}

output: Pasta with tomato ...

Comparing Java enum members: == or equals()?

I want to complement polygenelubricants answer:

I personally prefer equals(). But it lake the type compatibility check. Which I think is an important limitation.

To have type compatibility check at compilation time, declare and use a custom function in your enum.

public boolean isEquals(enumVariable) // compare constant from left
public static boolean areEqual(enumVariable, enumVariable2) // compare two variable

With this, you got all the advantage of both solution: NPE protection, easy to read code and type compatibility check at compilation time.

I also recommend to add an UNDEFINED value for enum.

ORA-12560: TNS:protocol adaptor error

  1. Go to the windows machine that hosts the Oracle database server
  2. Go to Start -> Run -> Services.msc in Windows. Locate OracleService < SID > (here OracleServiceORCL) and click on Start to start the oracle database service (if not already running) Services

  3. Once it is up and running, from the command prompt run the following:

    tnsping < tnsalias > 
    

    (tnsalias entry you can find it in tnsnames.ora file)

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

Laravel Migration Change to Make a Column Nullable

For Laravel 4.2, Unnawut's answer above is the best one. But if you are using table prefix, then you need to alter your code a little.

function up()
{
    $table_prefix = DB::getTablePrefix();
    DB::statement('ALTER TABLE `' . $table_prefix . 'throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
}

And to make sure you can still rollback your migration, we'll do the down() as well.

function down()
{
    $table_prefix = DB::getTablePrefix();
    DB::statement('ALTER TABLE `' . $table_prefix . 'throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Instead of

return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);

try

return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);

Example JavaScript code to parse CSV data

Here's my simple vanilla JavaScript code:

let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
console.log(splitQuotes(a))

function splitQuotes(line) {
  if(line.indexOf('"') < 0) 
    return line.split(',')

  let result = [], cell = '', quote = false;
  for(let i = 0; i < line.length; i++) {
    char = line[i]
    if(char == '"' && line[i+1] == '"') {
      cell += char
      i++
    } else if(char == '"') {
      quote = !quote;
    } else if(!quote && char == ',') {
      result.push(cell)
      cell = ''
    } else {
      cell += char
    }
    if ( i == line.length-1 && cell) {
      result.push(cell)
    }
  }
  return result
}

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

Another potential cause for this error: Attempting to get permission for a Facebook app in sandbox mode when the Facebook user is not listed in the app's admins, developers or testers.

How can I check if a date is the same day as datetime.today()?

all(getattr(someTime,x)==getattr(today(),x) for x in ['year','month','day'])

One should compare using .date(), but I leave this method as an example in case one wanted to, for example, compare things by month or by minute, etc.

Avoid line break between html elements

This is the real solution:

<td>
  <span class="inline-flag">
    <i class="flag-bfh-ES"></i> 
    <span>+34 666 66 66 66</span>
  </span>
</td>

css:

.inline-flag {
   position: relative;
   display: inline;
   line-height: 14px; /* play with this */
}

.inline-flag > i {
   position: absolute;
   display: block;
   top: -1px; /* play with this */
}

.inline-flag > span {
   margin-left: 18px; /* play with this */
}

Example, images which always before text:

enter image description here

C++: constructor initializer for arrays

There is no array-construction syntax that ca be used in this context, at least not directly. You can accomplish what you're trying to accomplish by something along the lines of:

Bar::Bar()
{
    static const int inits [] = {4,5,6};
    static const size_t numInits = sizeof(inits)/sizeof(inits[0]);
    std::copy(&inits[0],&inits[numInits],foo);  // be careful that there are enough slots in foo
}

...but you'll need to give Foo a default constructor.

Class has been compiled by a more recent version of the Java Environment

Go to Project section, click on properties > then to Java compiler > check compiler compliance level is 1.8 , or there should be no yellow warning at bottom

align divs to the bottom of their container

The modern way to do this is with flexbox, adding align-items: flex-end; on the container.

With this content:

<div class="Container">
  <div>one</div>
  <div>two</div>
</div>

Use this style:

.Container {
  display: flex;
  align-items: flex-end;
}

https://codepen.io/rds/pen/gGMBbg

Setting user agent of a java URLConnection

Off hand, setting the http.agent system property to "" might do the trick (I don't have the code in front of me).

You might get away with:

 System.setProperty("http.agent", "");

but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).

The property can also be set through JNLP files (available to applets from 6u10) and on the command line:

-Dhttp.agent=

Or for wrapper commands:

-J-Dhttp.agent=

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

Convert date to another timezone in JavaScript

You can try this also for convert date timezone to India:

var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
console.log(indainDateObj);

Working Copy Locked

To anyone still having this issue (Error: Working copy '{DIR}' locked.), I have your solution:

I found that when one of TortoiseSVN windows crash, it leaves a TSVNCache.exe that still has a few handles to your working copy and that is causing the Lock issues you are seeing (and also prevents Clean Up from doing it's job).

So to resolve this:

Either

1a) Use Process Explorer or similar to delete the handles owned by TSVNCache.exe

1b) ..Or even easier, just use Task Manager to kill TSVNCache.exe

Then

2) Right click -> TortoiseSVN -> Clean up. Only "Clean up working copy status" needs to be checked.

From there, happy updating/committing. You can reproduce Lock behavior by doing SVN Update and then quickly killing it's TortoiseProc.exe process before Update finishes.

How to check if IEnumerable is null or empty?

The way I do it, taking advantage of some modern C# features:

Option 1)

public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any() ?? false);
    }
}

Option 2)

public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any()).GetValueOrDefault();
    }
}

And by the way, never use Count == 0 or Count() == 0 just to check if a collection is empty. Always use Linq's .Any()

remove table row with specific id

Try

$('table#test tr#3').remove();

Is there a good jQuery Drag-and-drop file upload plugin?

I created a plugin which allows you to drop some files onto a given area. This plugin currently works in Firefox, Safari and Chrome.

http://code.google.com/p/dnd-file-upload/

Converting a column within pandas dataframe from int to string

Change data type of DataFrame column:

To int:

df.column_name = df.column_name.astype(np.int64)

To str:

df.column_name = df.column_name.astype(str)

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

I have a similar problem with IIS 7, Win 7 Enterprise Pack. I have changed the application Pool as in @Kirk answer :

Change the Application Pool mode to one that has Classic pipeline enabled".but no luck for me.

Adding one more step worked for me. I have changed the my website's .NET Frameworkis v2.0 to .NET Frameworkis v4.0. in ApplicationPool

C# - Print dictionary

There's more than one way to skin this problem so here's my solution:

  1. Use Select() to convert the key-value pair to a string;
  2. Convert to a list of strings;
  3. Write out to the console using ForEach().
dict.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);

Django: save() vs update() to update the database?

save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.

update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.

How to check for the type of a template parameter?

std::is_same() is only available since C++11. For pre-C++11 you can use typeid():

template <typename T>
void foo()
{
    if (typeid(T) == typeid(animal)) { /* ... */ }
}

invalid target release: 1.7

Other than setting JAVA_HOME environment variable, you got to make sure you are using the correct JDK in your Maven run configuration. Go to Run -> Run Configuration, select your Maven Build configuration, go to JRE tab and set the correct Runtime JRE.

Maven run configuration

How to convert a date to milliseconds

The 2017 answer is: Use the date and time classes introduced in Java 8 (and also backported to Java 6 and 7 in the ThreeTen Backport).

If you want to interpret the date-time string in the computer’s time zone:

    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atZone(ZoneId.systemDefault())
            .toInstant()
            .toEpochMilli();

If another time zone, fill that zone in instead of ZoneId.systemDefault(). If UTC, use

    long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
            .atOffset(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();

Position Absolute + Scrolling

I ran into this situation and creating an extra div was impractical. I ended up just setting the full-height div to height: 10000%; overflow: hidden;

Clearly not the cleanest solution, but it works really fast.

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

The answer to many CSS formatting problems seems to be "add another <div>!"

So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):

_x000D_
_x000D_
textarea_x000D_
{_x000D_
  width:100%;_x000D_
}_x000D_
.textwrapper_x000D_
{_x000D_
  border:1px solid #999999;_x000D_
  margin:5px 0;_x000D_
  padding:3px;_x000D_
}
_x000D_
<div style="display: block;" id="rulesformitem" class="formitem">_x000D_
  <label for="rules" id="ruleslabel">Rules:</label>_x000D_
  <div class="textwrapper"><textarea cols="2" rows="10" id="rules"/></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to detect lowercase letters in Python?

To check if a character is lower case, use the islower method of str. This simple imperative program prints all the lowercase letters in your string:

for c in s:
    if c.islower():
         print c

Note that in Python 3 you should use print(c) instead of print c.


Possibly ending up with assigning those letters to a different variable.

To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:

>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']

Or to get a string you can use ''.join with a generator:

>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'

TypeScript - Append HTML to container element in Angular 2

With the new angular class Renderer2

constructor(private renderer:Renderer2) {}

  @ViewChild('one', { static: false }) d1: ElementRef;

  ngAfterViewInit() {
    const d2 = this.renderer.createElement('div');
    const text = this.renderer.createText('two');
    this.renderer.appendChild(d2, text);
    this.renderer.appendChild(this.d1.nativeElement, d2);
  }

Get GPS location from the web browser

There is the GeoLocation API, but browser support is rather thin on the ground at present. Most sites that care about such things use a GeoIP database (with the usual provisos about the inaccuracy of such a system). You could also look at third party services requiring user cooperation such as FireEagle.

What is the difference between an Instance and an Object?

An instance is a specific representation of an object. An object is a generic thing while an instance is a single object that has been created in memory. Usually an instance will have values assigned to it's properties that differentiates it from other instances of the type of object.

Getting all request parameters in Symfony 2

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];

For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html

How to use relative/absolute paths in css URLs?

i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.

Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like

.icon{
  background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}

and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.

Good Luck!

Read input from console in Ruby?

If you want to make interactive console:

#!/usr/bin/env ruby

require "readline"
addends = []
while addend_string = Readline.readline("> ", true)
  addends << addend_string.to_i
  puts "#{addends.join(' + ')} = #{addends.sum}"
end

Usage (assuming you put above snippet into summator file in current directory):

chmod +x summator
./summator
> 1
1 = 1
> 2
1 + 2 = 3

Use Ctrl + D to exit

How do I remove a key from a JavaScript object?

It's as easy as:

delete object.keyname;

or

delete object["keyname"];

Warning: push.default is unset; its implicit value is changing in Git 2.0

I realize this is an old post but as I just ran into the same issue and had trouble finding the answer I thought I'd add a bit.

So @hammar's answer is correct. Using push.default simple is, in a way, like configuring tracking on your branches so you don't need to specify remotes and branches when pushing and pulling. The matching option will push all branches to their corresponding counterparts on the default remote (which is the first one that was set up unless you've configured your repo otherwise).

One thing I hope others find useful in the future is that I was running Git 1.8 on OS X Mountain Lion and never saw this error. Upgrading to Mavericks is what suddenly made it show up (running git --version will show git version 1.8.3.4 (Apple Git-47) which I'd never seen until the update to the OS.

How to clear all <div>s’ contents inside a parent <div>?

You can use .empty() function to clear all the child elements

 $(document).ready(function () {
  $("#button").click(function () {
   //only the content inside of the element will be deleted
   $("#masterdiv").empty();
  });
 });

To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/

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

You can try the following steps and code using qrtools:

  • Create a qrcode file, if not already existing

    • I used pyqrcode for doing this, which can be installed using pip install pyqrcode
    • And then use the code:

      >>> import pyqrcode
      >>> qr = pyqrcode.create("HORN O.K. PLEASE.")
      >>> qr.png("horn.png", scale=6)
      
  • Decode an existing qrcode file using qrtools

    • Install qrtools using sudo apt-get install python-qrtools
    • Now use the following code within your python prompt

      >>> import qrtools
      >>> qr = qrtools.QR()
      >>> qr.decode("horn.png")
      >>> print qr.data
      u'HORN O.K. PLEASE.'
      

Here is the complete code in a single run:

In [2]: import pyqrcode
In [3]: qr = pyqrcode.create("HORN O.K. PLEASE.")
In [4]: qr.png("horn.png", scale=6)
In [5]: import qrtools
In [6]: qr = qrtools.QR()
In [7]: qr.decode("horn.png")
Out[7]: True
In [8]: print qr.data
HORN O.K. PLEASE.

Caveats

  • You might need to install PyPNG using pip install pypng for using pyqrcode
  • In case you have PIL installed, you might get IOError: decoder zip not available. In that case, try uninstalling and reinstalling PIL using:

    pip uninstall PIL
    pip install PIL
    
  • If that doesn't work, try using Pillow instead

    pip uninstall PIL
    pip install pillow
    

How to get multiple selected values of select box in php?

// CHANGE name="select2" TO name="select2[]" THEN
<?php
  $mySelection = $_GET['select2'];

  $nSelection = count($MySelection);

  for($i=0; $i < $nSelection; $i++)
   {
      $numberVal = $MySelection[$i];

        if ($numberVal == "11"){
         echo("Eleven"); 
         }
        else if ($numberVal == "12"){
         echo("Twelve"); 
         } 
         ...

         ...
    }
?>

Unexpected 'else' in "else" error

I would suggest to read up a bit on the syntax. See here.

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else if (dst<0.05) {
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else 
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)

Return value from exec(@sql)

that's my procedure

CREATE PROC sp_count
    @CompanyId sysname,
    @codition sysname
    AS
    SET NOCOUNT ON
    CREATE TABLE #ctr
    ( NumRows int )

    DECLARE @intCount int
         , @vcSQL varchar(255)

    SELECT    @vcSQL = ' INSERT #ctr FROM dbo.Comm_Services 
                       WHERE CompanyId = '+@CompanyId+' and '+@condition+')'
    EXEC      (@vcSQL)

    IF @@ERROR = 0
    BEGIN
         SELECT    @intCount = NumRows
         FROM #ctr

         DROP TABLE #ctr
         RETURN @intCount
    END
    ELSE
    BEGIN
         DROP TABLE #ctr
         RETURN -1
    END
    GO

failed to open stream: HTTP wrapper does not support writeable connections

May this code help you. It works in my case.

$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
    $fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
    if(!file_exists($filename)):
        $handle = fopen( $filename, 'a' ) or die( 'Cannot open file:  ' . $fileUrl ); //implicitly creates file
        fwrite( $handle, json_encode(array()));
        fclose( $handle );
    endif;
    $response = file_get_contents($filename);
    $tempArray = json_decode($response);
    if(!empty($tempArray)):
        $count = count($tempArray) + 1;
    else:
        $count = 1;
    endif;
    $tempArray[] = array_merge(array("sn." => $count), $data);
    $jsonData = json_encode($tempArray);
    file_put_contents($filename, $jsonData);

How to export specific request to file using postman?

To do that you need to leverage the "Collections" feature of Postman. This link could help you: https://learning.getpostman.com/docs/postman/collections/creating_collections/

Here is the way to do it:

  • Create a collection (within tab "Collections")
  • Execute your request
  • Add the request to a collection
  • Share your collection as a file

In PHP with PDO, how to check the final SQL parametrized query?

I check Query Log to see the exact query that was executed as prepared statement.

MySQL IF ELSEIF in select query

IF() in MySQL is a ternary function, not a control structure -- if the condition in the first argument is true, it returns the second argument; otherwise, it returns the third argument. There is no corresponding ELSEIF() function or END IF keyword.

The closest equivalent to what you've got would be something like:

IF(qty_1<='23', price,
  IF('23'>qty_1 && qty_2<='23', price_2,
    IF('23'>qty_2 && qty_3<='23', price_3,
      IF('23'>qty_3, price_4, 1)
    )
  )
)

The conditions don't all make sense to me (it looks as though some of them may be inadvertently reversed?), but without knowing what exactly you're trying to accomplish, it's hard for me to fix that.

How to hide elements without having them take space on the page?

$('#abc').css({"display":"none"});

this hides the content and also does not leave empty space.

How to hide status bar in Android

This is the official documentation about hiding the Status Bar on Android 4.0 and lower and on Android 4.1 and higher

Please, take a look at it:

https://developer.android.com/training/system-ui/status.html

How to base64 encode image in linux bash / shell

Base 64 for html:

file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"

How to loop backwards in python?

range() and xrange() take a third parameter that specifies a step. So you can do the following.

range(10, 0, -1)

Which gives

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

But for iteration, you should really be using xrange instead. So,

xrange(10, 0, -1)

Note for Python 3 users: There are no separate range and xrange functions in Python 3, there is just range, which follows the design of Python 2's xrange.

How to for each the hashmap?

Lambda Expression Java 8

In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.

Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
 *     Logic to put the Key,Value pair in your HashMap hm
 */

// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Here is an example where a Lambda Expression is used:

    HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
    Random rand = new Random(47);
    int i=0;
    while(i<5){
        i++;
        int key = rand.nextInt(20);
        int value = rand.nextInt(50);
        System.out.println("Inserting key: "+key+" Value: "+value);
        Integer imap =hm.put(key,value);
        if( imap == null){
            System.out.println("Inserted");
        }
        else{
            System.out.println("Replaced with "+imap);
        }               
    }

    hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Output:

Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11

Also one can use Spliterator for the same.

Spliterator sit = hm.entrySet().spliterator();

UPDATE


Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.

Partly cherry-picking a commit with Git

I know I'm answering an old question, but it looks like there's a new way to do this with interactively checking out:

git checkout -p bc66559

Credit to Can I interactively pick hunks from another git commit?

how to fire event on file select

vanilla js using es6

document.querySelector('input[name="file"]').addEventListener('change', (e) => {
 const file = e.target.files[0];
  // todo: use file pointer
});

"Sub or Function not defined" when trying to run a VBA script in Outlook

This error “Sub or Function not defined”, will come every time when there is some compile error in script, so please check syntax again of your script.

I guess that is why when you used msqbox instead of msgbox it throws the error.

How do I read all classes from a Java package in the classpath?

I use this one, it works with files or jar archives

public static ArrayList<String>getClassNamesFromPackage(String packageName) throws IOException{
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL packageURL;
    ArrayList<String> names = new ArrayList<String>();;

    packageName = packageName.replace(".", "/");
    packageURL = classLoader.getResource(packageName);

    if(packageURL.getProtocol().equals("jar")){
        String jarFileName;
        JarFile jf ;
        Enumeration<JarEntry> jarEntries;
        String entryName;

        // build jar file name, then loop through zipped entries
        jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8");
        jarFileName = jarFileName.substring(5,jarFileName.indexOf("!"));
        System.out.println(">"+jarFileName);
        jf = new JarFile(jarFileName);
        jarEntries = jf.entries();
        while(jarEntries.hasMoreElements()){
            entryName = jarEntries.nextElement().getName();
            if(entryName.startsWith(packageName) && entryName.length()>packageName.length()+5){
                entryName = entryName.substring(packageName.length(),entryName.lastIndexOf('.'));
                names.add(entryName);
            }
        }

    // loop through files in classpath
    }else{
    URI uri = new URI(packageURL.toString());
    File folder = new File(uri.getPath());
        // won't work with path which contains blank (%20)
        // File folder = new File(packageURL.getFile()); 
        File[] contenuti = folder.listFiles();
        String entryName;
        for(File actual: contenuti){
            entryName = actual.getName();
            entryName = entryName.substring(0, entryName.lastIndexOf('.'));
            names.add(entryName);
        }
    }
    return names;
}

Python Binomial Coefficient

It's a good idea to apply a recursive definition, as in Vadim Smolyakov's answer, combined with a DP (dynamic programming), but for the latter you may apply the lru_cache decorator from module functools:

import functools

@functools.lru_cache(maxsize = None)
def binom(n,k):
    if k == 0: return 1
    if n == k: return 1
    return binom(n-1,k-1)+binom(n-1,k)

How do I comment on the Windows command line?

It's "REM".

Example:

REM This is a comment

Debug JavaScript in Eclipse

I'm not a 100% sure but I think Aptana let's you do that.

How do I pass named parameters with Invoke-Command?

I suspect its a new feature since this post was created - pass parameters to the script block using $Using:var. Then its a simple mater to pass parameters provided the script is already on the machine or in a known network location relative to the machine

Taking the main example it would be:

icm -cn $Env:ComputerName { 
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -one "uno" -two "dos" -Debug -Clear $Using:Clear
}

count (non-blank) lines-of-code in bash

cat foo.c | sed '/^\s*$/d' | wc -l

And if you consider comments blank lines:

cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l

Although, that's language dependent.

How to TryParse for Enum value?

There is not a TryParse because the Enum's type is not known until runtime. A TryParse that follows the same methodology as say the Date.TryParse method would throw an implicit conversion error on the ByRef parameter.

I suggest doing something like this:

//1 line call to get value
MyEnums enumValue = (Sections)EnumValue(typeof(Sections), myEnumTextValue, MyEnums.SomeEnumDefault);

//Put this somewhere where you can reuse
public static object EnumValue(System.Type enumType, string value, object NotDefinedReplacement)
{
    if (Enum.IsDefined(enumType, value)) {
        return Enum.Parse(enumType, value);
    } else {
        return Enum.Parse(enumType, NotDefinedReplacement);
    }
}

Microsoft Excel ActiveX Controls Disabled?

I did finally find this answer on the official Microsoft KB:

http://support.microsoft.com/kb/3025036/EN-US

No new information here than what we have in previous answers, but at least it acknowledges that Microsoft is aware of the issue.

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

How to return a PNG image from Jersey REST service method to the browser

If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:

@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage>  {
  @Override
  public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return type == BufferedImage.class;
  }

  @Override
  public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return -1; // not used in JAX-RS 2
  }

  @Override
  public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
    ImageIO.write(image, mt.getSubtype(), out);
  } 
}

This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.

Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:

@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
  BufferedImage image = ...;
  return Response.ok(image).build();
}

A couple of advantages to this approach:

  • It writes to the response OutputSteam rather than an intermediary BufferedOutputStream
  • It supports both png and jpg output (depending on the media types allowed by the resource method)

How to send a simple string between two programs using pipes?

From Creating Pipes in C, this shows you how to fork a program to use a pipe. If you don't want to fork(), you can use named pipes.

In addition, you can get the effect of prog1 | prog2 by sending output of prog1 to stdout and reading from stdin in prog2. You can also read stdin by opening a file named /dev/stdin (but not sure of the portability of that).

/*****************************************************************************
 Excerpt from "Linux Programmer's Guide - Chapter 6"
 (C)opyright 1994-1995, Scott Burkett
 ***************************************************************************** 
 MODULE: pipe.c
 *****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        char    string[] = "Hello, world!\n";
        char    readbuffer[80];

        pipe(fd);

        if((childpid = fork()) == -1)
        {
                perror("fork");
                exit(1);
        }

        if(childpid == 0)
        {
                /* Child process closes up input side of pipe */
                close(fd[0]);

                /* Send "string" through the output side of pipe */
                write(fd[1], string, (strlen(string)+1));
                exit(0);
        }
        else
        {
                /* Parent process closes up output side of pipe */
                close(fd[1]);

                /* Read in a string from the pipe */
                nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                printf("Received string: %s", readbuffer);
        }

        return(0);
}

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Android Studio Run/Debug configuration error: Module not specified

never mind, i changed the name in settings.gradle and synced and then changed it back and synced again and it inexplicably worked this time.

How to open a URL in a new Tab using JavaScript or jQuery?

Use window.open():

var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
    //Browser has allowed it to be opened
    win.focus();
} else {
    //Browser has blocked it
    alert('Please allow popups for this website');
}

Depending on the browsers implementation this will work

There is nothing you can do to make it open in a window rather than a tab.

What do the makefile symbols $@ and $< mean?

From Managing Projects with GNU Make, 3rd Edition, p. 16 (it's under GNU Free Documentation License):

Automatic variables are set by make after a rule is matched. They provide access to elements from the target and prerequisite lists so you don’t have to explicitly specify any filenames. They are very useful for avoiding code duplication, but are critical when defining more general pattern rules.

There are seven “core” automatic variables:

  • $@: The filename representing the target.

  • $%: The filename element of an archive member specification.

  • $<: The filename of the first prerequisite.

  • $?: The names of all prerequisites that are newer than the target, separated by spaces.

  • $^: The filenames of all the prerequisites, separated by spaces. This list has duplicate filenames removed since for most uses, such as compiling, copying, etc., duplicates are not wanted.

  • $+: Similar to $^, this is the names of all the prerequisites separated by spaces, except that $+ includes duplicates. This variable was created for specific situations such as arguments to linkers where duplicate values have meaning.

  • $*: The stem of the target filename. A stem is typically a filename without its suffix. Its use outside of pattern rules is discouraged.

In addition, each of the above variables has two variants for compatibility with other makes. One variant returns only the directory portion of the value. This is indicated by appending a “D” to the symbol, $(@D), $(<D), etc. The other variant returns only the file portion of the value. This is indicated by appending an “F” to the symbol, $(@F), $(<F), etc. Note that these variant names are more than one character long and so must be enclosed in parentheses. GNU make provides a more readable alternative with the dir and notdir functions.

php form action php self

You can use an echo shortcut also instead of typing out "echo blah;" as shown below:

<form method="POST" action="<?=($_SERVER['PHP_SELF'])?>">

Why does dividing two int not yield the right value when assigned to double?

The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double.

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

Div with margin-left and width:100% overflowing on the right side

Add some css either in the head or in a external document. asp:TextBox are rendered as input :

input {
     width:100%;
}

Your html should look like : http://jsfiddle.net/c5WXA/

Note this will affect all your textbox : if you don't want this, give the containing div a class and specify the css.

.divClass input {
     width:100%;
}