Programs & Examples On #Struts config

Use this question for struts-config related questions.

Why maven? What are the benefits?

This should have been a comment, but it wasn't fitting in a comment length, so I posted it as an answer.

All the benefits mentioned in other answers are achievable by simpler means than using maven. If, for-example, you are new to a project, you'll anyway spend more time creating project architecture, joining components, coding than downloading jars and copying them to lib folder. If you are experienced in your domain, then you already know how to start off the project with what libraries. I don't see any benefit of using maven, especially when it poses a lot of problems while automatically doing the "dependency management".

I only have intermediate level knowledge of maven, but I tell you, I have done large projects(like ERPs) without using maven.

getElementById in React

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
    }
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>
  );
}

If diff is not performed then, you will get null.

How do I increase the scrollback buffer in a running screen session?

As Already mentioned we have two ways!

 Per screen (session) interactive setting

And it's done interactively! And take effect immediately!

CTRL + A followed by : And we type scrollback 1000000 And hit ENTER

You detach from the screen and come back! It will be always the same.

You open another new screen! And the value is reset again to default! So it's not a global setting!

 And the permanent default setting

Which is done by adding defscrollback 1000000 to .screenrc (in home)

defscrollback and not scrollback (def stand for default)

What you need to know is if the file is not created ! You create it !

> cd ~ && vim .screenrc

And you add defscrollback 1000000 to it!

Or in one command

> echo "defscrollback 1000000" >> .screenrc

(if not created already)

Taking effect

When you add the default to .screenrc! The already running screen at re-attach will not take effect! The .screenrc run at the screen creation! And it make sense! Just as with a normal console and shell launch!

And all the new created screens will have the set value!

Checking the screen effective buffer size

To check type CTRL + A followed by i

And The result will be as

enter image description here

Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)

Note too that when you change it interactively! The effect is immediate and take over the default value!

Scrolling

CTRL+ A followed by ESC (to enter the copy mode).

Then navigate with Up,Down or PgUp PgDown

And ESC again to quit that mode.

(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)

Now the buffer is bigger!

And that's sum it up for the important details!

Launch an app on OS X with command line

Beginning with OS X Yosemite, we can now use AppleScript and Automator to automate complex tasks. JavaScript for automation can now be used as the scripting language.

This page gives a good example example script that can be written at the command line using bash and osascript interactive mode. It opens a Safari tab and navigates to example.com.

http://developer.telerik.com/featured/javascript-os-x-automation-example/
osascript -l JavaScript -i
Safari = Application("Safari");
window = Safari.windows[0];
window.name();
tab = Safari.Tab({url:"http://www.example.com"});
window.tabs.push(tab); 
window.currentTab = tab;

error: resource android:attr/fontVariationSettings not found

I removed all the unused plugins in the pubspec.yaml and in the External Libraries to solve the problem.

Is it a good practice to use try-except-else in Python?

Python doesn't subscribe to the idea that exceptions should only be used for exceptional cases, in fact the idiom is 'ask for forgiveness, not permission'. This means that using exceptions as a routine part of your flow control is perfectly acceptable, and in fact, encouraged.

This is generally a good thing, as working this way helps avoid some issues (as an obvious example, race conditions are often avoided), and it tends to make code a little more readable.

Imagine you have a situation where you take some user input which needs to be processed, but have a default which is already processed. The try: ... except: ... else: ... structure makes for very readable code:

try:
   raw_value = int(input())
except ValueError:
   value = some_processed_value
else: # no error occured
   value = process_value(raw_value)

Compare to how it might work in other languages:

raw_value = input()
if valid_number(raw_value):
    value = process_value(int(raw_value))
else:
    value = some_processed_value

Note the advantages. There is no need to check the value is valid and parse it separately, they are done once. The code also follows a more logical progression, the main code path is first, followed by 'if it doesn't work, do this'.

The example is naturally a little contrived, but it shows there are cases for this structure.

Change the location of the ~ directory in a Windows install of Git Bash

I don't understand, why you don't want to set the $HOME environment variable since that solves exactly what you're asking for.

cd ~ doesn't mean change to the root directory, but change to the user's home directory, which is set by the $HOME environment variable.

Quick'n'dirty solution

Edit C:\Program Files (x86)\Git\etc\profile and set $HOME variable to whatever you want (add it if it's not there). A good place could be for example right after a condition commented by # Set up USER's home directory. It must be in the MinGW format, for example:

HOME=/c/my/custom/home

Save it, open Git Bash and execute cd ~. You should be in a directory /c/my/custom/home now.

Everything that accesses the user's profile should go into this directory instead of your Windows' profile on a network drive.

Note: C:\Program Files (x86)\Git\etc\profile is shared by all users, so if the machine is used by multiple users, it's a good idea to set the $HOME dynamically:

HOME=/c/Users/$USERNAME

Cleaner solution

Set the environment variable HOME in Windows to whatever directory you want. In this case, you have to set it in Windows path format (with backslashes, e.g. c:\my\custom\home), Git Bash will load it and convert it to its format.

If you want to change the home directory for all users on your machine, set it as a system environment variable, where you can use for example %USERNAME% variable so every user will have his own home directory, for example:

HOME=c:\custom\home\%USERNAME%

If you want to change the home directory just for yourself, set it as a user environment variable, so other users won't be affected. In this case, you can simply hard-code the whole path:

HOME=c:\my\custom\home

Is multiplication and division using shift operators in C actually faster?

As far as I know in some machines multiplication can need upto 16 to 32 machine cycle. So Yes, depending on the machine type, bitshift operators are faster than multiplication / division.

However certain machine do have their math processor, which contains special instructions for multiplication/division.

How to find array / dictionary value using key?

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

What exactly does Double mean in java?

In a comment on @paxdiablo's answer, you asked:

"So basically, is it better to use Double than Float?"

That is a complicated question. I will deal with it in two parts


Deciding between double versus float

On the one hand, a double occupies 8 bytes versus 4 bytes for a float. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double values is typically slower than with float values ... though once again this is hardware dependent.

On the other hand, a double can represent larger (and smaller) numbers than a float and can represent them with more than twice the precision. For the details, refer to Wikipedia.

The tricky question is knowing whether you actually need the extra range and precision of a double. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double is going to give you enough precision. (And beware of the trap of expecting float and double to give you an exact representation. They won't and they can't!)

There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.


Deciding between Double versus Float

For the Double versus Float case, the issues of precision and range are the same as for double versus float, but the relative performance measures will be slightly different.

  • A Double (on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float. Compare this to 8 bytes versus 4 bytes for the double versus float case. So the ratio is 5 to 4 versus 2 to 1.

  • Arithmetic involving Double and Float typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double case.


Correctness

Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double in preference to float, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float will make a difference with respect to that requirement.

How to inspect Javascript Objects

How about alert(JSON.stringify(object)) with a modern browser?

In case of TypeError: Converting circular structure to JSON, here are more options: How to serialize DOM node to JSON even if there are circular references?

The documentation: JSON.stringify() provides info on formatting or prettifying the output.

setTimeout / clearTimeout problems

Not sure if this violates some good practice coding rule but I usually come out with this one:

if(typeof __t == 'undefined')
        __t = 0;
clearTimeout(__t);
__t = setTimeout(callback, 1000);

This prevent the need to declare the timer out of the function.

EDIT: this also don't declare a new variable at each invocation, but always recycle the same.

Hope this helps.

Where is Maven's settings.xml located on Mac OS?

After I have downloaded the binary from apache site I, have placed the extracted folder in /Library
So now the location of the settings.xml file is in:

/Library/apache_maven_3.6.3/conf

Reversing a string in C

You can try this pointer arithmetic:

void revString(char *s)
{
  char *e = s; while(*e){ e++; } e--;
  while(e > s){ *s ^= *e; *e ^= *s; *s++ ^= *e--; }
}

Basic Python client socket example

You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type python myprogram.py the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable — and thus you are confusing Python's runtime compilaint that “I can't find anyone listening on port 5000!” with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!

Effective way to find any file's Encoding

It may be useful

string path = @"address/to/the/file.extension";

using (StreamReader sr = new StreamReader(path))
{ 
    Console.WriteLine(sr.CurrentEncoding);                        
}

Parse time of format hh:mm:ss

As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:

    String myDateString = "13:24:40";
    LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));
    int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
    int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
    int second = localTime.get(ChronoField.SECOND_OF_MINUTE);

    //prints "hour: 13, minute: 24, second: 40":
    System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));

Remarks:

  • since the OP's question contains a concrete example of a time instant containing only hours, minutes and seconds (no day, month, etc.), the answer above only uses LocalTime. If wanting to parse a string that also contains days, month, etc. then LocalDateTime would be required. Its usage is pretty much analogous to that of LocalTime.
  • since the time instant int OP's question doesn't contain any information about timezone, the answer uses the LocalXXX version of the date/time classes (LocalTime, LocalDateTime). If the time string that needs to be parsed also contains timezone information, then ZonedDateTime needs to be used.

====== Below is the old (original) answer for this question, using pre-Java8 API: =====

I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.

A SimpleDateFormat might do the trick here:

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

It should be something like:

String myDateString = "13:24:40";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);

Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds

The gotchas you should be aware of:

  • the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this

  • Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.

Item frequency count in Python

Use reduce() to convert the list to a single dict.

words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})

returns

{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

Read response headers from API response - Angular 5 + TypeScript

As Hrishikesh Kale has explained we need to pass the Access-Control-Expose-Headers.

Here how we can do it in the WebAPI/MVC environment:

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

Another way is we can add code as below in the webApiconfig.cs file.

config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

**We can add custom headers in the web.config file as below. *

<httpProtocol>
   <customHeaders>
      <add name="Access-Control-Expose-Headers" value="TestHeaderToExpose" />
   </customHeaders>
</httpProtocol>

we can create an attribute and decore the method with the attribute.

Happy Coding !!

How can I view the shared preferences file using Android Studio?

Run the application in Emulator after you insert some data, just close the application.

Now open the DDMS or Android Monitor and select your emulator, on the right side you can see the File Explorer, look for Data folder in it and look for your application package that you have created, in that you can find the shared preference file open it , you can see the XML file, click it and click the pull a file from the device button in the top right corner.

The XML file will be saved in your desired location, then you can open it using any editor like notepad++ and can view the data you have entered.

How do I determine the size of my array in C?

The sizeof way is the right way iff you are dealing with arrays not received as parameters. An array sent as a parameter to a function is treated as a pointer, so sizeof will return the pointer's size, instead of the array's.

Thus, inside functions this method does not work. Instead, always pass an additional parameter size_t size indicating the number of elements in the array.

Test:

#include <stdio.h>
#include <stdlib.h>

void printSizeOf(int intArray[]);
void printLength(int intArray[]);

int main(int argc, char* argv[])
{
    int array[] = { 0, 1, 2, 3, 4, 5, 6 };

    printf("sizeof of array: %d\n", (int) sizeof(array));
    printSizeOf(array);

    printf("Length of array: %d\n", (int)( sizeof(array) / sizeof(array[0]) ));
    printLength(array);
}

void printSizeOf(int intArray[])
{
    printf("sizeof of parameter: %d\n", (int) sizeof(intArray));
}

void printLength(int intArray[])
{
    printf("Length of parameter: %d\n", (int)( sizeof(intArray) / sizeof(intArray[0]) ));
}

Output (in a 64-bit Linux OS):

sizeof of array: 28
sizeof of parameter: 8
Length of array: 7
Length of parameter: 2

Output (in a 32-bit windows OS):

sizeof of array: 28
sizeof of parameter: 4
Length of array: 7
Length of parameter: 1

Angular2 *ngIf check object array length in template

You could use *ngIf="teamMembers != 0" to check whether data is present

Can I set state inside a useEffect hook

Effects are always executed after the render phase is completed even if you setState inside the one effect, another effect will read the updated state and take action on it only after the render phase.

Having said that its probably better to take both actions in the same effect unless there is a possibility that b can change due to reasons other than changing a in which case too you would want to execute the same logic

How do I convert a calendar week into a date in Excel?

For ISO week numbers you can use this formula to get the Monday

=DATE(A2,1,-2)-WEEKDAY(DATE(A2,1,3))+B2*7

assuming year in A2 and week number in B2

it's the same as my answer here https://stackoverflow.com/a/10855872/1124287

Closing a file after File.Create

The function returns a FileStream object. So you could use it's return value to open your StreamWriter or close it using the proper method of the object:

File.Create(myPath).Close();

How to code a BAT file to always run as admin mode?

Just add this to the top of your bat file:

set "params=%*"
cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || (  echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/k cd ""%~sdp0"" && %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B )

It will elevate to admin and also stay in the correct directory. Tested on Windows 10.

"Are you missing an assembly reference?" compile error - Visual Studio

Right-click the assembly reference in the solution explorer, properties, disable the "Specific Version" option.

Building a fat jar using maven

You can use the maven-shade-plugin.

After configuring the shade plugin in your build the command mvn package will create one single jar with all dependencies merged into it.

Foreach loop in java for a custom object list

Actually the enhanced for loop should look like this

for (final Room room : rooms) {
          // Here your room is available
}

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

Excel VBA - select multiple columns not in sequential order

As a recorded macro.

range("A:A, B:B, D:D, E:E, G:G, H:H").select

Converting string to title case

For the ones who are looking to do it automatically on keypress I did it with following code in vb.net on a custom textboxcontrol - you can obviously also do it with a normal textbox - but I like the possibility to add recurring code for specific controls via custom controls it suits the concept of OOP.

Imports System.Windows.Forms
Imports System.Drawing
Imports System.ComponentModel

Public Class MyTextBox
    Inherits System.Windows.Forms.TextBox
    Private LastKeyIsNotAlpha As Boolean = True
    Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
        If _ProperCasing Then
            Dim c As Char = e.KeyChar
            If Char.IsLetter(c) Then
                If LastKeyIsNotAlpha Then
                    e.KeyChar = Char.ToUpper(c)
                    LastKeyIsNotAlpha = False
                End If
            Else
                LastKeyIsNotAlpha = True
            End If
        End If
        MyBase.OnKeyPress(e)
End Sub
    Private _ProperCasing As Boolean = False
    <Category("Behavior"), Description("When Enabled ensures for automatic proper casing of string"), Browsable(True)>
    Public Property ProperCasing As Boolean
        Get
            Return _ProperCasing
        End Get
        Set(value As Boolean)
            _ProperCasing = value
        End Set
    End Property
End Class

URL rewriting with PHP

this is an .htaccess file that forward almost all to index.php

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php

then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever

onclick go full screen

so simple try this

_x000D_
_x000D_
<div dir="ltr" style="text-align: left;" trbidi="on">_x000D_
<!-- begin snippet: js hide: false console: true babel: null -->
_x000D_
_x000D_
_x000D_

adb connection over tcp not working now

Step 1 . Go to Androidsdk\platform-tools on PC/Laptop

Step 2 :

Connect your device via USB and run:

adb kill-server

then run

adb tcpip 5555

you will see below message...

daemon not running. starting it now on port 5037 * daemon started successfully * restarting in TCP mode port: 5555

Step3:

Now open new CMD window,

Go to Androidsdk\platform-tools

Now run

adb connect xx.xx.xx.xx:5555 (xx.xx.xx.xx is device IP)

Step4: Disconnect your device from USB and it will work as if connected from your Android studio.

Determining if Swift dictionary contains key and obtaining any of its values

Why not simply check for dict.keys.contains(key)? Checking for dict[key] != nil will not work in cases where the value is nil. As with a dictionary [String: String?] for example.

function is not defined error in Python

Yes, but in what file is pyth_test's definition declared in? Is it also located before it's called?

Edit:

To put it into perspective, create a file called test.py with the following contents:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1,2)

Now run the following command:

python test.py

You should see the output you desire. Now if you are in an interactive session, it should go like this:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 

I hope this explains how the declaration works.


To give you an idea of how the layout works, we'll create a few files. Create a new empty folder to keep things clean with the following:

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 

program.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)

Now if you run:

python program.py

It will print out 3. Now to explain what went wrong, let's modify our program this way:

# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

Now let's see what happens:

$ python program.py 
Traceback (most recent call last):
  File "program.py", line 3, in <module>
    pyth_test(1,2)
NameError: name 'pyth_test' is not defined

As noted, python cannot find the module for the reasons outlined above. For that reason, you should keep your declarations at top.

Now then, if we run the interactive python session:

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3

The same process applies. Now, package importing isn't all that simple, so I recommend you look into how modules work with Python. I hope this helps and good luck with your learnings!

how to release localhost from Error: listen EADDRINUSE

When you get an error

Error: listen EADDRINUSE

Open command prompt and type the following instructions:

netstat -a -o | grep 8080
taskkill /F /PID** <*ur Process ID no*>

after that restart phone gap interface.

If you want to know which process ID phonegap is using, open TASK MANAGER and look at the Column heading PID and find the PID no.

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

"title" is widely implemented in browsers. Try:

<a href="#" title="hello">asf</a>

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

How to find top three highest salary in emp table in oracle?

    select empno,salary from emp e
     where 3 > ( Select count(salary) from emp
      where e.salary < salary )


Another way :

    select * from
    (
    select empno,salary,
    Rank() over(order by salary desc) as rank from emp )
    where Rank <= 3;

Another Way :

    select * from
    (
    select empno,salary from emp
    order by salary desc
    )
    where rownum <= 3;

How can I start PostgreSQL on Windows?

pg_ctl is a command line (Windows) program not a SQL statement. You need to do that from a cmd.exe. Or use net start postgresql-9.5

enter image description here


If you have installed Postgres through the installer, you should start the Windows service instead of running pg_ctl manually, e.g. using:

net start postgresql-9.5

Note that the name of the service might be different in your installation. Another option is to start the service through the Windows control panel


I have used the pgAdmin II tool to create a database called company

Which means that Postgres is already running, so I don't understand why you think you need to do that again. Especially because the installer typically sets the service to start automatically when Windows is started.


The reason you are not seeing any result is that psql requires every SQL command to be terminated with ; in your case it's simply waiting for you to finish the statement.

See here for more details: In psql, why do some commands have no effect?

How to include an HTML page into another HTML page without frame/iframe?

$.get("file.html", function(data){
    $("#div").html(data);
});

GitHub Error Message - Permission denied (publickey)

I found this page while searching for a solution to a similar error message using git pull on a remote host:

$ git pull
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I was connected from my local machine to the remote host via ssh -AY remote_hostname. This is not a solution to OP's question, but useful for others who come across this page, so posting it here.

Note that in my case, git pull works fine on my local machine (that is, ssh key had been set up, and added to the GitHub account, etc). I solved my issue by adding this to ~/.ssh/config on my laptop:

Host *
     ForwardAgent yes

I then re-connected to the remote host with ssh -AY remote_hostname, and git pull now worked. The change in the config enables to forward my ssh keypair from my local machine to any host. The -A option to ssh actually forwards it in that ssh session. See more details here.

PDF Editing in PHP?

The PDF/pdflib extension documentation in PHP is sparse (something that has been noted in bugs.php.net) - I reccommend you use the Zend library.

Efficient way to insert a number into a sorted array of numbers?

Here's a comparison of four different algorithms for accomplishing this: https://jsperf.com/sorted-array-insert-comparison/1

Algorithms

Naive is always horrible. It seems for small array sizes, the other three dont differ too much, but for larger arrays, the last 2 outperform the simple linear approach.

Getting the difference between two repositories

You can add other repo first as a remote to your current repo:

git remote add other_name PATH_TO_OTHER_REPO

then fetch brach from that remote:

git fetch other_name branch_name:branch_name

this creates that branch as a new branch in your current repo, then you can diff that branch with any of your branches, for example, to compare current branch against new branch(branch_name):

git diff branch_name

Twitter Bootstrap hide css class and jQuery

I agree with dfsq if all you want to do is show the button. If you want to switch between hiding and showing the button however, it is easier to use:

$("#buttonEditComment").toggleClass("hide");

How to convert wstring into string?

At the time of writing this answer, the number one google search for "convert string wstring" would land you on this page. My answer shows how to convert string to wstring, although this is NOT the actual question, and I should probably delete this answer but that is considered bad form. You may want to jump to this StackOverflow answer, which is now higher ranked than this page.


Here's a way to combining string, wstring and mixed string constants to wstring. Use the wstringstream class.

#include <sstream>

std::string narrow = "narrow";
std::wstring wide = "wide";

std::wstringstream cls;
cls << " abc " << narrow.c_str() << L" def " << wide.c_str();
std::wstring total= cls.str();

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)

How to print a list in Python "nicely"

You mean something like...:

>>> print L
['this', 'is', 'a', ['and', 'a', 'sublist', 'too'], 'list', 'including', 'many', 'words', 'in', 'it']
>>> import pprint
>>> pprint.pprint(L)
['this',
 'is',
 'a',
 ['and', 'a', 'sublist', 'too'],
 'list',
 'including',
 'many',
 'words',
 'in',
 'it']
>>> 

...? From your cursory description, standard library module pprint is the first thing that comes to mind; however, if you can describe example inputs and outputs (so that one doesn't have to learn PHP in order to help you;-), it may be possible for us to offer more specific help!

How can I access Oracle from Python?

import cx_Oracle
   dsn_tns = cx_Oracle.makedsn('host', 'port', service_name='give service name') 
   conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns) 
   c = conn.cursor()
   c.execute('select count(*) from schema.table_name')
for row in c:
   print row
conn.close()

Note :

  1. In (dsn_tns) if needed, place an 'r' before any parameter in order to address any special character such as '\'.

  2. In (conn) if needed, place an 'r' before any parameter in order to address any special character such as '\'. For example, if your user name contains '\', you'll need to place 'r' before the user name: user=r'User Name' or password=r'password'

  3. use triple quotes if you want to spread your query across multiple lines.

How to determine the version of the C++ standard used by the compiler?

Use __cplusplus as suggested. Only one note for Microsoft compiler, use Zc:__cplusplus compiler switch to enable __cplusplus

Source https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/

ModelState.IsValid == false, why?

If you remove the check for the ModelsState.IsValid and let it error, if you copy this line ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors and paste it in the watch section in Visual Studio it will give you exactly what the error is. Saves a lot of time checking where the error is.

WRONGTYPE Operation against a key holding the wrong kind of value php

This error means that the value indexed by the key "l_messages" is not of type hash, but rather something else. You've probably set it to that other value earlier in your code. Try various other value-getter commands, starting with GET, to see which one works and you'll know what type is actually here.

How to specify legend position in matplotlib in graph coordinates

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Let us create a sample database with a table by the below script:

CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE dbo.tblTest (Id INT, Name NVARCHAR(50))

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a tblTest Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

The above query checks the existence of the tblTest table across all the schemas in the current database. Instead of this if you want to check the existence of the Table in a specified Schema and the Specified Database then we can write the above query as below:

IF EXISTS (SELECT * FROM Test.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = N'dbo'  AND TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

Pros of this Approach: INFORMATION_SCHEMA views are portable across different RDBMS systems, so porting to different RDBMS doesn’t require any change.

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a tblTest Table exists in the current database.

IF OBJECT_ID(N'dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Specifying the Database Name and Schema Name parts for the Table Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the table in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that even though the current database is MASTER database, we can check the existence of the tblTest table in the dbo schema in the Test database.

USE MASTER
GO
IF OBJECT_ID(N'Test.dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Pros: Easy to remember. One other notable point to mention about OBJECT_ID() function is: it provides an option to check the existence of the Temporary Table which is created in the current connection context. All other Approaches checks the existence of the Temporary Table created across all the connections context instead of just the current connection context. Below query shows how to check the existence of a Temporary Table using OBJECT_ID() function:

CREATE TABLE #TempTable(ID INT)
GO
IF OBJECT_ID(N'TempDB.dbo.#TempTable', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END
GO

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.tblTest') AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'tblTest' AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Sys.Tables catalog view inherits the rows from the Sys.Objects catalog view, Sys.objects catalog view is referred to as base view where as sys.Tables is referred to as derived view. Sys.Tables will return the rows only for the Table objects whereas Sys.Object view apart from returning the rows for table objects, it returns rows for the objects like: stored procedure, views etc.

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per [Microsoft BOL][1] link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'tblTest' AND xtype = N'U')
BEGIN
  PRINT 'Table Exists'
END

Reference: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

@font-face src: local - How to use the local font if the user already has it?

If you want to check for local files first do:

@font-face {
font-family: 'Green Sans Web';
src:
    local('Green Web'),
    local('GreenWeb-Regular'),
    url('GreenWeb.ttf');
}

There is a more elaborate description of what to do here.

cannot resolve symbol javafx.application in IntelliJ Idea IDE

As indicated here, JavaFX is no longer included in openjdk.

So check, if you have <Java SDK root>/jre/lib/ext/jfxrt.jar on your classpath under Project Structure -> SDKs -> 1.x -> Classpath? If not, that could be why. Try adding it and see if that fixes your issue, e.g. on Ubuntu, install then openjfx package with sudo apt-get install openjfx.

Calculating and printing the nth prime number

int counter = 0;

for(int i = 1; ; i++) {
    if(isPrime(i)
        counter++;

    if(counter == userInput) {
        print(i);
        break;
    }
}

Edit: Your prime function could use a bit of work. Here's one that I have written:

private static boolean isPrime(long n) {
    if(n < 2)
        return false;

    for (long i = 2; i * i <= n; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}

Note - you only need to go up to sqrt(n) when looking at factors, hence the i * i <= n

JavaScript: replace last occurrence of text in a string

I know this is silly, but I'm feeling creative this morning:

'one two, one three, one four, one'
.split(' ') // array: ["one", "two,", "one", "three,", "one", "four,", "one"]
.reverse() // array: ["one", "four,", "one", "three,", "one", "two,", "one"]
.join(' ') // string: "one four, one three, one two, one"
.replace(/one/, 'finish') // string: "finish four, one three, one two, one"
.split(' ') // array: ["finish", "four,", "one", "three,", "one", "two,", "one"]
.reverse() // array: ["one", "two,", "one", "three,", "one", "four,", "finish"]
.join(' '); // final string: "one two, one three, one four, finish"

So really, all you'd need to do is add this function to the String prototype:

String.prototype.replaceLast = function (what, replacement) {
    return this.split(' ').reverse().join(' ').replace(new RegExp(what), replacement).split(' ').reverse().join(' ');
};

Then run it like so: str = str.replaceLast('one', 'finish');

One limitation you should know is that, since the function is splitting by space, you probably can't find/replace anything with a space.

Actually, now that I think of it, you could get around the 'space' problem by splitting with an empty token.

String.prototype.reverse = function () {
    return this.split('').reverse().join('');
};

String.prototype.replaceLast = function (what, replacement) {
    return this.reverse().replace(new RegExp(what.reverse()), replacement.reverse()).reverse();
};

str = str.replaceLast('one', 'finish');

jQuery Refresh/Reload Page if Ajax Success after time

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...

How to change a TextView's style at runtime

Programmatically: Run time

You can do programmatically using setTypeface():

textView.setTypeface(null, Typeface.NORMAL);      // for Normal Text
textView.setTypeface(null, Typeface.BOLD);        // for Bold only
textView.setTypeface(null, Typeface.ITALIC);      // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic

XML: Design Time

You can set in XML as well:

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

Hope this will help

Summved

Get random boolean in Java

Have you tried looking at the Java Documentation?

Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence ... the values true and false are produced with (approximately) equal probability.

For example:

import java.util.Random;

Random random = new Random();
random.nextBoolean();

C++ Singleton design pattern

Simple singleton class, This must be your header class file

#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H

class SingletonClass
{
    public:
        static SingletonClass* Instance()
        {
           static SingletonClass* instance = new SingletonClass();
           return instance;
        }

        void Relocate(int X, int Y, int Z);

    private:
        SingletonClass();
        ~SingletonClass();
};

#define sSingletonClass SingletonClass::Instance()

#endif

Access your singleton like this:

sSingletonClass->Relocate(1, 2, 5);

Base64 encoding and decoding in oracle

All the previous posts are correct. There's more than one way to skin a cat. Here is another way to do the same thing: (just replace "what_ever_you_want_to_convert" with your string and run it in Oracle:

    set serveroutput on;
    DECLARE
    v_str VARCHAR2(1000);
    BEGIN
    --Create encoded value
    v_str := utl_encode.text_encode
    ('what_ever_you_want_to_convert','WE8ISO8859P1', UTL_ENCODE.BASE64);
    dbms_output.put_line(v_str);
    --Decode the value..
    v_str := utl_encode.text_decode
    (v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
    dbms_output.put_line(v_str);
    END;
    /

source

Something better than .NET Reflector?

9Rays used to have a decompiler, but I haven't checked in a while. It was not free, I remember...

There is also a new one (at least for me) named Dis#.

Full Screen Theme for AppCompat

<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>

Form onSubmit determine which submit button was pressed

First Suggestion:

Create a Javascript Variable that will reference the button clicked. Lets call it buttonIndex

<input type="submit" onclick="buttonIndex=0;" name="save" value="Save" />
<input type="submit" onclick="buttonIndex=1;" name="saveAndAdd" value="Save and add another" />

Now, you can access that value. 0 means the save button was clicked, 1 means the saveAndAdd Button was clicked.

Second Suggestion

The way I would handle this is to create two JS functions that handle each of the two buttons.

First, make sure your form has a valid ID. For this example, I'll say the ID is "myForm"

change

<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />

to

<input type="submit" onclick="submitFunc();return(false);" name="save" value="Save" />
<input type="submit" onclick="submitAndAddFunc();return(false);" name="saveAndAdd" value="Save and add 

the return(false) will prevent your form submission from actually processing, and call your custom functions, where you can submit the form later on.

Then your functions will work something like this...

function submitFunc(){
    // Do some asyncrhnous stuff, that will later on submit the form
    if (okToSubmit) {
        document.getElementById('myForm').submit();
    }
}
function submitAndAddFunc(){
    // Do some asyncrhnous stuff, that will later on submit the form
    if (okToSubmit) {
        document.getElementById('myForm').submit();
    }
}

NoClassDefFoundError in Java: com/google/common/base/Function

I got the same error, but it was resolved if you add the libraries of selenium (again if you haven't), if you are using INTELIJ

project>projectStructure>Module>+>add the selenium jars (both from lib folder and outside ones.).

Same needs to be done for other IDE's as well, like eclipse.

ImportError: No module named PyQt4.QtCore

I had the same issue when uninstalled my Python27 and re-installed it.

I downloaded the sip-4.15.5 and PyQt-win-gpl-4.10.4 and installed/configured both of them. it still gives 'ImportError: No module named PyQt4.QtCore'. I tried to move the files/folders in Lib to make it looked 'have' but not working.

in fact, jut download the Windows 64 bit installer for a suitable Python version (my case) from http://www.riverbankcomputing.co.uk/software/pyqt/download and installed it, will do the job.

* March 2017 update *

The given link says, Binary installers for Windows are no longer provided.

See cgohlke's answer at, PyQt4 and 64-bit python.

  1. Download the .whl file at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyqt4.
  2. Use pip to install the downloaded .whl file.

How to implement "confirmation" dialog in Jquery UI dialog?

I found the answer by Paul didn't quite work as the way he was setting the options AFTER the dialog was instantiated on the click event were incorrect. Here is my code which was working. I've not tailored it to match Paul's example but it's only a cat's whisker's difference in terms of some elements are named differently. You should be able to work it out. The correction is in the setter of the dialog option for the buttons on the click event.

$(document).ready(function() {

    $("#dialog").dialog({
        modal: true,
        bgiframe: true,
        width: 500,
        height: 200,
        autoOpen: false
    });


    $(".lb").click(function(e) {

        e.preventDefault();
        var theHREF = $(this).attr("href");

        $("#dialog").dialog('option', 'buttons', {
            "Confirm" : function() {
                window.location.href = theHREF;
            },
            "Cancel" : function() {
                $(this).dialog("close");
            }
        });

        $("#dialog").dialog("open");

    });

});

Hope this helps someone else as this post originally got me down the right track I thought I'd better post the correction.

What is the difference between a HashMap and a TreeMap?

TreeMap is an example of a SortedMap, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.

HashMap on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap, you can't be sure what order they will be in.

HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.

How do I use PHP namespaces with autoload?

I see that the autoload functions only receive the "full" classname - with all the namespaces preceeding it - in the following two cases:

[a] $a = new The\Full\Namespace\CoolClass();

[b] use The\Full\Namespace as SomeNamespace; (at the top of your source file) followed by $a = new SomeNamespace\CoolClass();

I see that the autoload functions DO NOT receive the full classname in the following case:

[c] use The\Full\Namespace; (at the top of your source file) followed by $a = new CoolClass();

UPDATE: [c] is a mistake and isn't how namespaces work anyway. I can report that, instead of [c], the following two cases also work well:

[d] use The\Full\Namespace; (at the top of your source file) followed by $a = new Namespace\CoolClass();

[e] use The\Full\Namespace\CoolClass; (at the top of your source file) followed by $a = new CoolClass();

Hope this helps.

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

I had this issue and the other fixes on this page didn't fully solve the problem.

What did solve the problem was going in to my system environment variables and looking at the PATH - I had uninstalled Python 3 but the old path to the Python 3 folder was still there. I'm running only Python 2 on my PC and used Python 2 to install pip.

Deleting the references to the nonexistent Python 3 folders from PATH in addition to upgrading to the latest version of pip fixed the issue.

Best practice for storing and protecting private API keys in applications

Few ideas, in my opinion only first one gives some guarantee:

  1. Keep your secrets on some server on internet, and when needed just grab them and use. If user is about to use dropbox then nothing stops you from making request to your site and get your secret key.

  2. Put your secrets in jni code, add some variable code to make your libraries bigger and more difficult to decompile. You might also split key string in few parts and keep them in various places.

  3. use obfuscator, also put in code hashed secret and later on unhash it when needed to use.

  4. Put your secret key as last pixels of one of your image in assets. Then when needed read it in your code. Obfuscating your code should help hide code that will read it.

If you want to have a quick look at how easy it is to read you apk code then grab APKAnalyser:

http://developer.sonymobile.com/knowledge-base/tool-guides/analyse-your-apks-with-apkanalyser/

How can I access my localhost from my Android device?

On linux use ip addr instead of ifconfig since ifconfig is deprecated for many years and not installed by default in recent distros

How to run an external program, e.g. notepad, using hyperlink?

Sorry this answer sucks, but you can't launch an just any external application via a click, as this would be a serious security issue, this functionality isn't available in HTML or javascript. Think of just launching cmd.exe with args...you want to launch WinMerge with arguments, but you can see the security problems introduced by allowing this for anything.

The only possibly viable exception I can think of would be a protocol handler (since these are explicitly defined handlers), like winmerge://, though the best way to pass 2 file parameters I'm not sure of, if it's an option it's worth looking into, but I'm not sure what you are or are not allowed to do to the client, so this may be a non-starter solution.

Count work days between two dates

I found the below TSQL a fairly elegant solution (I don't have permissions to run functions). I found the DATEDIFF ignores DATEFIRST and I wanted my first day of the week to be a Monday. I also wanted the first working day to be set a zero and if it falls on a weekend Monday will be a zero. This may help someone who has a slightly different requirement :)

It does not handle bank holidays

SET DATEFIRST 1
SELECT
,(DATEDIFF(DD,  [StartDate], [EndDate]))        
-(DATEDIFF(wk,  [StartDate], [EndDate]))        
-(DATEDIFF(wk, DATEADD(dd,-@@DATEFIRST,[StartDate]), DATEADD(dd,-@@DATEFIRST,[EndDate]))) AS [WorkingDays] 
FROM /*Your Table*/ 

How to change the docker image installation directory?

Copy-and-paste version of the winner answer :)

Create this file with only this content:

$ sudo vi /etc/docker/daemon.json

  {
      "graph": "/my-docker-images"
  }

Tested on Ubuntu 16.04.2 LTS in docker 1.12.6

Access key value from Web.config in Razor View-MVC3 ASP.NET

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

Serialize form data to JSON

I know this doesn't meet the helper function requirement, but the way I've done this is using jQuery's $.each() method

var loginForm = $('.login').serializeArray();
var loginFormObject = {};
$.each(loginForm,
    function(i, v) {
        loginFormObject[v.name] = v.value;
    });

Then I can pass loginFormObject to my backend, or you could create a userobject and save() it in backbone as well.

How do you properly determine the current script directory?

This should work in most cases:

import os,sys
dirname=os.path.dirname(os.path.realpath(sys.argv[0]))

SQL query to group by day

For oracle you can

group by trunc(created);

as this truncates the created datetime to the previous midnight.

Another option is to

group by to_char(created, 'DD.MM.YYYY');

which achieves the same result, but may be slower as it requires a type conversion.

Add back button to action bar

You'll need to check menuItem.getItemId() against android.R.id.home in the onOptionsItemSelected method

Duplicate of Android Sherlock ActionBar Up button

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

Code line wrapping - how to handle long lines

IMHO this is the best way to write your line :

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

This way the increased indentation without any braces can help you to see that the code was just splited because the line was too long. And instead of 4 spaces, 8 will make it clearer.

How to clear a data grid view

You can assign the datasource as null of your data grid and then rebind it.

dg.DataSource = null;
dg.DataBind();

use jQuery's find() on JSON object

This works for me on [{"id":"data"},{"id":"data"}]

function getObjects(obj, key, val) 
{
    var newObj = false; 
    $.each(obj, function()
    {
        var testObject = this; 
        $.each(testObject, function(k,v)
        {
            //alert(k);
            if(val == v && k == key)
            {
                newObj = testObject;
            }
        });
    });

    return newObj;
}

C# Version Of SQL LIKE

As a late but proper answer:

The closest thing there is to a SQL-Like function in C-Sharp is the implementation of a SQL-Like function in C#.

You can rip it out of http://code.google.com/p/csharp-sqlite/source/checkout
[root]/csharp-sqlite/Community.CsharpSqlite/src/func_c.cs

    /*
** Implementation of the like() SQL function.  This function implements
** the build-in LIKE operator.  The first argument to the function is the
** pattern and the second argument is the string.  So, the SQL statements:
**
**       A LIKE B
**
** is implemented as like(B,A).
**
** This same function (with a different compareInfo structure) computes
** the GLOB operator.
*/
    static void likeFunc(
    sqlite3_context context,
    int argc,
    sqlite3_value[] argv
    )
    {
      string zA, zB;
      u32 escape = 0;
      int nPat;
      sqlite3 db = sqlite3_context_db_handle( context );

      zB = sqlite3_value_text( argv[0] );
      zA = sqlite3_value_text( argv[1] );

      /* Limit the length of the LIKE or GLOB pattern to avoid problems
      ** of deep recursion and N*N behavior in patternCompare().
      */
      nPat = sqlite3_value_bytes( argv[0] );
      testcase( nPat == db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
      testcase( nPat == db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] + 1 );
      if ( nPat > db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] )
      {
        sqlite3_result_error( context, "LIKE or GLOB pattern too complex", -1 );
        return;
      }
      //Debug.Assert( zB == sqlite3_value_text( argv[0] ) );  /* Encoding did not change */

      if ( argc == 3 )
      {
        /* The escape character string must consist of a single UTF-8 character.
        ** Otherwise, return an error.
        */
        string zEsc = sqlite3_value_text( argv[2] );
        if ( zEsc == null )
          return;
        if ( sqlite3Utf8CharLen( zEsc, -1 ) != 1 )
        {
          sqlite3_result_error( context,
          "ESCAPE expression must be a single character", -1 );
          return;
        }
        escape = sqlite3Utf8Read( zEsc, ref zEsc );
      }
      if ( zA != null && zB != null )
      {
        compareInfo pInfo = (compareInfo)sqlite3_user_data( context );
#if SQLITE_TEST
#if !TCLSH
        sqlite3_like_count++;
#else
        sqlite3_like_count.iValue++;
#endif
#endif
        sqlite3_result_int( context, patternCompare( zB, zA, pInfo, escape ) ? 1 : 0 );
      }
    }




    /*
    ** Compare two UTF-8 strings for equality where the first string can
    ** potentially be a "glob" expression.  Return true (1) if they
    ** are the same and false (0) if they are different.
    **
    ** Globbing rules:
    **
    **      '*'       Matches any sequence of zero or more characters.
    **
    **      '?'       Matches exactly one character.
    **
    **     [...]      Matches one character from the enclosed list of
    **                characters.
    **
    **     [^...]     Matches one character not in the enclosed list.
    **
    ** With the [...] and [^...] matching, a ']' character can be included
    ** in the list by making it the first character after '[' or '^'.  A
    ** range of characters can be specified using '-'.  Example:
    ** "[a-z]" matches any single lower-case letter.  To match a '-', make
    ** it the last character in the list.
    **
    ** This routine is usually quick, but can be N**2 in the worst case.
    **
    ** Hints: to match '*' or '?', put them in "[]".  Like this:
    **
    **         abc[*]xyz        Matches "abc*xyz" only
    */
    static bool patternCompare(
    string zPattern,            /* The glob pattern */
    string zString,             /* The string to compare against the glob */
    compareInfo pInfo,          /* Information about how to do the compare */
    u32 esc                     /* The escape character */
    )
    {
      u32 c, c2;
      int invert;
      int seen;
      int matchOne = (int)pInfo.matchOne;
      int matchAll = (int)pInfo.matchAll;
      int matchSet = (int)pInfo.matchSet;
      bool noCase = pInfo.noCase;
      bool prevEscape = false;     /* True if the previous character was 'escape' */
      string inPattern = zPattern; //Entered Pattern

      while ( ( c = sqlite3Utf8Read( zPattern, ref zPattern ) ) != 0 )
      {
        if ( !prevEscape && c == matchAll )
        {
          while ( ( c = sqlite3Utf8Read( zPattern, ref zPattern ) ) == matchAll
          || c == matchOne )
          {
            if ( c == matchOne && sqlite3Utf8Read( zString, ref zString ) == 0 )
            {
              return false;
            }
          }
          if ( c == 0 )
          {
            return true;
          }
          else if ( c == esc )
          {
            c = sqlite3Utf8Read( zPattern, ref zPattern );
            if ( c == 0 )
            {
              return false;
            }
          }
          else if ( c == matchSet )
          {
            Debug.Assert( esc == 0 );         /* This is GLOB, not LIKE */
            Debug.Assert( matchSet < 0x80 );  /* '[' is a single-byte character */
            int len = 0;
            while ( len < zString.Length && patternCompare( inPattern.Substring( inPattern.Length - zPattern.Length - 1 ), zString.Substring( len ), pInfo, esc ) == false )
            {
              SQLITE_SKIP_UTF8( zString, ref len );
            }
            return len < zString.Length;
          }
          while ( ( c2 = sqlite3Utf8Read( zString, ref zString ) ) != 0 )
          {
            if ( noCase )
            {
               if( 0==((c2)&~0x7f) )
                c2 = (u32)sqlite3UpperToLower[c2]; //GlogUpperToLower(c2);
               if ( 0 == ( ( c ) & ~0x7f ) )
                 c = (u32)sqlite3UpperToLower[c]; //GlogUpperToLower(c);
              while ( c2 != 0 && c2 != c )
              {
                c2 = sqlite3Utf8Read( zString, ref zString );
                if ( 0 == ( ( c2 ) & ~0x7f ) )
                  c2 = (u32)sqlite3UpperToLower[c2]; //GlogUpperToLower(c2);
              }
            }
            else
            {
              while ( c2 != 0 && c2 != c )
              {
                c2 = sqlite3Utf8Read( zString, ref zString );
              }
            }
            if ( c2 == 0 )
              return false;
            if ( patternCompare( zPattern, zString, pInfo, esc ) )
              return true;
          }
          return false;
        }
        else if ( !prevEscape && c == matchOne )
        {
          if ( sqlite3Utf8Read( zString, ref zString ) == 0 )
          {
            return false;
          }
        }
        else if ( c == matchSet )
        {
          u32 prior_c = 0;
          Debug.Assert( esc == 0 );    /* This only occurs for GLOB, not LIKE */
          seen = 0;
          invert = 0;
          c = sqlite3Utf8Read( zString, ref zString );
          if ( c == 0 )
            return false;
          c2 = sqlite3Utf8Read( zPattern, ref zPattern );
          if ( c2 == '^' )
          {
            invert = 1;
            c2 = sqlite3Utf8Read( zPattern, ref zPattern );
          }
          if ( c2 == ']' )
          {
            if ( c == ']' )
              seen = 1;
            c2 = sqlite3Utf8Read( zPattern, ref zPattern );
          }
          while ( c2 != 0 && c2 != ']' )
          {
            if ( c2 == '-' && zPattern[0] != ']' && zPattern[0] != 0 && prior_c > 0 )
            {
              c2 = sqlite3Utf8Read( zPattern, ref zPattern );
              if ( c >= prior_c && c <= c2 )
                seen = 1;
              prior_c = 0;
            }
            else
            {
              if ( c == c2 )
              {
                seen = 1;
              }
              prior_c = c2;
            }
            c2 = sqlite3Utf8Read( zPattern, ref zPattern );
          }
          if ( c2 == 0 || ( seen ^ invert ) == 0 )
          {
            return false;
          }
        }
        else if ( esc == c && !prevEscape )
        {
          prevEscape = true;
        }
        else
        {
          c2 = sqlite3Utf8Read( zString, ref zString );
          if ( noCase )
          {
            if ( c < 0x80 )
              c = (u32)sqlite3UpperToLower[c]; //GlogUpperToLower(c);
            if ( c2 < 0x80 )
              c2 = (u32)sqlite3UpperToLower[c2]; //GlogUpperToLower(c2);
          }
          if ( c != c2 )
          {
            return false;
          }
          prevEscape = false;
        }
      }
      return zString.Length == 0;
    }

decimal vs double! - Which one should I use and when?

For money: decimal. It costs a little more memory, but doesn't have rounding troubles like double sometimes has.

error 1265. Data truncated for column when trying to load data from txt file

I had this issue when trying to convert an existing varchar column to enum. For me the issue was that there were existing values for that column that were not part of the enum's list of accepted values. So if your enum will only allow values, say ('dog', 'cat') but there is a row with bird in your table, the MODIFY COLUMN will fail with this error.

Iterate through a C array

It depends. If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one).

If it's a static array, you can sizeof it's size/the size of one element. For example:

int array[10], array_size;
...
array_size = sizeof(array)/sizeof(int);

Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer.

Hope it helps.

std::vector versus std::array in C++

Using the std::vector<T> class:

  • ...is just as fast as using built-in arrays, assuming you are doing only the things built-in arrays allow you to do (read and write to existing elements).

  • ...automatically resizes when new elements are inserted.

  • ...allows you to insert new elements at the beginning or in the middle of the vector, automatically "shifting" the rest of the elements "up"( does that make sense?). It allows you to remove elements anywhere in the std::vector, too, automatically shifting the rest of the elements down.

  • ...allows you to perform a range-checked read with the at() method (you can always use the indexers [] if you don't want this check to be performed).

There are two three main caveats to using std::vector<T>:

  1. You don't have reliable access to the underlying pointer, which may be an issue if you are dealing with third-party functions that demand the address of an array.

  2. The std::vector<bool> class is silly. It's implemented as a condensed bitfield, not as an array. Avoid it if you want an array of bools!

  3. During usage, std::vector<T>s are going to be a bit larger than a C++ array with the same number of elements. This is because they need to keep track of a small amount of other information, such as their current size, and because whenever std::vector<T>s resize, they reserve more space then they need. This is to prevent them from having to resize every time a new element is inserted. This behavior can be changed by providing a custom allocator, but I never felt the need to do that!


Edit: After reading Zud's reply to the question, I felt I should add this:

The std::array<T> class is not the same as a C++ array. std::array<T> is a very thin wrapper around C++ arrays, with the primary purpose of hiding the pointer from the user of the class (in C++, arrays are implicitly cast as pointers, often to dismaying effect). The std::array<T> class also stores its size (length), which can be very useful.

What's the difference between the Window.Loaded and Window.ContentRendered events

I think there is little difference between the two events. To understand this, I created a simple example to manipulation:

XAML

<Window x:Class="LoadedAndContentRendered.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Name="MyWindow"
        Title="MainWindow" Height="1000" Width="525"
        WindowStartupLocation="CenterScreen"
        ContentRendered="Window_ContentRendered"     
        Loaded="Window_Loaded">

    <Grid Name="RootGrid">        
    </Grid>
</Window>

Code behind

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered");
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded");
}   

In this case the message Loaded appears the first after the message ContentRendered. This confirms the information in the documentation.

In general, in WPF the Loaded event fires if the element:

is laid out, rendered, and ready for interaction.

Since in WPF the Window is the same element, but it should be generally content that is arranged in a root panel (for example: Grid). Therefore, to monitor the content of the Window and created an ContentRendered event. Remarks from MSDN:

If the window has no content, this event is not raised.

That is, if we create a Window:

<Window x:Class="LoadedAndContentRendered.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Name="MyWindow"        
    ContentRendered="Window_ContentRendered" 
    Loaded="Window_Loaded" />

It will only works Loaded event.

With regard to access to the elements in the Window, they work the same way. Let's create a Label in the main Grid of Window. In both cases we have successfully received access to Width:

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());
}   

As for the Styles and Templates, at this stage they are successfully applied, and in these events we will be able to access them.

For example, we want to add a Button:

private void Window_ContentRendered(object sender, EventArgs e)
{
    MessageBox.Show("ContentRendered: " + SampleLabel.Width.ToString());

    Button b1 = new Button();
    b1.Content = "ContentRendered Button";
    RootGrid.Children.Add(b1);
    b1.Height = 25;
    b1.Width = 200;
    b1.HorizontalAlignment = HorizontalAlignment.Right;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Loaded: " + SampleLabel.Width.ToString());

    Button b1 = new Button();
    b1.Content = "Loaded Button";
    RootGrid.Children.Add(b1);
    b1.Height = 25;
    b1.Width = 200;
    b1.HorizontalAlignment = HorizontalAlignment.Left;
}

In the case of Loaded event, Button to add to Grid immediately at the appearance of the Window. In the case of ContentRendered event, Button to add to Grid after all its content will appear.

Therefore, if you want to add items or changes before load Window you must use the Loaded event. If you want to do the operations associated with the content of Window such as taking screenshots you will need to use an event ContentRendered.

Event when window.location.href changes

popstate event:

The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)

So, listening to popstate event and sending a popstate event when using history.pushState() should be enough to take action on href change:

window.addEventListener('popstate', listener);

const pushUrl = (href) => {
  history.pushState({}, '', href);
  window.dispatchEvent(new Event('popstate'));
};

XPath test if node value is number

Test the value against NaN:

<xsl:if test="string(number(myNode)) != 'NaN'">
    <!-- myNode is a number -->
</xsl:if>

This is a shorter version (thanks @Alejandro):

<xsl:if test="number(myNode) = myNode">
    <!-- myNode is a number -->
</xsl:if>

Capture event onclose browser

http://docs.jquery.com/Events/unload#fn

jQuery:

$(window).unload( function () { alert("Bye now!"); } );

or javascript:

window.onunload = function(){alert("Bye now!");}

Does C# have a String Tokenizer like Java's?

_words = new List<string>(YourText.ToLower().Trim('\n', '\r').Split(' ').
            Select(x => new string(x.Where(Char.IsLetter).ToArray()))); 

Or

_words = new List<string>(YourText.Trim('\n', '\r').Split(' ').
            Select(x => new string(x.Where(Char.IsLetterOrDigit).ToArray()))); 

InputStream from a URL

Your original code uses FileInputStream, which is for accessing file system hosted files.

The constructor you used will attempt to locate a file named a.txt in the www.somewebsite.com subfolder of the current working directory (the value of system property user.dir). The name you provide is resolved to a file using the File class.

URL objects are the generic way to solve this. You can use URLs to access local files but also network hosted resources. The URL class supports the file:// protocol besides http:// or https:// so you're good to go.

MySQL Select all columns from one table and some from another table

Using alias for referencing the tables to get the columns from different tables after joining them.

Select tb1.*, tb2.col1, tb2.col2 from table1 tb1 JOIN table2 tb2 on tb1.Id = tb2.Id

Truncate Two decimal places without rounding

Here is my implementation of TRUNC function

private static object Tranc(List<Expression.Expression> p)
{
    var target = (decimal)p[0].Evaluate();

    // check if formula contains only one argument
    var digits = p.Count > 1
        ? (decimal) p[1].Evaluate()
        : 0;

    return Math.Truncate((double)target * Math.Pow(10, (int)digits)) / Math.Pow(10, (int)digits);
}

MySQL error #1054 - Unknown column in 'Field List'

You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.

Also, I don't think you can use NOW() as default value in OrderDate. Try to use the following:

 OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Example Fiddle

How to get the current date/time in Java

Use:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd::HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));

The print statement will print the time when it is called and not when the SimpleDateFormat was created. So it can be called repeatedly without creating any new objects.

Triangle Draw Method

Use a line algorithm to connect point A with point C, and in an outer loop, let point A wander towards point B with the same line algorithm and with the wandering coordinates, repeat drawing that line. You can probably also include a z delta with which is also incremented iteratively. For the line algorithm, just calculate two or three slopes for the delta change of each coordinate and set one slope to 1 after changing the two others proportionally so they are below 1. This is very important for drawing closed geometrical areas between connected mesh particles. Take a look at the Qt Elastic Nodes example and now imagine drawing triangles between the nodes after stretching this over a skeleton. As long as it will remain online

How to declare a constant in Java

  1. You can use an enum type in Java 5 and onwards for the purpose you have described. It is type safe.
  2. A is an instance variable. (If it has the static modifier, then it becomes a static variable.) Constants just means the value doesn't change.
  3. Instance variables are data members belonging to the object and not the class. Instance variable = Instance field.

If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.

Java 5 and up enum type

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public String toString(){
    return this.color;
  }
}

If you wish to change the value of the enum you have created, provide a mutator method.

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public void setColor(String color){
    this.color = color;
  }

  public String toString(){
    return this.color;
  }
}

Example of accessing:

public static void main(String args[]){
  System.out.println(Color.RED.getColor());

  // or

  System.out.println(Color.GREEN);
}

How to filter by object property in angularJS

You can try this. its working for me 'name' is a property in arr.

repeat="item in (tagWordOptions | filter:{ name: $select.search } ) track by $index

Change default text in input type="file"?

Ok so very simple pure css way of creating your custom input file.

Use labels, but as you know from previous answers, label doesn't invoke onclick function in firefox, may be a bug but doesn't matter with the following.

<label for="file"  class="custom-file-input"><input type="file"  name="file" class="custom-file-input"></input></label>

What you do is style the label to look how you want it to

    .custom-file-input {
        color: transparent;/* This is to take away the browser text for file uploading*/
        /* Carry on with the style you want */
        background: url(../img/doc-o.png);
        background-size: 100%;
        position: absolute;
        width: 200px;
        height: 200px;
        cursor: pointer;
        top: 10%;
        right: 15%;
    }

now simply hide the actual input button, but you cant set it to to visability: hidden

So make in invisible by setting opacity: 0;

input.custom-file-input {
    opacity: 0;
    position: absolute;/*set position to be exactly over your input*/
    left: 0;
    top: 0;
}

now as you might have noticed i have the same class on my label as i do my input field, that is because i want the to both have the same styling, thus where ever you click on the label, you are actually clicking on the invisible input field.

AngularJS Error: $injector:unpr Unknown Provider

I got this error writing a Jasmine unit test. I had the line:

angular.injector(['myModule'])

It needed to be:

angular.injector(['ng', 'myModule'])

Using two values for one switch case statement

With the integration of JEP 325: Switch Expressions (Preview) in JDK-12 early access builds, one can now make use of the new form of the switch label as :-

case text1, text4 -> {
     //blah
} 

or to rephrase the demo from one of the answers, something like :-

public class RephraseDemo {

    public static void main(String[] args) {
        int month = 9;
        int year = 2018;
        int numDays = 0;

        switch (month) {
            case 1, 3, 5, 7, 8, 10, 12 ->{
                numDays = 31;
            }
            case 4, 6, 9, 11 ->{
                numDays = 30;
            }
            case 2 ->{
                if (((year % 4 == 0) &&
                        !(year % 100 == 0))
                        || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
            }
            default ->{
                System.out.println("Invalid month.");

            }
        }
        System.out.println("Number of Days = " + numDays);
    }
}

Here is how you can give it a try - Compile a JDK12 preview feature with Maven

How do you transfer or export SQL Server 2005 data to Excel

If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv

Updating Python on Mac

using Homebrew just do:

brew install python3 && cp /usr/local/bin/python3 /usr/local/bin/python

done :)

Should try...catch go inside or outside a loop?

If you want to catch Exception for each iteration, or check at what iteration Exception is thrown and catch every Exceptions in an itertaion, place try...catch inside the loop. This will not break the loop if Exception occurs and you can catch every Exception in each iteration throughout the loop.

If you want to break the loop and examine the Exception whenever thrown, use try...catch out of the loop. This will break the loop and execute statements after catch (if any).

It all depends on your need. I prefer using try...catch inside the loop while deploying as, if Exception occurs, the results aren't ambiguous and loop will not break and execute completely.

A button to start php script, how?

You could do it in one document if you had a conditional based on params sent over. Eg:

if (isset($_GET['secret_param'])) {
    <run script>
} else {
    <display button>
}

I think the best way though is to have two files.

How can I list all foreign keys referencing a given table in SQL Server?

SELECT
  object_name(parent_object_id),
  object_name(referenced_object_id),
  name 
FROM sys.foreign_keys
WHERE parent_object_id = object_id('Table Name')

Encoding an image file with base64

Borrowing from what Ivo van der Wijk and gnibbler have developed earlier, this is a dynamic solution

import cStringIO
import PIL.Image

image_data = None

def imagetopy(image, output_file):
    with open(image, 'rb') as fin:
        image_data = fin.read()

    with open(output_file, 'w') as fout:
        fout.write('image_data = '+ repr(image_data))

def pytoimage(pyfile):
    pymodule = __import__(pyfile)
    img = PIL.Image.open(cStringIO.StringIO(pymodule.image_data))
    img.show()

if __name__ == '__main__':
    imagetopy('spot.png', 'wishes.py')
    pytoimage('wishes')

You can then decide to compile the output image file with Cython to make it cool. With this method, you can bundle all your graphics into one module.

Replacing last character in a String with java

org.apache.commons.lang3.StringUtils.removeEnd() and org.springframework.util.StringUtils.trimTrailingCharacter() are your friends:

StringUtils.removeEnd(null, *)      = null
StringUtils.removeEnd("", *)        = ""
StringUtils.removeEnd(*, null)      = *
StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "")    = "abc"
    @Test
    public void springStringUtils() {
        String url = "https://some.site/path/";

        String result = org.springframework.util.StringUtils.trimTrailingCharacter(url, '/');

        assertThat(result, equalTo("https://some.site/path"));
    }

An "and" operator for an "if" statement in Bash

Try this:

if [ ${STATUS} -ne 100 -a "${STRING}" = "${VALUE}" ]

or

if [ ${STATUS} -ne 100 ] && [ "${STRING}" = "${VALUE}" ]

What is the difference between Scrum and Agile Development?

At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".

In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.

So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.

How to join multiple collections with $lookup in mongodb

The join feature supported by Mongodb 3.2 and later versions. You can use joins by using aggregate query.
You can do it using below example :

db.users.aggregate([

    // Join with user_info table
    {
        $lookup:{
            from: "userinfo",       // other table name
            localField: "userId",   // name of users table field
            foreignField: "userId", // name of userinfo table field
            as: "user_info"         // alias for userinfo table
        }
    },
    {   $unwind:"$user_info" },     // $unwind used for getting data in object or for one record only

    // Join with user_role table
    {
        $lookup:{
            from: "userrole", 
            localField: "userId", 
            foreignField: "userId",
            as: "user_role"
        }
    },
    {   $unwind:"$user_role" },

    // define some conditions here 
    {
        $match:{
            $and:[{"userName" : "admin"}]
        }
    },

    // define which fields are you want to fetch
    {   
        $project:{
            _id : 1,
            email : 1,
            userName : 1,
            userPhone : "$user_info.phone",
            role : "$user_role.role",
        } 
    }
]);

This will give result like this:

{
    "_id" : ObjectId("5684f3c454b1fd6926c324fd"),
    "email" : "[email protected]",
    "userName" : "admin",
    "userPhone" : "0000000000",
    "role" : "admin"
}

Hope this will help you or someone else.

Thanks

How to access the request body when POSTing using Node.js and Express?

Express 4.0 and above:

$ npm install --save body-parser

And then in your node app:

const bodyParser = require('body-parser');
app.use(bodyParser);

Express 3.0 and below:

Try passing this in your cURL call:

--header "Content-Type: application/json"

and making sure your data is in JSON format:

{"user":"someone"}

Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:

var express = require('express');
var app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(req, res){
    console.dir(req.body);
    res.send("test");
}); 

app.listen(3000);

This other question might also help: How to receive JSON in express node.js POST request?

If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681

PHP Adding 15 minutes to Time value

Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.

// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');

Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:

!g:i:s 12-hour format without leading zeroes on hour

!G:i:s 12-hour format with leading zeroes

Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)

try/catch with InputMismatchException creates infinite loop

To follow debobroto das's answer you can also put after

input.reset();
input.next(); 

I had the same problem and when I tried this. It completely fixed it.

Excel: last character/string match in a string

Just came up with this solution, no VBA needed;

Find the last occurance of "_" in my example;

=IFERROR(FIND(CHAR(1);SUBSTITUTE(A1;"_";CHAR(1);LEN(A1)-LEN(SUBSTITUTE(A1;"_";"")));0)

Explained inside out;

SUBSTITUTE(A1;"_";"") => replace "_" by spaces
LEN( *above* ) => count the chars
LEN(A1)- *above*  => indicates amount of chars replaced (= occurrences of "_")
SUBSTITUTE(A1;"_";CHAR(1); *above* ) => replace the Nth occurence of "_" by CHAR(1) (Nth = amount of chars replaced = the last one)
FIND(CHAR(1); *above* ) => Find the CHAR(1), being the last (replaced) occurance of "_" in our case
IFERROR( *above* ;"0") => in case no chars were found, return "0"

Hope this was helpful.

Is CSS Turing complete?

CSS is not a programming language, so the question of turing-completeness is a meaningless one. If programming extensions are added to CSS such as was the case in IE6 then that new synthesis is a whole different thing.

CSS is merely a description of styles; it does not have any logic, and its structure is flat.

How do I add my new User Control to the Toolbox or a new Winform?

Assuming I understand what you mean:

  1. If your UserControl is in a library you can add this to you Toolbox using

    Toolbox -> right click -> Choose Items -> Browse

    Select your assembly with the UserControl.

  2. If the UserControl is part of your project you only need to build the entire solution. After that, your UserControl should appear in the toolbox.

In general, it is not possible to add a Control from Solution Explorer, only from the Toolbox.

Enter image description here

How to remove an unpushed outgoing commit in Visual Studio?

Try to rebase your local master branch onto your remote/origin master branch and resolve any conflicts in the process.

SVN Repository Search

I do like TRAC - this plugin might be helpful for your task: http://trac-hacks.org/wiki/RepoSearchPlugin

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

jQuery: Check if button is clicked

jQuery(':button').click(function () {
    if (this.id == 'button1') {
        alert('Button 1 was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

EDIT:- This will work for all buttons.

Convert SVG to PNG in Python

Another solution I've just found here How to render a scaled SVG to a QImage?

from PySide.QtSvg import *
from PySide.QtGui import *


def convertSvgToPng(svgFilepath,pngFilepath,width):
    r=QSvgRenderer(svgFilepath)
    height=r.defaultSize().height()*width/r.defaultSize().width()
    i=QImage(width,height,QImage.Format_ARGB32)
    p=QPainter(i)
    r.render(p)
    i.save(pngFilepath)
    p.end()

PySide is easily installed from a binary package in Windows (and I use it for other things so is easy for me).

However, I noticed a few problems when converting country flags from Wikimedia, so perhaps not the most robust svg parser/renderer.

Is there any ASCII character for <br>?

& is a character; &amp; is a HTML character entity for that character.

<br> is an element. Elements don't get character entities.

In contrast to many answers here, \n or &#13; are not equivalent to <br>. The former denotes a line break in text documents. The latter is intended to denote a line break in HTML documents and is doing that by virtue of its default CSS:

br:before { content: "\A"; white-space: pre-line }

A textual line break can be rendered as an HTML line break or can be treated as whitespace, depending on the CSS white-space property.

What version of Python is on my Mac?

Use the which command. It will show you the path

which python

How do I restore a dump file from mysqldump?

./mysql -u <username> -p <password> -h <host-name like localhost> <database-name> < db_dump-file

Best algorithm for detecting cycles in a directed graph

If you can't add a "visited" property to the nodes, use a set (or map) and just add all visited nodes to the set unless they are already in the set. Use a unique key or the address of the objects as the "key".

This also gives you the information about the "root" node of the cyclic dependency which will come in handy when a user has to fix the problem.

Another solution is to try to find the next dependency to execute. For this, you must have some stack where you can remember where you are now and what you need to do next. Check if a dependency is already on this stack before you execute it. If it is, you've found a cycle.

While this might seem to have a complexity of O(N*M) you must remember that the stack has a very limited depth (so N is small) and that M becomes smaller with each dependency that you can check off as "executed" plus you can stop the search when you found a leaf (so you never have to check every node -> M will be small, too).

In MetaMake, I created the graph as a list of lists and then deleted every node as I executed them which naturally cut down the search volume. I never actually had to run an independent check, it all happened automatically during normal execution.

If you need a "test only" mode, just add a "dry-run" flag which disables the execution of the actual jobs.

Select row on click react-table

I found the solution after a few tries, I hope this can help you. Add the following to your <ReactTable> component:

getTrProps={(state, rowInfo) => {
  if (rowInfo && rowInfo.row) {
    return {
      onClick: (e) => {
        this.setState({
          selected: rowInfo.index
        })
      },
      style: {
        background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
        color: rowInfo.index === this.state.selected ? 'white' : 'black'
      }
    }
  }else{
    return {}
  }
}

In your state don't forget to add a null selected value, like:

state = { selected: null }

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.

My example code

$rexpenditure = <<<Expenditure
                  <tr>
                      <td>$row->payment_referencenumber</td>
                      <td>$row->payment_requestdate</td>
                      <td>$row->payment_description</td>
                      <td>$row->payment_fundingsource</td>
                      <td>$row->payment_agencyulo</td>
                      <td>$row->payment_agencyproject</td>
                      <td>$$row->payment_disbustment</td>
                      <td>$row->payment_payeename</td>
                      <td>$row->payment_processpayment</td>
                  </tr>
Expenditure;

It will error if there is a space on PHP 7.0.33.

Accessing SQL Database in Excel-VBA

I'm sitting at a computer with none of the relevant bits of software, but from memory that code looks wrong. You're executing the command but discarding the RecordSet that objMyCommand.Execute returns.

I'd do:

Set objMyRecordset = objMyCommand.Execute

...and then lose the "open recordset" part.

HTML/CSS font color vs span style

You should use <span>, because as specified by the spec, <font> has been deprecated and probably won't display as you intend.

How to call a method function from another class?

You need to instantiate the other classes inside the main class;

Date d = new Date(params);
TemperatureRange t = new TemperatureRange(params);

You can then call their methods with:

object.methodname(params);
d.method();

You currently have constructors in your other classes. You should not return anything in these.

public Date(params){
    set variables for date object
}

Next you need a method to reference.

public returnType methodName(params){
  return something;
}

Fastest way to iterate over all the chars in a String

FIRST UPDATE: Before you try this ever in a production environment (not advised), read this first: http://www.javaspecialists.eu/archive/Issue237.html Starting from Java 9, the solution as described won't work anymore, because now Java will store strings as byte[] by default.

SECOND UPDATE: As of 2016-10-25, on my AMDx64 8core and source 1.8, there is no difference between using 'charAt' and field access. It appears that the jvm is sufficiently optimized to inline and streamline any 'string.charAt(n)' calls.

THIRD UPDATE: As of 2020-09-07, on my Ryzen 1950-X 16 core and source 1.14, 'charAt1' is 9 times slower than field access and 'charAt2' is 4 times slower than field access. Field access is back as the clear winner. Note than the program will need to use byte[] access for Java 9+ version jvms.

It all depends on the length of the String being inspected. If, as the question says, it is for long strings, the fastest way to inspect the string is to use reflection to access the backing char[] of the string.

A fully randomized benchmark with JDK 8 (win32 and win64) on an 64 AMD Phenom II 4 core 955 @ 3.2 GHZ (in both client mode and server mode) with 9 different techniques (see below!) shows that using String.charAt(n) is the fastest for small strings and that using reflection to access the String backing array is almost twice as fast for large strings.

THE EXPERIMENT

  • 9 different optimization techniques are tried.

  • All string contents are randomized

  • The test are done for string sizes in multiples of two starting with 0,1,2,4,8,16 etc.

  • The tests are done 1,000 times per string size

  • The tests are shuffled into random order each time. In other words, the tests are done in random order every time they are done, over 1000 times over.

  • The entire test suite is done forwards, and backwards, to show the effect of JVM warmup on optimization and times.

  • The entire suite is done twice, once in -client mode and the other in -server mode.

CONCLUSIONS

-client mode (32 bit)

For strings 1 to 256 characters in length, calling string.charAt(i) wins with an average processing of 13.4 million to 588 million characters per second.

Also, it is overall 5.5% faster (client) and 13.9% (server) like this:

    for (int i = 0; i < data.length(); i++) {
        if (data.charAt(i) <= ' ') {
            doThrow();
        }
    }

than like this with a local final length variable:

    final int len = data.length();
    for (int i = 0; i < len; i++) {
        if (data.charAt(i) <= ' ') {
            doThrow();
        }
    }

For long strings, 512 to 256K characters length, using reflection to access the String's backing array is fastest. This technique is almost twice as fast as String.charAt(i) (178% faster). The average speed over this range was 1.111 billion characters per second.

The Field must be obtained ahead of time and then it can be re-used in the library on different strings. Interestingly, unlike the code above, with Field access, it is 9% faster to have a local final length variable than to use 'chars.length' in the loop check. Here is how Field access can be setup as fastest:

   final Field field = String.class.getDeclaredField("value");
   field.setAccessible(true);

   try {
       final char[] chars = (char[]) field.get(data);
       final int len = chars.length;
       for (int i = 0; i < len; i++) {
           if (chars[i] <= ' ') {
               doThrow();
           }
       }
       return len;
   } catch (Exception ex) {
       throw new RuntimeException(ex);
   }

Special comments on -server mode

Field access starting winning after 32 character length strings in server mode on a 64 bit Java machine on my AMD 64 machine. That was not seen until 512 characters length in client mode.

Also worth noting I think, when I was running JDK 8 (32 bit build) in server mode, the overall performance was 7% slower for both large and small strings. This was with build 121 Dec 2013 of JDK 8 early release. So, for now, it seems that 32 bit server mode is slower than 32 bit client mode.

That being said ... it seems the only server mode that is worth invoking is on a 64 bit machine. Otherwise it actually hampers performance.

For 32 bit build running in -server mode on an AMD64, I can say this:

  1. String.charAt(i) is the clear winner overall. Although between sizes 8 to 512 characters there were winners among 'new' 'reuse' and 'field'.
  2. String.charAt(i) is 45% faster in client mode
  3. Field access is twice as fast for large Strings in client mode.

Also worth saying, String.chars() (Stream and the parallel version) are a bust. Way slower than any other way. The Streams API is a rather slow way to perform general string operations.

Wish List

Java String could have predicate accepting optimized methods such as contains(predicate), forEach(consumer), forEachWithIndex(consumer). Thus, without the need for the user to know the length or repeat calls to String methods, these could help parsing libraries beep-beep beep speedup.

Keep dreaming :)

Happy Strings!

~SH

The test used the following 9 methods of testing the string for the presence of whitespace:

"charAt1" -- CHECK THE STRING CONTENTS THE USUAL WAY:

int charAtMethod1(final String data) {
    final int len = data.length();
    for (int i = 0; i < len; i++) {
        if (data.charAt(i) <= ' ') {
            doThrow();
        }
    }
    return len;
}

"charAt2" -- SAME AS ABOVE BUT USE String.length() INSTEAD OF MAKING A FINAL LOCAL int FOR THE LENGTh

int charAtMethod2(final String data) {
    for (int i = 0; i < data.length(); i++) {
        if (data.charAt(i) <= ' ') {
            doThrow();
        }
    }
    return data.length();
}

"stream" -- USE THE NEW JAVA-8 String's IntStream AND PASS IT A PREDICATE TO DO THE CHECKING

int streamMethod(final String data, final IntPredicate predicate) {
    if (data.chars().anyMatch(predicate)) {
        doThrow();
    }
    return data.length();
}

"streamPara" -- SAME AS ABOVE, BUT OH-LA-LA - GO PARALLEL!!!

// avoid this at all costs
int streamParallelMethod(final String data, IntPredicate predicate) {
    if (data.chars().parallel().anyMatch(predicate)) {
        doThrow();
    }
    return data.length();
}

"reuse" -- REFILL A REUSABLE char[] WITH THE STRINGS CONTENTS

int reuseBuffMethod(final char[] reusable, final String data) {
    final int len = data.length();
    data.getChars(0, len, reusable, 0);
    for (int i = 0; i < len; i++) {
        if (reusable[i] <= ' ') {
            doThrow();
        }
    }
    return len;
}

"new1" -- OBTAIN A NEW COPY OF THE char[] FROM THE STRING

int newMethod1(final String data) {
    final int len = data.length();
    final char[] copy = data.toCharArray();
    for (int i = 0; i < len; i++) {
        if (copy[i] <= ' ') {
            doThrow();
        }
    }
    return len;
}

"new2" -- SAME AS ABOVE, BUT USE "FOR-EACH"

int newMethod2(final String data) {
    for (final char c : data.toCharArray()) {
        if (c <= ' ') {
            doThrow();
        }
    }
    return data.length();
}

"field1" -- FANCY!! OBTAIN FIELD FOR ACCESS TO THE STRING'S INTERNAL char[]

int fieldMethod1(final Field field, final String data) {
    try {
        final char[] chars = (char[]) field.get(data);
        final int len = chars.length;
        for (int i = 0; i < len; i++) {
            if (chars[i] <= ' ') {
                doThrow();
            }
        }
        return len;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

"field2" -- SAME AS ABOVE, BUT USE "FOR-EACH"

int fieldMethod2(final Field field, final String data) {
    final char[] chars;
    try {
        chars = (char[]) field.get(data);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    for (final char c : chars) {
        if (c <= ' ') {
            doThrow();
        }
    }
    return chars.length;
}

COMPOSITE RESULTS FOR CLIENT -client MODE (forwards and backwards tests combined)

Note: that the -client mode with Java 32 bit and -server mode with Java 64 bit are the same as below on my AMD64 machine.

Size     WINNER  charAt1 charAt2  stream streamPar   reuse    new1    new2  field1  field2
1        charAt    77.0     72.0   462.0     584.0   127.5    89.5    86.0   159.5   165.0
2        charAt    38.0     36.5   284.0   32712.5    57.5    48.3    50.3    89.0    91.5
4        charAt    19.5     18.5   458.6    3169.0    33.0    26.8    27.5    54.1    52.6
8        charAt     9.8      9.9   100.5    1370.9    17.3    14.4    15.0    26.9    26.4
16       charAt     6.1      6.5    73.4     857.0     8.4     8.2     8.3    13.6    13.5
32       charAt     3.9      3.7    54.8     428.9     5.0     4.9     4.7     7.0     7.2
64       charAt     2.7      2.6    48.2     232.9     3.0     3.2     3.3     3.9     4.0
128      charAt     2.1      1.9    43.7     138.8     2.1     2.6     2.6     2.4     2.6
256      charAt     1.9      1.6    42.4      90.6     1.7     2.1     2.1     1.7     1.8
512      field1     1.7      1.4    40.6      60.5     1.4     1.9     1.9     1.3     1.4
1,024    field1     1.6      1.4    40.0      45.6     1.2     1.9     2.1     1.0     1.2
2,048    field1     1.6      1.3    40.0      36.2     1.2     1.8     1.7     0.9     1.1
4,096    field1     1.6      1.3    39.7      32.6     1.2     1.8     1.7     0.9     1.0
8,192    field1     1.6      1.3    39.6      30.5     1.2     1.8     1.7     0.9     1.0
16,384   field1     1.6      1.3    39.8      28.4     1.2     1.8     1.7     0.8     1.0
32,768   field1     1.6      1.3    40.0      26.7     1.3     1.8     1.7     0.8     1.0
65,536   field1     1.6      1.3    39.8      26.3     1.3     1.8     1.7     0.8     1.0
131,072  field1     1.6      1.3    40.1      25.4     1.4     1.9     1.8     0.8     1.0
262,144  field1     1.6      1.3    39.6      25.2     1.5     1.9     1.9     0.8     1.0

COMPOSITE RESULTS FOR SERVER -server MODE (forwards and backwards tests combined)

Note: this is the test for Java 32 bit running in server mode on an AMD64. The server mode for Java 64 bit was the same as Java 32 bit in client mode except that Field access starting winning after 32 characters size.

Size     WINNER  charAt1 charAt2  stream streamPar   reuse    new1    new2  field1  field2
1        charAt     74.5    95.5   524.5     783.0    90.5   102.5    90.5   135.0   151.5
2        charAt     48.5    53.0   305.0   30851.3    59.3    57.5    52.0    88.5    91.8
4        charAt     28.8    32.1   132.8    2465.1    37.6    33.9    32.3    49.0    47.0
8          new2     18.0    18.6    63.4    1541.3    18.5    17.9    17.6    25.4    25.8
16         new2     14.0    14.7   129.4    1034.7    12.5    16.2    12.0    16.0    16.6
32         new2      7.8     9.1    19.3     431.5     8.1     7.0     6.7     7.9     8.7
64        reuse      6.1     7.5    11.7     204.7     3.5     3.9     4.3     4.2     4.1
128       reuse      6.8     6.8     9.0     101.0     2.6     3.0     3.0     2.6     2.7
256      field2      6.2     6.5     6.9      57.2     2.4     2.7     2.9     2.3     2.3
512       reuse      4.3     4.9     5.8      28.2     2.0     2.6     2.6     2.1     2.1
1,024    charAt      2.0     1.8     5.3      17.6     2.1     2.5     3.5     2.0     2.0
2,048    charAt      1.9     1.7     5.2      11.9     2.2     3.0     2.6     2.0     2.0
4,096    charAt      1.9     1.7     5.1       8.7     2.1     2.6     2.6     1.9     1.9
8,192    charAt      1.9     1.7     5.1       7.6     2.2     2.5     2.6     1.9     1.9
16,384   charAt      1.9     1.7     5.1       6.9     2.2     2.5     2.5     1.9     1.9
32,768   charAt      1.9     1.7     5.1       6.1     2.2     2.5     2.5     1.9     1.9
65,536   charAt      1.9     1.7     5.1       5.5     2.2     2.4     2.4     1.9     1.9
131,072  charAt      1.9     1.7     5.1       5.4     2.3     2.5     2.5     1.9     1.9
262,144  charAt      1.9     1.7     5.1       5.1     2.3     2.5     2.5     1.9     1.9

FULL RUNNABLE PROGRAM CODE

(to test on Java 7 and earlier, remove the two streams tests)

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.function.IntPredicate;

/**
 * @author Saint Hill <http://stackoverflow.com/users/1584255/saint-hill>
 */
public final class TestStrings {

    // we will not test strings longer than 512KM
    final int MAX_STRING_SIZE = 1024 * 256;

    // for each string size, we will do all the tests
    // this many times
    final int TRIES_PER_STRING_SIZE = 1000;

    public static void main(String[] args) throws Exception {
        new TestStrings().run();
    }

    void run() throws Exception {

        // double the length of the data until it reaches MAX chars long
        // 0,1,2,4,8,16,32,64,128,256 ... 
        final List<Integer> sizes = new ArrayList<>();
        for (int n = 0; n <= MAX_STRING_SIZE; n = (n == 0 ? 1 : n * 2)) {
            sizes.add(n);
        }

        // CREATE RANDOM (FOR SHUFFLING ORDER OF TESTS)
        final Random random = new Random();

        System.out.println("Rate in nanoseconds per character inspected.");
        System.out.printf("==== FORWARDS (tries per size: %s) ==== \n", TRIES_PER_STRING_SIZE);

        printHeadings(TRIES_PER_STRING_SIZE, random);

        for (int size : sizes) {
            reportResults(size, test(size, TRIES_PER_STRING_SIZE, random));
        }

        // reverse order or string sizes
        Collections.reverse(sizes);

        System.out.println("");
        System.out.println("Rate in nanoseconds per character inspected.");
        System.out.printf("==== BACKWARDS (tries per size: %s) ==== \n", TRIES_PER_STRING_SIZE);

        printHeadings(TRIES_PER_STRING_SIZE, random);

        for (int size : sizes) {
            reportResults(size, test(size, TRIES_PER_STRING_SIZE, random));

        }
    }

    ///
    ///
    ///  METHODS OF CHECKING THE CONTENTS
    ///  OF A STRING. ALWAYS CHECKING FOR
    ///  WHITESPACE (CHAR <=' ')
    ///  
    ///
    // CHECK THE STRING CONTENTS
    int charAtMethod1(final String data) {
        final int len = data.length();
        for (int i = 0; i < len; i++) {
            if (data.charAt(i) <= ' ') {
                doThrow();
            }
        }
        return len;
    }

    // SAME AS ABOVE BUT USE String.length()
    // instead of making a new final local int 
    int charAtMethod2(final String data) {
        for (int i = 0; i < data.length(); i++) {
            if (data.charAt(i) <= ' ') {
                doThrow();
            }
        }
        return data.length();
    }

    // USE new Java-8 String's IntStream
    // pass it a PREDICATE to do the checking
    int streamMethod(final String data, final IntPredicate predicate) {
        if (data.chars().anyMatch(predicate)) {
            doThrow();
        }
        return data.length();
    }

    // OH LA LA - GO PARALLEL!!!
    int streamParallelMethod(final String data, IntPredicate predicate) {
        if (data.chars().parallel().anyMatch(predicate)) {
            doThrow();
        }
        return data.length();
    }

    // Re-fill a resuable char[] with the contents
    // of the String's char[]
    int reuseBuffMethod(final char[] reusable, final String data) {
        final int len = data.length();
        data.getChars(0, len, reusable, 0);
        for (int i = 0; i < len; i++) {
            if (reusable[i] <= ' ') {
                doThrow();
            }
        }
        return len;
    }

    // Obtain a new copy of char[] from String
    int newMethod1(final String data) {
        final int len = data.length();
        final char[] copy = data.toCharArray();
        for (int i = 0; i < len; i++) {
            if (copy[i] <= ' ') {
                doThrow();
            }
        }
        return len;
    }

    // Obtain a new copy of char[] from String
    // but use FOR-EACH
    int newMethod2(final String data) {
        for (final char c : data.toCharArray()) {
            if (c <= ' ') {
                doThrow();
            }
        }
        return data.length();
    }

    // FANCY!
    // OBTAIN FIELD FOR ACCESS TO THE STRING'S
    // INTERNAL CHAR[]
    int fieldMethod1(final Field field, final String data) {
        try {
            final char[] chars = (char[]) field.get(data);
            final int len = chars.length;
            for (int i = 0; i < len; i++) {
                if (chars[i] <= ' ') {
                    doThrow();
                }
            }
            return len;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    // same as above but use FOR-EACH
    int fieldMethod2(final Field field, final String data) {
        final char[] chars;
        try {
            chars = (char[]) field.get(data);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        for (final char c : chars) {
            if (c <= ' ') {
                doThrow();
            }
        }
        return chars.length;
    }

    /**
     *
     * Make a list of tests. We will shuffle a copy of this list repeatedly
     * while we repeat this test.
     *
     * @param data
     * @return
     */
    List<Jobber> makeTests(String data) throws Exception {
        // make a list of tests
        final List<Jobber> tests = new ArrayList<Jobber>();

        tests.add(new Jobber("charAt1") {
            int check() {
                return charAtMethod1(data);
            }
        });

        tests.add(new Jobber("charAt2") {
            int check() {
                return charAtMethod2(data);
            }
        });

        tests.add(new Jobber("stream") {
            final IntPredicate predicate = new IntPredicate() {
                public boolean test(int value) {
                    return value <= ' ';
                }
            };

            int check() {
                return streamMethod(data, predicate);
            }
        });

        tests.add(new Jobber("streamPar") {
            final IntPredicate predicate = new IntPredicate() {
                public boolean test(int value) {
                    return value <= ' ';
                }
            };

            int check() {
                return streamParallelMethod(data, predicate);
            }
        });

        // Reusable char[] method
        tests.add(new Jobber("reuse") {
            final char[] cbuff = new char[MAX_STRING_SIZE];

            int check() {
                return reuseBuffMethod(cbuff, data);
            }
        });

        // New char[] from String
        tests.add(new Jobber("new1") {
            int check() {
                return newMethod1(data);
            }
        });

        // New char[] from String
        tests.add(new Jobber("new2") {
            int check() {
                return newMethod2(data);
            }
        });

        // Use reflection for field access
        tests.add(new Jobber("field1") {
            final Field field;

            {
                field = String.class.getDeclaredField("value");
                field.setAccessible(true);
            }

            int check() {
                return fieldMethod1(field, data);
            }
        });

        // Use reflection for field access
        tests.add(new Jobber("field2") {
            final Field field;

            {
                field = String.class.getDeclaredField("value");
                field.setAccessible(true);
            }

            int check() {
                return fieldMethod2(field, data);
            }
        });

        return tests;
    }

    /**
     * We use this class to keep track of test results
     */
    abstract class Jobber {

        final String name;
        long nanos;
        long chars;
        long runs;

        Jobber(String name) {
            this.name = name;
        }

        abstract int check();

        final double nanosPerChar() {
            double charsPerRun = chars / runs;
            long nanosPerRun = nanos / runs;
            return charsPerRun == 0 ? nanosPerRun : nanosPerRun / charsPerRun;
        }

        final void run() {
            runs++;
            long time = System.nanoTime();
            chars += check();
            nanos += System.nanoTime() - time;
        }
    }

    // MAKE A TEST STRING OF RANDOM CHARACTERS A-Z
    private String makeTestString(int testSize, char start, char end) {
        Random r = new Random();
        char[] data = new char[testSize];
        for (int i = 0; i < data.length; i++) {
            data[i] = (char) (start + r.nextInt(end));
        }
        return new String(data);
    }

    // WE DO THIS IF WE FIND AN ILLEGAL CHARACTER IN THE STRING
    public void doThrow() {
        throw new RuntimeException("Bzzzt -- Illegal Character!!");
    }

    /**
     * 1. get random string of correct length 2. get tests (List<Jobber>) 3.
     * perform tests repeatedly, shuffling each time
     */
    List<Jobber> test(int size, int tries, Random random) throws Exception {
        String data = makeTestString(size, 'A', 'Z');
        List<Jobber> tests = makeTests(data);
        List<Jobber> copy = new ArrayList<>(tests);
        while (tries-- > 0) {
            Collections.shuffle(copy, random);
            for (Jobber ti : copy) {
                ti.run();
            }
        }
        // check to make sure all char counts the same
        long runs = tests.get(0).runs;
        long count = tests.get(0).chars;
        for (Jobber ti : tests) {
            if (ti.runs != runs && ti.chars != count) {
                throw new Exception("Char counts should match if all correct algorithms");
            }
        }
        return tests;
    }

    private void printHeadings(final int TRIES_PER_STRING_SIZE, final Random random) throws Exception {
        System.out.print("  Size");
        for (Jobber ti : test(0, TRIES_PER_STRING_SIZE, random)) {
            System.out.printf("%9s", ti.name);
        }
        System.out.println("");
    }

    private void reportResults(int size, List<Jobber> tests) {
        System.out.printf("%6d", size);
        for (Jobber ti : tests) {
            System.out.printf("%,9.2f", ti.nanosPerChar());
        }
        System.out.println("");
    }
}

Is it possible to cast a Stream in Java 8?

I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

Stream.of(objects)
    .filter(c -> c instanceof Client)
    .map(c -> (Client) c)
    .map(Client::getID)
    .forEach(System.out::println);

or, as suggested in the comments, you could use the cast method - the former may be easier to read though:

Stream.of(objects)
    .filter(Client.class::isInstance)
    .map(Client.class::cast)
    .map(Client::getID)
    .forEach(System.out::println);

How can I get the count of milliseconds since midnight for the current?

  1. long timeNow = System.currentTimeMillis();
  2. System.out.println(new Date(timeNow));

Fri Apr 04 14:27:05 PDT 2014

javascript - Create Simple Dynamic Array

If you are asking whether there is a built in Pythonic range-like function, there isn't. You have to do it the brute force way. Maybe rangy would be of interest to you.

C# Creating and using Functions

Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".

Thats not true. you may read about (func type+ Lambda expressions),( anonymous function"using delegates type"),(action type +Lambda expressions ),(Predicate type+Lambda expressions). etc...etc... this will work.

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

           int a;
           int b;
           int c;

           Console.WriteLine("Enter value of 'a':");
           a = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("Enter value of 'b':");
           b = Convert.ToInt32(Console.ReadLine());

           Func<int, int, int> funcAdd = (x, y) => x + y;
           c=funcAdd.Invoke(a, b);
           Console.WriteLine(Convert.ToString(c));

        }

     }
}

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
      END 
WHERE columnC = 1

Concatenating null strings in Java

This is behavior specified in the Java API's String.valueOf(Object) method. When you do concatenation, valueOf is used to get the String representation. There is a special case if the Object is null, in which case the string "null" is used.

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

Parameters: obj - an Object.

Returns:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

How to convert numbers between hexadecimal and decimal

Try using BigNumber in C# - Represents an arbitrarily large signed integer.

Program

using System.Numerics;
...
var bigNumber = BigInteger.Parse("837593454735734579347547357233757342857087879423437472347757234945743");
Console.WriteLine(bigNumber.ToString("X"));

Output

4F30DC39A5B10A824134D5B18EEA3707AC854EE565414ED2E498DCFDE1A15DA5FEB6074AE248458435BD417F06F674EB29A2CFECF

Possible Exceptions,

ArgumentNullException - value is null.

FormatException - value is not in the correct format.

Conclusion

You can convert string and store a value in BigNumber without constraints about the size of the number unless the string is empty and non-analphabets

How to send only one UDP packet with netcat?

Netcat sends one packet per newline. So you're fine. If you do anything more complex then you might need something else.

I was fooling around with Wireshark when I realized this. Don't know if it helps.

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give name and values to those submit buttons like:

    <td>
    <input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
    </td>
    <td>
    <input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
    </td>

and then in your php script you could check

if($_POST['mybutton'] == 'save')
{
  ///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
  ///do publish processing here
}

Comparing Class Types in Java

It prints true on my machine. And it should, otherwise nothing in Java would work as expected. (This is explained in the JLS: 4.3.4 When Reference Types Are the Same)

Do you have multiple classloaders in place?


Ah, and in response to this comment:

I realise I have a typo in my question. I should be like this:

MyImplementedObject obj = new MyImplementedObject ();
if(obj.getClass() == MyObjectInterface.class) System.out.println("true");

MyImplementedObject implements MyObjectInterface So in other words, I am comparing it with its implemented objects.

OK, if you want to check that you can do either:

if(MyObjectInterface.class.isAssignableFrom(obj.getClass()))

or the much more concise

if(obj instanceof MyobjectInterface)

How to loop in excel without VBA or macros?

Add more columns when you have variable loops that repeat at different rates. I'm not sure explicitly what you're trying to do, but I think I've done something that could apply.

Creating a single loop in Excel is prettty simple. It actually does the work for you. Try this on a new workbook

  1. Enter "1" in A1
  2. Enter "=A1+1" in A2

A3 will automatically be "=A2+1" as you drag down. The first steps don't have to be that explicit. Excel will automatically recognize the pattern and count if you just put "2" in A2, but if we want B1-B5 to be "100" and B5-B10 to be "200" (counting up the same way) you can see why knowing how to do it explicitly matters. In this scenario, You just enter:

  1. "100" in B1, drag through to B5 and
  2. "=B1+100" in B6

B7 will automatically be "=B2+100" etc. as you drag down, so basically it increases every 5 rows infinitely. To make a loop of numbers 1-5 in column A:

  1. Enter "=A1" in cell A6. As you drag down, it will automatically be "=A2" in cell A7, etc. because of the way that Excel does things.

So, now we have column A repeating numbers 1-5 while column B is increasing by 100 every 5 cells.You could make column B repeat, for instance, the numbers 100-900 in using the same method as you did with column A as a way to produce, for instance, each possible combination with multiple variables. Drag down the columns and they'll do it infinitely. I'm not explicitly addressing the scenario given, but if you follow the steps and understand them, the concept should give you an answer to the problem that involves adding more columns and concactinating or using them as your variables.

Accessing a class' member variables in Python?

Implement the return statement like the example below! You should be good. I hope it helps someone..

class Example(object):
    def the_example(self):
        itsProblem = "problem"
        return itsProblem 


theExample = Example()
print theExample.the_example()

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

os.path.isdir() checks if the path exists and is a directory and returns TRUE for the case.

Similarly, os.path.isfile() checks if the path exists and is a file and returns TRUE for the case.

And, os.path.exists() checks if the path exists and doesn’t care if the path points to a file or a directory and returns TRUE in either of the cases.

Converting NumPy array into Python List structure?

The numpy .tolist method produces nested lists if the numpy array shape is 2D.

if flat lists are desired, the method below works.

import numpy as np
from itertools import chain

a = [1,2,3,4,5,6,7,8,9]
print type(a), len(a), a
npa = np.asarray(a)
print type(npa), npa.shape, "\n", npa
npa = npa.reshape((3, 3))
print type(npa), npa.shape, "\n", npa
a = list(chain.from_iterable(npa))
print type(a), len(a), a`

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I dont think there is any sdk support for sending mms in android. Look here Atleast I havent found yet. But a guy claimed to have it. Have a look at this post.

Send MMS from My application in android

Add days Oracle SQL

It's Simple.You can use

select (sysdate+2) as new_date from dual;

This will add two days from current date.

Removing cordova plugins from the project

You can do it with bash as well (after switching to your Cordova project directory):

for i in `cordova plugin ls | grep '^[^ ]*' -o`; do cordova plugin rm $i; done

Centering a canvas

Looking at the current answers I feel that one easy and clean fix is missing. Just in case someone passes by and looks for the right solution. I am quite successful with some simple CSS and javascript.

Center canvas to middle of the screen or parent element. No wrapping.

HTML:

<canvas id="canvas" width="400" height="300">No canvas support</canvas>

CSS:

#canvas {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
}

Javascript:

window.onload = window.onresize = function() {
    var canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth * 0.8;
    canvas.height = window.innerHeight * 0.8;
}

Works like a charm - tested: firefox, chrome

fiddle: http://jsfiddle.net/djwave28/j6cffppa/3/

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Use java.util.Date class instead of Timestamp.

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

This will get you the current date in the format specified.

What is a monad?

Explaining "what is a monad" is a bit like saying "what is a number?" We use numbers all the time. But imagine you met someone who didn't know anything about numbers. How the heck would you explain what numbers are? And how would you even begin to describe why that might be useful?

What is a monad? The short answer: It's a specific way of chaining operations together.

In essence, you're writing execution steps and linking them together with the "bind function". (In Haskell, it's named >>=.) You can write the calls to the bind operator yourself, or you can use syntax sugar which makes the compiler insert those function calls for you. But either way, each step is separated by a call to this bind function.

So the bind function is like a semicolon; it separates the steps in a process. The bind function's job is to take the output from the previous step, and feed it into the next step.

That doesn't sound too hard, right? But there is more than one kind of monad. Why? How?

Well, the bind function can just take the result from one step, and feed it to the next step. But if that's "all" the monad does... that actually isn't very useful. And that's important to understand: Every useful monad does something else in addition to just being a monad. Every useful monad has a "special power", which makes it unique.

(A monad that does nothing special is called the "identity monad". Rather like the identity function, this sounds like an utterly pointless thing, yet turns out not to be... But that's another story™.)

Basically, each monad has its own implementation of the bind function. And you can write a bind function such that it does hoopy things between execution steps. For example:

  • If each step returns a success/failure indicator, you can have bind execute the next step only if the previous one succeeded. In this way, a failing step aborts the whole sequence "automatically", without any conditional testing from you. (The Failure Monad.)

  • Extending this idea, you can implement "exceptions". (The Error Monad or Exception Monad.) Because you're defining them yourself rather than it being a language feature, you can define how they work. (E.g., maybe you want to ignore the first two exceptions and only abort when a third exception is thrown.)

  • You can make each step return multiple results, and have the bind function loop over them, feeding each one into the next step for you. In this way, you don't have to keep writing loops all over the place when dealing with multiple results. The bind function "automatically" does all that for you. (The List Monad.)

  • As well as passing a "result" from one step to another, you can have the bind function pass extra data around as well. This data now doesn't show up in your source code, but you can still access it from anywhere, without having to manually pass it to every function. (The Reader Monad.)

  • You can make it so that the "extra data" can be replaced. This allows you to simulate destructive updates, without actually doing destructive updates. (The State Monad and its cousin the Writer Monad.)

  • Because you're only simulating destructive updates, you can trivially do things that would be impossible with real destructive updates. For example, you can undo the last update, or revert to an older version.

  • You can make a monad where calculations can be paused, so you can pause your program, go in and tinker with internal state data, and then resume it.

  • You can implement "continuations" as a monad. This allows you to break people's minds!

All of this and more is possible with monads. Of course, all of this is also perfectly possible without monads too. It's just drastically easier using monads.

How do I install Python 3 on an AWS EC2 instance?

Here are the steps I used to manually install python3 for anyone else who wants to do it as it's not super straight forward. EDIT: It's almost certainly easier to use the yum package manager (see other answers).

Note, you'll probably want to do sudo yum groupinstall 'Development Tools' before doing this otherwise pip won't install.

wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
tar zxvf Python-3.4.2.tgz
cd Python-3.4.2
sudo yum install gcc
./configure --prefix=/opt/python3
make
sudo yum install openssl-devel
sudo make install
sudo ln -s /opt/python3/bin/python3 /usr/bin/python3
python3 (should start the interpreter if it's worked (quit() to exit)

disabling spring security in spring boot app

The accepted answer didn't work for me.

If you have a multi configuration, adding the following to your WebSecurityConfig class worked for me (ensure that your Order(1) is lower than all of your other Order annotations in the class):

/* UNCOMMENT TO DISABLE SPRING SECURITY */
    /*@Configuration
    @Order(1)
    public static class DisableSecurityConfigurationAdapater extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
        }
    }*/

How do I make a text go onto the next line if it overflows?

As long as you specify a width on the element, it should wrap itself without needing anything else.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

The issue that JavaFX is no longer part of JDK 11. The following solution works using IntelliJ (haven't tried it with NetBeans):

  1. Add JavaFX Global Library as a dependency:

    Settings -> Project Structure -> Module. In module go to the Dependencies tab, and click the add "+" sign -> Library -> Java-> choose JavaFX from the list and click Add Selected, then Apply settings.

  2. Right click source file (src) in your JavaFX project, and create a new module-info.java file. Inside the file write the following code :

    module YourProjectName { 
        requires javafx.fxml;
        requires javafx.controls;
        requires javafx.graphics;
        opens sample;
    }
    

    These 2 steps will solve all your issues with JavaFX, I assure you.

Reference : There's a You Tube tutorial made by The Learn Programming channel, will explain all the details above in just 5 minutes. I also recommend watching it to solve your problem: https://www.youtube.com/watch?v=WtOgoomDewo

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

execute below

Python manage.py makemigrations

It will show missing package.

Install missing package and again run below command to make sure if nothing is missed.

Python manage.py makemigrations

It will resolve your issue.

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

For cv::Mat_<T> mat just use mat(row, col)

Accessing elements of a matrix with specified type cv::Mat_< _Tp > is more comfortable, as you can skip the template specification. This is pointed out in the documentation as well.

code:

cv::Mat1d mat0 = cv::Mat1d::zeros(3, 4);
std::cout << "mat0:\n" << mat0 << std::endl;
std::cout << "element: " << mat0(2, 0) << std::endl;
std::cout << std::endl;

cv::Mat1d mat1 = (cv::Mat1d(3, 4) <<
    1, NAN, 10.5, NAN,
    NAN, -99, .5, NAN,
    -70, NAN, -2, NAN);
std::cout << "mat1:\n" << mat1 << std::endl;
std::cout << "element: " << mat1(0, 2) << std::endl;
std::cout << std::endl;

cv::Mat mat2 = cv::Mat(3, 4, CV_32F, 0.0);
std::cout << "mat2:\n" << mat2 << std::endl;
std::cout << "element: " << mat2.at<float>(2, 0) << std::endl;
std::cout << std::endl;

output:

mat0:
[0, 0, 0, 0;
 0, 0, 0, 0;
 0, 0, 0, 0]
element: 0

mat1:
[1, nan, 10.5, nan;
 nan, -99, 0.5, nan;
 -70, nan, -2, nan]
element: 10.5

mat2:
[0, 0, 0, 0;
 0, 0, 0, 0;
 0, 0, 0, 0]
element: 0

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

How can I restore the MySQL root user’s full privileges?

  1. "sudo cat /etc/mysql/debian.cnf" to use debian-sys-maint user
  2. login by this user throgh "mysql -u saved-username -p;", then enter the saved password.
  3. mysql> UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
  4. mysql> FLUSH PRIVILEGES;
  5. mysql> exit
  6. reboot Thanks

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

Just an addition to the answer of @phantomlimb,

while View.generateViewId() require API Level >= 17,
this tool is compatibe with all API.

according to current API Level,
it decide weather using system API or not.

so you can use ViewIdGenerator.generateViewId() and View.generateViewId() in the same time and don't worry about getting same id

import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;

/**
 * {@link View#generateViewId()}??API Level >= 17,??????????API Level
 * <p>
 * ??????API Level,?????{@link View#generateViewId()},???????{@link View#generateViewId()}
 * ??,???????Id??
 * <p>
 * =============
 * <p>
 * while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API.
 * <p>
 * according to current API Level, it decide weather using system API or not.<br>
 * so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the
 * same time and don't worry about getting same id
 * 
 * @author [email protected]
 */
public class ViewIdGenerator {
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    @SuppressLint("NewApi")
    public static int generateViewId() {

        if (Build.VERSION.SDK_INT < 17) {
            for (;;) {
                final int result = sNextGeneratedId.get();
                // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
                int newValue = result + 1;
                if (newValue > 0x00FFFFFF)
                    newValue = 1; // Roll over to 1, not 0.
                if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result;
                }
            }
        } else {
            return View.generateViewId();
        }

    }
}

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

PHP cURL, extract an XML response

Example:

<songs>
<song dateplayed="2011-07-24 19:40:26">
    <title>I left my heart on Europa</title>
    <artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
    <title>Oh Ganymede</title>
    <artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
    <title>Kallichore</title>
    <artist>Jewitt K. Sheppard</artist>
</song>

then:

<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>

Output on your browser: Ship of Nomads

credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

How to show full column content in a Spark Dataframe?

In c# Option("truncate", false) does not truncate data in the output.

StreamingQuery query = spark
                    .Sql("SELECT * FROM Messages")
                    .WriteStream()
                    .OutputMode("append")
                    .Format("console")
                    .Option("truncate", false)
                    .Start();

JUnit Testing private variables?

First of all, you are in a bad position now - having the task of writing tests for the code you did not originally create and without any changes - nightmare! Talk to your boss and explain, it is not possible to test the code without making it "testable". To make code testable you usually do some important changes;

Regarding private variables. You actually never should do that. Aiming to test private variables is the first sign that something wrong with the current design. Private variables are part of the implementation, tests should focus on behavior rather of implementation details.

Sometimes, private field are exposed to public access with some getter. I do that, but try to avoid as much as possible (mark in comments, like 'used for testing').

Since you have no possibility to change the code, I don't see possibility (I mean real possibility, not like Reflection hacks etc.) to check private variable.

How do I download code using SVN/Tortoise from Google Code?

After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".

Can I restore a single table from a full mysql mysqldump file?

This can be done more easily? This is how I did it:

Create a temporary database (e.g. restore):

mysqladmin -u root -p create restore

Restore the full dump in the temp database:

mysql -u root -p restore < fulldump.sql

Dump the table you want to recover:

mysqldump restore mytable > mytable.sql

Import the table in another database:

mysql -u root -p database < mytable.sql

Getting value from a cell from a gridview on RowDataBound event

Just use a loop to check your cell in a gridview for example:

for (int i = 0; i < GridView2.Rows.Count; i++)
{
    string vr;
    vr = GridView2.Rows[i].Cells[4].Text; // here you go vr = the value of the cel
    if (vr  == "0") // you can check for anything
    {
        GridView2.Rows[i].Cells[4].Text = "Done";
        // you can format this cell 
    }
}

Return row of Data Frame based on value in a column - R

@Zelazny7's answer works, but if you want to keep ties you could do:

df[which(df$Amount == min(df$Amount)), ]

For example with the following data frame:

df <- data.frame(Name = c("A", "B", "C", "D", "E"), 
                 Amount = c(150, 120, 175, 160, 120))

df[which.min(df$Amount), ]
#   Name Amount
# 2    B    120

df[which(df$Amount == min(df$Amount)), ]
#   Name Amount
# 2    B    120
# 5    E    120

Edit: If there are NAs in the Amount column you can do:

df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]

Creating a blurring overlay view

You can use UIVisualEffectView to achieve this effect. This is a native API that has been fine-tuned for performance and great battery life, plus it's easy to implement.

Swift:

//only apply the blur if the user hasn't disabled transparency effects
if !UIAccessibility.isReduceTransparencyEnabled {
    view.backgroundColor = .clear

    let blurEffect = UIBlurEffect(style: .dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    //always fill the view
    blurEffectView.frame = self.view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    view.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed
} else {
    view.backgroundColor = .black
}

Objective-C:

//only apply the blur if the user hasn't disabled transparency effects
if (!UIAccessibilityIsReduceTransparencyEnabled()) {
    self.view.backgroundColor = [UIColor clearColor];

    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    //always fill the view
    blurEffectView.frame = self.view.bounds;
    blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    [self.view addSubview:blurEffectView]; //if you have more UIViews, use an insertSubview API to place it where needed
} else {
    self.view.backgroundColor = [UIColor blackColor];
}

If you are presenting this view controller modally to blur the underlying content, you'll need to set the modal presentation style to Over Current Context and set the background color to clear to ensure the underlying view controller will remain visible once this is presented overtop.

Setting JDK in Eclipse

JDK 1.8 have some more enrich feature which doesn't support to many eclipse .

If you didn't find java compliance level as 1.8 in java compiler ,then go ahead and install the below eclipse 32bit or 64 bit depending on your system supports.

  1. Install jdk 1.8 and then set the JAVA_HOME and CLASSPATH in environment variable.
  2. Download eclipse-jee-neon-3-win32 and unzip : supports to java 1.8
  3. Or download Oracle Enterprise Pack for Eclipse (12.2.1.5) and unzip :Supports java 1.8 with 64 bit OS
  4. Right click your project > properties
  5. Select “Java Compiler” on left and set java compliance level to 1.8 [select from the dropdown 1.8]
  6. Try running one java program supports to java 8 like lambda expression as below and if no compilation error ,means your eclipse supports to java 1.8, something like this:

    interface testI{
        void show();
    }
    
    /*class A implements testI{
        public void show(){
            System.out.println("Hello");
        }
    }*/
    
    public class LambdaDemo1 {
        public static void main(String[] args) {
            testI test ;
            /*test= new A();
            test.show();*/
            test = () ->System.out.println("Hello,how are you?"); //lambda 
            test.show();
        }        
    }
    

How to retrieve data from a SQL Server database in C#?

To retrieve data from database:

private SqlConnection Conn;
 private void CreateConnection()
 {
    string ConnStr =
    ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    Conn = new SqlConnection(ConnStr);
 }
 public DataTable getData()
 {
 CreateConnection();
    string SqlString = "SELECT * FROM TableName WHERE SomeID = @SomeID;";
    SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
    DataTable dt = new DataTable();
    try
    {
        Conn.Open();
        sda.Fill(dt);
    }
    catch (SqlException se)
    {
        DBErLog.DbServLog(se, se.ToString());
    }
    finally
    {
        Conn.Close();
    }
    return dt;
}

How do I automatically scroll to the bottom of a multiline text box?

I use a function for this :

private void Log (string s) {
    TB1.AppendText(Environment.NewLine + s);
    TB1.ScrollToCaret();
}

How to get element by classname or id

getElementsByClassName is a function on the DOM Document. It is neither a jQuery nor a jqLite function.

Don't add the period before the class name when using it:

var result = document.getElementsByClassName("multi-files");

Wrap it in jqLite (or jQuery if jQuery is loaded before Angular):

var wrappedResult = angular.element(result);

If you want to select from the element in a directive's link function you need to access the DOM reference instead of the the jqLite reference - element[0] instead of element:

link: function (scope, element, attrs) {

  var elementResult = element[0].getElementsByClassName('multi-files');
}

Alternatively you can use the document.querySelector function (need the period here if selecting by class):

var queryResult = element[0].querySelector('.multi-files');
var wrappedQueryResult = angular.element(queryResult);

Demo: http://plnkr.co/edit/AOvO47ebEvrtpXeIzYOH?p=preview

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

In Visual Studio Code How do I merge between two local branches?

Actually you can do with VS Code the following:

Merge Local Branch with VS Code

When using SASS how can I import a file from a different directory?

I was have same problem and i found solution by adding path to file like:

@import "C:/xampp/htdocs/Scss_addons/Bootstrap/bootstrap";

@import "C:/xampp/htdocs/Scss_addons/Compass/compass";

Difference between arguments and parameters in Java

In java, there are two types of parameters, implicit parameters and explicit parameters. Explicit parameters are the arguments passed into a method. The implicit parameter of a method is the instance that the method is called from. Arguments are simply one of the two types of parameters.

How to clear a textbox once a button is clicked in WPF?

I use this. I think this is the simpliest way to do it:

 textBoxName.Clear();

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().

UIDevice uniqueIdentifier deprecated - What to do now?

iOS 11 has introduced the DeviceCheck framework. It has a fullproof solution for uniquely identifying the device.

How do I calculate the date six months from the current date using the datetime Python module?

    def addDay(date, number):
        for i in range(number)
            #try to add a day
            try:
                date = date.replace(day = date.day + 1)
            #in case it's impossible ex:january 32nd add a month and restart at day 1
            except:
                #add month part
                try:
                    date = date.replace(month = date.month +1, day = 1)
                except:
                    date = date.replace(year = date.year +1, month = 1, day = 1)

For everyone still reading this post. I think this code is way clearer, especially compared to code using modulo(%).

Sorry for any grammatical error, english is so not my main language

PHP mkdir: Permission denied problem

If you'r using LINUX, first let's check apache's user, since in some distros it can be different:

egrep -i '^user|^group' /etc/httpd/conf/httpd.conf 

Let's say the result is "http". Do the folowwing, just remember change path_to_folder to folders path:

chown -R http:http path_to_folder
chmod -R g+rw path_to_folder