Programs & Examples On #Silverlight 5.0

Silverlight is Microsoft's cross-browser, cross platform plug-in for media experiences and rich interactive applications. The latest Silverlight version available is Silverlight 5.

Task<> does not contain a definition for 'GetAwaiter'

Make sure your .NET version 4.5 or greater

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

Do not forget to include Reference to Microsoft Excel 12.0/11.0 object Library

using Excel = Microsoft.Office.Interop.Excel;
// Include this Namespace

Microsoft.Office.Interop.Excel.Application xlApp = null;
Excel.Workbook xlWorkbook = null;
Excel.Sheets xlSheets = null;
Excel.Worksheet xlNewSheet = null;
string worksheetName ="Sheet_Name";
object readOnly1 = false;

object isVisible = true;

object missing = System.Reflection.Missing.Value;

try
{
    xlApp = new Microsoft.Office.Interop.Excel.Application();

    if (xlApp == null)
        return;

    // Uncomment the line below if you want to see what's happening in Excel
    // xlApp.Visible = true;

    xlWorkbook = xlApp.Workbooks.Open(@"C:\Book1.xls", missing, readOnly1, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing);

    xlSheets = (Excel.Sheets)xlWorkbook.Sheets;

    // The first argument below inserts the new worksheet as the first one
    xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
    xlNewSheet.Name = worksheetName;

    xlWorkbook.Save();
    xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
    xlApp.Quit();
}
finally
{
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlNewSheet);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
    //xlApp = null;
}

Find IP address of directly connected device

Your Best Approach is to install Wireshark, reboot the device wait for the TCP/UDP stream , broadcasts will announce the IP address for both Ethernet ports This is especially useful when the device connected does not have DHCP Client enabled, then you can go from there.

Error: fix the version conflict (google-services plugin)

For fire base to install properly all the versions of the fire base compiles must be in same version so

compile 'com.google.firebase:firebase-messaging:11.0.4' 
compile 'com.google.android.gms:play-services-maps:11.0.4' 
compile 'com.google.android.gms:play-services-location:11.0.4'

this is the correct way to do it.

Assign static IP to Docker container

If you want your container to have it's own virtual ethernet socket (with it's own MAC address), iptables, then use the Macvlan driver. This may be necessary to route traffic out to your/ISPs router.

https://docs.docker.com/engine/userguide/networking/get-started-macvlan

Check empty string in Swift?

Check check for only spaces and newlines characters in text

extension String
{
    var  isBlank:Bool {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
    }
}

using

if text.isBlank
{
  //text is blank do smth
}

Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

enter image description here

Pointers in Python?

From one point of view, everything is a pointer in Python. Your example works a lot like the C++ code.

int* a = new int(1);
int* b = a;
a = new int(2);
cout << *b << endl;   // prints 1

(A closer equivalent would use some type of shared_ptr<Object> instead of int*.)

Here's an example: I want form.data['field'] and form.field.value to always have the same value. It's not completely necessary, but I think it would be nice.

You can do this by overloading __getitem__ in form.data's class.

How to remove specific substrings from a set of strings in Python?

I did the test (but it is not your example) and the data does not return them orderly or complete

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = {x.replace('p','') for x in ind}
>>> newind
{'1', '2', '8', '5', '4'}

I proved that this works:

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = [x.replace('p','') for x in ind]
>>> newind
['5', '1', '8', '4', '2', '8']

or

>>> newind = []
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> for x in ind:
...     newind.append(x.replace('p',''))
>>> newind
['5', '1', '8', '4', '2', '8']

What does -z mean in Bash?

The expression -z string is true if the length of string is zero.

Appending a vector to a vector

While saying "the compiler can reserve", why rely on it? And what about automatic detection of move semantics? And what about all that repeating of the container name with the begins and ends?

Wouldn't you want something, you know, simpler?

(Scroll down to main for the punchline)

#include <type_traits>
#include <vector>
#include <iterator>
#include <iostream>

template<typename C,typename=void> struct can_reserve: std::false_type {};

template<typename T, typename A>
struct can_reserve<std::vector<T,A>,void>:
    std::true_type
{};

template<int n> struct secret_enum { enum class type {}; };
template<int n>
using SecretEnum = typename secret_enum<n>::type;

template<bool b, int override_num=1>
using EnableFuncIf = typename std::enable_if< b, SecretEnum<override_num> >::type;
template<bool b, int override_num=1>
using DisableFuncIf = EnableFuncIf< !b, -override_num >;

template<typename C, EnableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t n ) {
  c.reserve(n);
}
template<typename C, DisableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t ) { } // do nothing

template<typename C,typename=void>
struct has_size_method:std::false_type {};
template<typename C>
struct has_size_method<C, typename std::enable_if<std::is_same<
  decltype( std::declval<C>().size() ),
  decltype( std::declval<C>().size() )
>::value>::type>:std::true_type {};

namespace adl_aux {
  using std::begin; using std::end;
  template<typename C>
  auto adl_begin(C&&c)->decltype( begin(std::forward<C>(c)) );
  template<typename C>
  auto adl_end(C&&c)->decltype( end(std::forward<C>(c)) );
}
template<typename C>
struct iterable_traits {
    typedef decltype( adl_aux::adl_begin(std::declval<C&>()) ) iterator;
    typedef decltype( adl_aux::adl_begin(std::declval<C const&>()) ) const_iterator;
};
template<typename C> using Iterator = typename iterable_traits<C>::iterator;
template<typename C> using ConstIterator = typename iterable_traits<C>::const_iterator;
template<typename I> using IteratorCategory = typename std::iterator_traits<I>::iterator_category;

template<typename C, EnableFuncIf< has_size_method<C>::value, 1>... >
std::size_t size_at_least( C&& c ) {
    return c.size();
}

template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 2>... >
std::size_t size_at_least( C&& c ) {
    using std::begin; using std::end;
  return end(c)-begin(c);
};
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  !std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 3>... >
std::size_t size_at_least( C&& c ) {
  return 0;
};

template < typename It >
auto try_make_move_iterator(It i, std::true_type)
-> decltype(make_move_iterator(i))
{
    return make_move_iterator(i);
}
template < typename It >
It try_make_move_iterator(It i, ...)
{
    return i;
}


#include <iostream>
template<typename C1, typename C2>
C1&& append_containers( C1&& c1, C2&& c2 )
{
  using std::begin; using std::end;
  try_reserve( c1, size_at_least(c1) + size_at_least(c2) );

  using is_rvref = std::is_rvalue_reference<C2&&>;
  c1.insert( end(c1),
             try_make_move_iterator(begin(c2), is_rvref{}),
             try_make_move_iterator(end(c2), is_rvref{}) );

  return std::forward<C1>(c1);
}

struct append_infix_op {} append;
template<typename LHS>
struct append_on_right_op {
  LHS lhs;
  template<typename RHS>
  LHS&& operator=( RHS&& rhs ) {
    return append_containers( std::forward<LHS>(lhs), std::forward<RHS>(rhs) );
  }
};

template<typename LHS>
append_on_right_op<LHS> operator+( LHS&& lhs, append_infix_op ) {
  return { std::forward<LHS>(lhs) };
}
template<typename LHS,typename RHS>
typename std::remove_reference<LHS>::type operator+( append_on_right_op<LHS>&& lhs, RHS&& rhs ) {
  typename std::decay<LHS>::type retval = std::forward<LHS>(lhs.lhs);
  return append_containers( std::move(retval), std::forward<RHS>(rhs) );
}

template<typename C>
void print_container( C&& c ) {
  for( auto&& x:c )
    std::cout << x << ",";
  std::cout << "\n";
};

int main() {
  std::vector<int> a = {0,1,2};
  std::vector<int> b = {3,4,5};
  print_container(a);
  print_container(b);
  a +append= b;
  const int arr[] = {6,7,8};
  a +append= arr;
  print_container(a);
  print_container(b);
  std::vector<double> d = ( std::vector<double>{-3.14, -2, -1} +append= a );
  print_container(d);
  std::vector<double> c = std::move(d) +append+ a;
  print_container(c);
  print_container(d);
  std::vector<double> e = c +append+ std::move(a);
  print_container(e);
  print_container(a);
}

hehe.

Now with move-data-from-rhs, append-array-to-container, append forward_list-to-container, move-container-from-lhs, thanks to @DyP's help.

Note that the above does not compile in clang thanks to the EnableFunctionIf<>... technique. In clang this workaround works.

SQL Error: ORA-00922: missing or invalid option

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

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

If you are getting this message from a Maven built war change the scope of the JDBC driver to provided, and put a copy of it in the lib directory. Like this:

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.18</version>
  <!-- put a copy in /usr/share/tomcat7/lib -->
  <scope>provided</scope>
</dependency>

Scroll / Jump to id without jQuery

on anchor tag use href and not onclick

<a href="#target1">asdf<a>

And div:

<div id="target1">some content</div>

Best way to strip punctuation from a string

For the convenience of usage, I sum up the note of striping punctuation from a string in both Python 2 and Python 3. Please refer to other answers for the detailed description.


Python 2

import string

s = "string. With. Punctuation?"
table = string.maketrans("","")
new_s = s.translate(table, string.punctuation)      # Output: string without punctuation

Python 3

import string

s = "string. With. Punctuation?"
table = str.maketrans(dict.fromkeys(string.punctuation))  # OR {key: None for key in string.punctuation}
new_s = s.translate(table)                          # Output: string without punctuation

VB.NET: Clear DataGridView

The mistake that you are making is that you seem to be using a dataset object for storing your data. Each time you use the following code to put data into your dataset you add data to the data already in your dataset.

myDataAdapter.Fill(myDataSet)

If you assign the table in your dataset to a DataGridView object in your program by the following code you will get duplicate results because you have not cleared data which is already residing in your dataset and in your dataset table.

myDataGridView.DataSource = myDataSet.Tables(0)

To avoid replicating the data you have to call clear method on your dataset object.

myDataSet.clear()

An then assign the table in your dataset to your DataGridView object. The code is like this.

myDataSet.clear()
myDataAdapter.Fill(myDataSet)
myDataGridView.DataSource = myDataSet.Tables(0)

You can try this code:

' clear previous data
DataGridView2.DataSource = Nothing
DataGridView2.DataMember = Nothing
DataGridView2.Refresh()
Try
    connection.Open()
    adapter1 = New SqlDataAdapter(sql, connection)
    ' clear data already in the dataset
    ds1.Clear()
    adapter1.Fill(ds1)
    DataGridView2.DataSource = ds1.Tables(0)
    connection.Close()
Catch ex As Exception
    MsgBox(ex.ToString)
End Try

Delete a row from a table by id

And what about trying not to delete but hide that row?

How to get to a particular element in a List in java?

You have about 98% right. The only issue is that you're trying to print out an String[] which does not print the way you'd like. Instead try this...

for (String[] s : myEntries) {
    System.out.print("Next item: " + s[0]);
    for(int i = 1; i < s.length; i++) {
        System.out.print(", " + s[i]);
    }
    System.out.println("");
}

This way you're accessing each string in the array instead of the array itself.

Hope this helps!

Python script to convert from UTF-8 to ASCII

UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

Overlaying a DIV On Top Of HTML 5 Video

<div id="video_box">
  <div id="video_overlays"></div>
  <div>
    <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm" onclick="this.play();">Your browser does not support this streaming content.</video>
  </div>
</div>

for this you need to just add css like this:

#video_overlays {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.46);
  z-index: 2;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
#video_box{position: relative;}

UIView background color in Swift

I see that this question is solved, but, I want to add some information than can help someone.

if you want use hex to set background color, I found this function and work:

func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
    let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
    let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
    let blue = CGFloat(rgbValue & 0xFF)/256.0

    return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}

I use this function as follows:

view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)

some times you must use self:

self.view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)

Well that was it, I hope it helps someone .

sorry for my bad english.

this work on iOS 7.1+

Eclipse shows errors but I can't find them

I came across the same issue while working on a selenium project(maven). The Project folder and pom.xml were showing red cross symbol. This was coming as i had the test datasheet open. I could remove the error by just closing the datasheet and the never faced the issue again

Java - How do I make a String array with values?

Another way to create an array with String apart from

String[] strings =  { "abc", "def", "hij", "xyz" };

is to use split. I find this more readable if there are lots of Strings.

String[] strings =  "abc,def,hij,xyz".split(",");

or the following is good if you are parsing lines of strings from another source.

String[] strings =  ("abc\n" +
                     "def\n" +
                     "hij\n" +
                     "xyz").split("\n");

SQL Server Text type vs. varchar data type

TEXT is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.

VARCHAR is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x), where x > 8000, you get an error:

Server: Msg 131, Level 15, State 3, Line 1

The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)

These length limitations do not concern VARCHAR(MAX) in SQL Server 2005, which may be stored out of row, just like TEXT.

Note that MAX is not a kind of constant here, VARCHAR and VARCHAR(MAX) are very different types, the latter being very close to TEXT.

In prior versions of SQL Server you could not access the TEXT directly, you only could get a TEXTPTR and use it in READTEXT and WRITETEXT functions.

In SQL Server 2005 you can directly access TEXT columns (though you still need an explicit cast to VARCHAR to assign a value for them).

TEXT is good:

  • If you need to store large texts in your database
  • If you do not search on the value of the column
  • If you select this column rarely and do not join on it.

VARCHAR is good:

  • If you store little strings
  • If you search on the string value
  • If you always select it or use it in joins.

By selecting here I mean issuing any queries that return the value of the column.

By searching here I mean issuing any queries whose result depends on the value of the TEXT or VARCHAR column. This includes using it in any JOIN or WHERE condition.

As the TEXT is stored out of row, the queries not involving the TEXT column are usually faster.

Some examples of what TEXT is good for:

  • Blog comments
  • Wiki pages
  • Code source

Some examples of what VARCHAR is good for:

  • Usernames
  • Page titles
  • Filenames

As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT.

Otherwise use VARCHAR.

P.S. The same applies to UNICODE enabled NTEXT and NVARCHAR as well, which you should use for examples above.

P.P.S. The same applies to VARCHAR(MAX) and NVARCHAR(MAX) that SQL Server 2005+ uses instead of TEXT and NTEXT. You'll need to enable large value types out of row for them with sp_tableoption if you want them to be always stored out of row.

As mentioned above and here, TEXT is going to be deprecated in future releases:

The text in row option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently use text in row. We recommend that you store large data by using the varchar(max), nvarchar(max), or varbinary(max) data types. To control in-row and out-of-row behavior of these data types, use the large value types out of row option.

Returning Month Name in SQL Server Query

This will give you what u are requesting for:

select convert(varchar(3),datename(month, S0.OrderDateTime)) 

Clear the value of bootstrap-datepicker

You can use this syntax to reset your bootstrap datepicker

$('#datepicker').datepicker('update','');

reference http://bootstrap-datepicker.readthedocs.org/en/latest/methods.html#update

How to make a edittext box in a dialog

Setting margin in layout params will not work in Alertdialog. you have to set padding in parent layout and then add edittext in that layout.

This is my working kotlin code...

val alert =  AlertDialog.Builder(context!!)

val edittext = EditText(context!!)
edittext.hint = "Enter Name"
edittext.maxLines = 1

val layout = FrameLayout(context!!)

//set padding in parent layout
layout.setPaddingRelative(45,15,45,0)

alert.setTitle(title)

layout.addView(edittext)

alert.setView(layout)

alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {

    dialog, which ->
    run {

        val qName = edittext.text.toString()

        Utility.hideKeyboard(context!!, dialogView!!)

    }

})
alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {

            dialog, which ->
            run {
                dismiss()
            }

})

alert.show()

Closing Application with Exit button

Don't ever put an Exit button on an Android app. Let the OS decide when to kill your Activity. Learn about the Android Activity lifecycle and implement any necessary callbacks.

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

Find the greatest number in a list of numbers

max is a builtin function in python, which is used to get max value from a sequence, i.e (list, tuple, set, etc..)

print(max([9, 7, 12, 5]))

# prints 12 

Unresponsive KeyListener for JFrame

KeyListener is low level and applies only to a single component. Despite attempts to make it more usable JFrame creates a number of component components, the most obvious being the content pane. JComboBox UI is also often implemented in a similar manner.

It's worth noting the mouse events work in a strange way slightly different to key events.

For details on what you should do, see my answer on Application wide keyboard shortcut - Java Swing.

Auto-indent in Notepad++

For those who using version 7.8.5, the Auto-indent settings is now located at "Settings" -> "Preferences..." -> "Auto-Completion".

enter image description here

Switch statement with returns -- code correctness

Personally I would remove the returns and keep the breaks. I would use the switch statement to assign a value to a variable. Then return that variable after the switch statement.

Though this is an arguable point I've always felt that good design and encapsulation means one way in and one way out. It is much easier to guarantee the logic and you don't accidentally miss cleanup code based on the cyclomatic complexity of your function.

One exception: Returning early is okay if a bad parameter is detected at the beginning of a function--before any resources are acquired.

How to filter multiple values (OR operation) in angularJS

Too late to join the party but may be it can help someone:

We can do it in two step, first filter by first property and then concatenate by second filter:

$scope.filterd = $filter('filter')($scope.empList, { dept: "account" });
$scope.filterd = $scope.filterd.concat($filter('filter')($scope.empList, { dept: "sales" }));  

See the working fiddle with multiple property filter

"No such file or directory" but it exists

As mentioned by others, this is because the loader can't be found, not your executable file. Unfortunately the message is not clear enough.

You can fix it by changing the loader that your executable uses, see my thorough answer in this other question: Multiple glibc libraries on a single host

Basically you have to find which loader it's trying to use:

$ readelf -l arm-mingw32ce-g++ | grep interpreter
  [Requesting program interpreter: /lib/ld-linux.so.2]

Then find the right path for an equivalent loader, and change your executable to use the loader from the path that it really is:

$ ./patchelf --set-interpreter /path/to/newglibc/ld-linux.so.2 arm-mingw32ce-g++

You will probably need to set the path of the includes too, you will know if you want it or not after you try to run it. See all the details in that other thread.

How do I get the day of week given a date?

A solution whithout imports for dates after 1700/1/1

def weekDay(year, month, day):
    offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
    week   = ['Sunday', 
              'Monday', 
              'Tuesday', 
              'Wednesday', 
              'Thursday',  
              'Friday', 
              'Saturday']
    afterFeb = 1
    if month > 2: afterFeb = 0
    aux = year - 1700 - afterFeb
    # dayOfWeek for 1700/1/1 = 5, Friday
    dayOfWeek  = 5
    # partial sum of days betweem current date and 1700/1/1
    dayOfWeek += (aux + afterFeb) * 365                  
    # leap year correction    
    dayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400     
    # sum monthly and day offsets
    dayOfWeek += offset[month - 1] + (day - 1)               
    dayOfWeek %= 7
    return dayOfWeek, week[dayOfWeek]

print weekDay(2013, 6, 15) == (6, 'Saturday')
print weekDay(1969, 7, 20) == (0, 'Sunday')
print weekDay(1945, 4, 30) == (1, 'Monday')
print weekDay(1900, 1, 1)  == (1, 'Monday')
print weekDay(1789, 7, 14) == (2, 'Tuesday')

How to assign more memory to docker container

Allocate maximum memory to your docker machine from (docker preference -> advance )

Screenshot of advance settings: Screenshot of advance settings.

This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.

docker run -m=4g {imageID}

Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.

Go back button in a page

You can either use:

<button onclick="window.history.back()">Back</button>

or..

<button onclick="window.history.go(-1)">Back</button>

The difference, of course, is back() only goes back 1 page but go() goes back/forward the number of pages you pass as a parameter, relative to your current page.

Looping through GridView rows and Checking Checkbox Control

Loop like

foreach (GridViewRow row in grid.Rows)
{
   if (((CheckBox)row.FindControl("chkboxid")).Checked)
   {
    //read the label            
   }            
}

How To Show And Hide Input Fields Based On Radio Button Selection

Replace all instances of visibility style to display

display:none //to hide
display:block //to show

Here's updated jsfiddle: http://jsfiddle.net/QAaHP/16/

You can do it using Mootools or jQuery functions to slide up/down but if you don't need animation effect it's probably too much for what you need.

CSS display is a faster and simpler approach.

jQuery - Call ajax every 10 seconds

Are you going to want to do a setInterval()?

setInterval(function(){get_fb();}, 10000);

Or:

setInterval(get_fb, 10000);

Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).success(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Or use .ajax().complete() if you want it to run regardless of result:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).complete(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.

http://jsfiddle.net/YXMPn/

Node update a specific package

Use npm outdated to see Current and Latest version of all packages.


Then npm i packageName@versionNumber to install specific version : example npm i [email protected].

Or npm i packageName@latest to install latest version : example npm i browser-sync@latest.

How to get HttpContext.Current in ASP.NET Core?

There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)

app.Use(async (httpContext, next) =>
{
    CallContext.LogicalSetData("CurrentContextKey", httpContext);
    try
    {
        await next();
    }
    finally
    {
        CallContext.FreeNamedDataSlot("CurrentContextKey");
    }
});

And when you need it you can get it with :

HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;

I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.

Assign output of os.system to a variable and prevent it from being displayed on the screen

The commands module is a reasonably high-level way to do this:

import commands
status, output = commands.getstatusoutput("cat /etc/services")

status is 0, output is the contents of /etc/services.

What is the attribute property="og:title" inside meta tag?

The property in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.

For example, to use that code you would have to have something like this in your <head tag. <head xmlns:og="http://example.org/"> and inside the http://example.org/ there would be a specification for title (og:title).

The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).

Generating Request/Response XML from a WSDL

Since you are saying the webservice is not live right now, you can do it by creating mockservices which will create the sample response format.

Javascript call() & apply() vs bind()?

Use bind for future calls to the function. Both apply and call invoke the function.

bind() also allows for additional arguments to be perpended to the args array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

RecyclerView expand/collapse items

Use two view types in the your RVAdapter. One for expanded layout and other for collapsed. And the magic happens with setting android:animateLayoutChanges="true" for RecyclerView Checkout the effect achieved using this at 0:42 in this video

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

Delete rows with blank values in one particular column

An easy approach would be making all the blank cells NA and only keeping complete cases. You might also look for na.omit examples. It is a widely discussed topic.

df[df==""]<-NA
df<-df[complete.cases(df),]

Comparing date part only without comparing time in JavaScript

This works for me:

 export default (chosenDate) => {
  const now = new Date();
  const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
  const splitChosenDate = chosenDate.split('/');

  today.setHours(0, 0, 0, 0);
  const fromDate = today.getTime();
  const toDate = new Date(splitChosenDate[2], splitChosenDate[1] - 1, splitChosenDate[0]).getTime();

  return toDate < fromDate;
};

In accepted answer, there is timezone issue and in the other time is not 00:00:00

Environment variables for java installation

The JDK installation instructions explain exactly how to set the PATH, for different versions of Windows.

Normally you should not set the CLASSPATH environment variable. If you leave it unset, Java will look in the current directory to find classes. You can use the -cp or -classpath command line switch with java or javac.

Excel date to Unix timestamp

To make up for the daylight saving time (starting on March's last sunday until October's last sunday) I had to use the following formula:

=IF(
  AND(
    A2>=EOMONTH(DATE(YEAR(A2);3;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);3;1);0);11);7);
    A2<=EOMONTH(DATE(YEAR(A2);10;1);0)-MOD(WEEKDAY(EOMONTH(DATE(YEAR(A2);10;1);0);11);7)
  );
  (A2-DATE(1970;1;1)-TIME(1;0;0))*24*60*60*1000;
  (A2-DATE(1970;1;1))*24*60*60*1000
)

Quick explanation:

If the date ["A2"] is between March's last sunday and October's last sunday [third and fourth code lines], then I'll be subtracting one hour [-TIME(1;0;0)] to the date.

What does SQL clause "GROUP BY 1" mean?

That means sql group by 1st column in your select clause, we always use this GROUP BY 1 together with ORDER BY 1, besides you can also use like this GROUP BY 1,2,3.., of course it is convenient for us but you need to pay attention to that condition the result may be not what you want if some one has modified your select columns, and it's not visualized

Fetch frame count with ffmpeg

Calculate it based on time, instead.

That's what I do and it works great for me, and many others. First, find the length of the video in the below snippet:

Seems stream 0 codec frame rate differs from container frame rate: 5994.00 
(5994/1) -> 29.97 (30000/1001)
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/stu/Movies/District9.mov':
  Duration: 00:02:32.20, start: 0.000000, bitrate: 9808 kb/s
    Stream #0.0(eng): Video: h264, yuv420p, 1920x1056, 29.97tbr, 2997tbn, 5994tbc
    Stream #0.1(eng): Audio: aac, 44100 Hz, 2 channels, s16
    Stream #0.2(eng): Data: tmcd / 0x64636D74

You'll should be able to consistently and safely find Duration: hh:mm:ss.nn to determine the source video clip size. Then, for each update line (CR, no LF) you can parse the text for the current time mark it is at:

frame=   84 fps= 18 q=10.0 size=       5kB time=1.68 bitrate=  26.1kbits/s    
frame=   90 fps= 17 q=10.0 size=       6kB time=1.92 bitrate=  23.8kbits/s    
frame=   94 fps= 16 q=10.0 size=     232kB time=2.08 bitrate= 913.0kbits/s    

Just be careful to not always expect perfect output from these status lines. They can include error messages like here:

frame=   24 fps= 24 q=-1.0 size=       0kB time=1.42 bitrate=   0.3kbits/s    
frame=   41 fps= 26 q=-1.0 size=       0kB time=2.41 bitrate=   0.2kbits/s    
[h264 @ 0x1013000]Cannot parallelize deblocking type 1, decoding such frames in
sequential order
frame=   49 fps= 24 q=26.0 size=       4kB time=0.28 bitrate= 118.1kbits/s    
frame=   56 fps= 22 q=23.0 size=       4kB time=0.56 bitrate=  62.9kbits/s    

Once you have the time, it is simple math: time / duration * 100 = % done.

Try-catch block in Jenkins pipeline script

Look up the AbortException class for Jenkins. You should be able to use the methods to get back simple messages or stack traces. In a simple case, when making a call in a script block (as others have indicated), you can call getMessage() to get the string to echo to the user. Example:

script {
        try {
            sh "sudo docker rmi frontend-test"
        } catch (err) {
            echo err.getMessage()
            echo "Error detected, but we will continue."
        }
        ...continue with other code...
}

How to dump a table to console?

Adding another version. This one tries to iterate over userdata as well.

function inspect(o,indent)
    if indent == nil then indent = 0 end
    local indent_str = string.rep("    ", indent)
    local output_it = function(str)
        print(indent_str..str)
    end

    local length = 0

    local fu = function(k, v)
        length = length + 1
        if type(v) == "userdata" or type(v) == 'table' then
            output_it(indent_str.."["..k.."]")
            inspect(v, indent+1)
        else
            output_it(indent_str.."["..k.."] "..tostring(v))
        end
    end

    local loop_pairs = function()
        for k,v in pairs(o) do fu(k,v) end
    end

    local loop_metatable_pairs = function()
        for k,v in pairs(getmetatable(o)) do fu(k,v) end
    end

    if not pcall(loop_pairs) and not pcall(loop_metatable_pairs) then
        output_it(indent_str.."[[??]]")
    else
        if length == 0 then
            output_it(indent_str.."{}")
        end
    end
end

Why are the Level.FINE logging messages not showing?

This solution appears better to me, regarding maintainability and design for change:

  1. Create the logging property file embedding it in the resource project folder, to be included in the jar file:

    # Logging
    handlers = java.util.logging.ConsoleHandler
    .level = ALL
    
    # Console Logging
    java.util.logging.ConsoleHandler.level = ALL
    
  2. Load the property file from code:

    public static java.net.URL retrieveURLOfJarResource(String resourceName) {
       return Thread.currentThread().getContextClassLoader().getResource(resourceName);
    }
    
    public synchronized void initializeLogger() {
       try (InputStream is = retrieveURLOfJarResource("logging.properties").openStream()) {
          LogManager.getLogManager().readConfiguration(is);
       } catch (IOException e) {
          // ...
       }
    }
    

How to set default value to the input[type="date"]

Use Microsoft Visual Studio

Date separator '-'

@{string dateValue = request.Date.ToString("yyyy'-'MM'-'ddTHH:mm:ss");}

< input type="datetime-local" class="form-control" name="date1" value="@dateValue" >

How to take complete backup of mysql database using mysqldump command line utility

To create dump follow below steps:

  1. Open CMD and go to bin folder where you have installed your MySQL
    ex:C:\Program Files\MySQL\MySQL Server 8.0\bin. If you see in this
    folder mysqldump.exe will be there. Or you have setup above folder in your Path variable of Environment Variable.

  2. Now if you hit mysqldump in CMD you can see CMD is able to identify dump command.

  3. Now run "mysqldump -h [host] -P [port] -u [username] -p --skip-triggers --no-create-info --single-transaction --quick --lock-tables=false ABC_databse > c:\xyz.sql"
  4. Above command will prompt for password then it will start processing.

How do I get the latest version of my code?

I understand you want to trash your local changes and pull down what's on your remote?

If all else fails, and if you're (quite understandably) scared of "reset", the simplest thing is just to clone origin into a new directory and trash your old one.

How to programmatically determine the current checked out Git branch

If you are using gradle,

```

def gitHash = new ByteArrayOutputStream()    
project.exec {
                commandLine 'git', 'rev-parse', '--short', 'HEAD'
                standardOutput = gitHash
            }

def gitBranch = new ByteArrayOutputStream()   
project.exec {
                def gitCmd = "git symbolic-ref --short -q HEAD || git branch -rq --contains "+getGitHash()+" | sed -e '2,\$d'  -e 's/\\(.*\\)\\/\\(.*\\)\$/\\2/' || echo 'master'"
                commandLine "bash", "-c", "${gitCmd}"
                standardOutput = gitBranch
            }

```

Let JSON object accept bytes or let urlopen output strings

HTTP sends bytes. If the resource in question is text, the character encoding is normally specified, either by the Content-Type HTTP header or by another mechanism (an RFC, HTML meta http-equiv,...).

urllib should know how to encode the bytes to a string, but it's too naïve—it's a horribly underpowered and un-Pythonic library.

Dive Into Python 3 provides an overview about the situation.

Your "work-around" is fine—although it feels wrong, it's the correct way to do it.

undefined reference to WinMain@16 (codeblocks)

You should create a new project in Code::Blocks, and make sure it's 'Console Application'.

Add your .cpp files into the project so they are all compiled and linked together.

git status shows modifications, git checkout -- <file> doesn't remove them

Normally, in GIT to clear all your modifications & new files the following 2 commands should work very nicely (be CAREFUL, this will delete all your new files+folders you may have created & will restore all your modified files to the state of your current commit):

$ git clean --force -d
$ git checkout -- .

Maybe a better option sometimes is just doing "git stash push" with optional message, like so:

$ git stash push -m "not sure if i will need this later"

This will also clear all your new and modified files, but you'll have all of them stashed in case you want to restore them. Stash in GIT carries from branch to branch, so you can restore them in a different branch, if you wish to.

As a side note, in case you have already staged some newly added files and want to get rid of them, this should do the trick:

$ git reset --hard

If all of the above doesn't work for you, read below what worked for me a while ago:

I ran into this problem few times before. I'm currently developing on Windows 10 machine provided by my employer. Today, this particular git behavior was caused by me creating a new branch from my "develop" branch. For some reason, after I switched back to "develop" branch, some seemingly random files persisted and were showing up as "modified" in "git status".

Also, at that point I couldn't checkout another branch, so I was stuck on my "develop" branch.

This is what I did:

$ git log

I noticed that the new branch I created from "develop" earlier today was showing in the first "commit" message, being referenced at the end "HEAD -> develop, origin/develop, origin/HEAD, The-branch-i-created-earlier-today".

Since I didn't really need it, I deleted it:

$ git branch -d The-branch-i-created-earlier-today

The changed files were still showing up, so I did:

$ git stash

This solved my problem:

$ git status
On branch develop
Your branch is up to date with 'origin/develop'.

nothing to commit, working tree clean

Of course $ git stash list will show stashed changes, and since I had few and didn't need any of my stashes, I did $ git stash clear to DELETE ALL STASHES.

NOTE: I haven't tried doing what someone suggested here before me:

$ git rm --cached -r .
$ git reset --hard

This may have worked as well, I'll be sure to try it next time I run into this problem.

Convert a char to upper case using regular expressions (EditPad Pro)

You can also capitalize the first letter of the match using \I1 and \I2 etc instead of $1 and $2.

How can I get a JavaScript stack trace when I throw an exception?

<script type="text/javascript"
src="https://rawgithub.com/stacktracejs/stacktrace.js/master/stacktrace.js"></script>
<script type="text/javascript">
    try {
        // error producing code
    } catch(e) {
        var trace = printStackTrace({e: e});
        alert('Error!\n' + 'Message: ' + e.message + '\nStack trace:\n' + trace.join('\n'));
        // do something else with error
    }
</script>

this script will show the error

Is there any method to get the URL without query string?

Use properties of window.location

var loc = window.location;
var withoutQuery = loc.hostname + loc.pathname;
var includingProtocol = loc.protocol + "//" + loc.hostname + loc.pathname;

You can see more properties at https://developer.mozilla.org/en/DOM/window.location

How to exit from Python without traceback?

something like import sys; sys.exit(0) ?

error: command 'gcc' failed with exit status 1 while installing eventlet

sudo apt install gcc

It works for PyCharm on Ubuntu 20.10.

get next and previous day with PHP

Requirement: PHP 5 >= 5.2.0

You should make use of the DateTime and DateInterval classes in Php, and things will turn to be very easy and readable.

Example: Lets get the previous day.

// always make sure to have set your default timezone
date_default_timezone_set('Europe/Berlin');

// create DateTime instance, holding the current datetime
$datetime = new DateTime();

// create one day interval
$interval = new DateInterval('P1D');

// modify the DateTime instance
$datetime->sub($interval);

// display the result, or print_r($datetime); for more insight 
echo $datetime->format('Y-m-d');


/** 
* TIP:
* if you dont want to change the default timezone, use
* use the DateTimeZone class instead.
*
* $myTimezone = new DateTimeZone('Europe/Berlin');
* $datetime->setTimezone($myTimezone); 
*
* or just include it inside the constructor 
* in this form new DateTime("now",   $myTimezone);
*/

References: Modern PHP, New Features and Good Practices By Josh Lockhart

Increase max execution time for php

Try to set a longer max_execution_time:

<IfModule mod_php5.c>
    php_value max_execution_time 300
</IfModule>

<IfModule mod_php7.c>
    php_value max_execution_time 300
</IfModule>

URL.Action() including route values

outgoing url in mvc generated based on the current routing schema.

because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.

to solve this problem you should use UrlParameter.Optional:

 <a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>

how to add value to combobox item

Although this question is 5 years old I have come across a nice solution.

Use the 'DictionaryEntry' object to pair keys and values.

Set the 'DisplayMember' and 'ValueMember' properties to:

   Me.myComboBox.DisplayMember = "Key"
   Me.myComboBox.ValueMember = "Value"

To add items to the ComboBox:

   Me.myComboBox.Items.Add(New DictionaryEntry("Text to be displayed", 1))

To retreive items like this:

MsgBox(Me.myComboBox.SelectedItem.Key & " " & Me.myComboBox.SelectedItem.Value)

How to clear a chart from a canvas so that hover events cannot be triggered?

This worked for me. Add a call to clearChart, at the top oF your updateChart()

`function clearChart() {
    event.preventDefault();
    var parent = document.getElementById('parent-canvas');
    var child = document.getElementById('myChart');          
    parent.removeChild(child);            
    parent.innerHTML ='<canvas id="myChart" width="350" height="99" ></canvas>';             
    return;
}`

How to set seekbar min and max value

Seek Bar has methods for setting max values but not for setting min value here i write a code for setting minimum seek bar value when we add this code then your seek bar values not less then mim value try this its work fine for me

/* This methods call after seek bar value change */

            public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            /* Check the current seekbar value is greather than min value*/
            if (progress < MIN_VALUE) {
                /* if seek bar value is lesser than min value then set min value to seek bar */
                seekBar.setProgress(MIN_VALUE);
            }

        }

Laravel update model with unique validation rule for attribute

or what you could do in your Form Request is (for Laravel 5.3+)

public function rules()
    {
        return [

            'email' => 'required|email|unique:users,email,'.$this->user, //here user is users/{user} from resource's route url
               ];
    }

i've done it in Laravel 5.6 and it worked.

What is the difference between an interface and abstract class?

I am constructing a building of 300 floors

The building's blueprint interface

  • For example, Servlet(I)

Building constructed up to 200 floors - partially completed---abstract

  • Partial implementation, for example, generic and HTTP servlet

Building construction completed-concrete

  • Full implementation, for example, own servlet

Interface

  • We don't know anything about implementation, just requirements. We can go for an interface.
  • Every method is public and abstract by default
  • It is a 100% pure abstract class
  • If we declare public we cannot declare private and protected
  • If we declare abstract we cannot declare final, static, synchronized, strictfp and native
  • Every interface has public, static and final
  • Serialization and transient is not applicable, because we can't create an instance for in interface
  • Non-volatile because it is final
  • Every variable is static
  • When we declare a variable inside an interface we need to initialize variables while declaring
  • Instance and static block not allowed

Abstract

  • Partial implementation
  • It has an abstract method. An addition, it uses concrete
  • No restriction for abstract class method modifiers
  • No restriction for abstract class variable modifiers
  • We cannot declare other modifiers except abstract
  • No restriction to initialize variables

Taken from DurgaJobs Website

Sum of two input value by jquery

Cast them to a Number

$('#total_price').val(Number(a)+Number(b));

But before you do that

if (!isNaN($('input[name=service_price]').val()) {...

window.close() doesn't work - Scripts may close only the windows that were opened by it

Error messages don't get any clearer than this:

"Scripts may close only the windows that were opened by it."

If your script did not initiate opening the window (with something like window.open), then the script in that window is not allowed to close it. Its a security to prevent a website taking control of your browser and closing windows.

Javascript Src Path

If you have

<base href="/" />

It's will not load file right. Just delete it.

split string only on first instance - java

As many other answers suggest the limit approach, This can be another way

You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output

String target = "apple=fruit table price=5" ;
int x= target.indexOf("=");
System.out.println(target.substring(x+1));

How to pass parameters in GET requests with jQuery

Put your params in the data part of the ajax call. See the docs. Like so:

$.ajax({
    url: "/TestPage.aspx",
    data: {"first": "Manu","Last":"Sharma"},
    success: function(response) {
        //Do Something
    },
    error: function(xhr) {
        //Do Something to handle error
    }
});

How can I get the file name from request.FILES?

file = request.FILES['filename']
file.name           # Gives name
file.content_type   # Gives Content type text/html etc
file.size           # Gives file's size in byte
file.read()         # Reads file

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Our server calls stored procs from Java like so - works on both SQL Server 2000 & 2008:

String SPsql = "EXEC <sp_name> ?,?";   // for stored proc taking 2 parameters
Connection con = SmartPoolFactory.getConnection();   // java.sql.Connection
PreparedStatement ps = con.prepareStatement(SPsql);
ps.setEscapeProcessing(true);
ps.setQueryTimeout(<timeout value>);
ps.setString(1, <param1>);
ps.setString(2, <param2>);
ResultSet rs = ps.executeQuery();

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Simple if you have not import module then import and declare import { FormsModule } from '@angular/forms';

and if you did then you just need to remove ** formControlName='whatever' ** from input fields.

module.ts

import {FormsModule, ReactiveFormsModule} from '@angular/forms'

 imports: [
    BrowserModule,
    FormsModule, 
    ReactiveFormsModule
  ],

How to hide the border for specified rows of a table?

Use the CSS property border on the <td>s following the <tr>s you do not want to have the border.

In my example I made a class noBorder that I gave to one <tr>. Then I use a simple selector tr.noBorder td to make the border go away for all the <td>s that are inside of <tr>s with the noBorder class by assigning border: 0.

Note that you do not need to provide the unit (i.e. px) if you set something to 0 as it does not matter anyway. Zero is just zero.

_x000D_
_x000D_
table, tr, td {_x000D_
  border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
  border: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A1</td>_x000D_
    <td>B1</td>_x000D_
    <td>C1</td>_x000D_
  </tr>_x000D_
  <tr class="noBorder">_x000D_
    <td>A2</td>_x000D_
    <td>B2</td>_x000D_
    <td>C2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the output as an image:

Output from HTML

Property 'json' does not exist on type 'Object'

The other way to tackle it is to use this code snippet:

JSON.parse(JSON.stringify(response)).data

This feels so wrong but it works

System.loadLibrary(...) couldn't find native library in my case

To root cause (and maybe solve your issue in the same time), here is what you can do:

  1. Remove the jni folder and all the .mk files. You don't need these nor the NDK if you aren't compiling anything.

  2. Copy your libcalculate.so file inside <project>/libs/(armeabi|armeabi-v7a|x86|...) . When using Android Studio, it's <project>/app/src/main/jniLibs/(armeabi|armeabi-v7a|x86|...), but I see you're using eclipse.

  3. Build your APK and open it as a zip file, to check that your libcalculate.so file is inside lib/(armeabi|armeabi-v7a|x86|...).

  4. Remove and install your application

  5. Run dumpsys package packages | grep yourpackagename to get the nativeLibraryPath or legacyNativeLibraryDir of your application.

  6. Run ls on the nativeLibraryPath you had or on legacyNativeLibraryDir/armeabi, to check if your libcalculate.so is indeed there.

  7. If it's there, check if it hasn't been altered from your original libcalculate.so file: is it compiled against the right architecture, does it contain the expected symbols, are there any missing dependencies. You can analyze libcalculate.so using readelf.

In order to check step 5-7, you can use my application instead of command lines and readelf: Native Libs Monitor

PS: It's easy to get confused on where .so files should be put or generated by default, here is a summary:

  • libs/CPU_ABI inside an eclipse project

  • jniLibs/CPU_ABI inside an Android Studio project

  • jni/CPU_ABI inside an AAR

  • lib/CPU_ABI inside the final APK

  • inside the app's nativeLibraryPath on a <5.0 device, and inside the app's legacyNativeLibraryDir/CPU_ARCH on a >=5.0 device.

Where CPU_ABI is any of: armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips, mips64. Depending on which architectures you're targeting and your libs have been compiled for.

Note also that libs aren't mixed between CPU_ABI directories: you need the full set of what you're using, a lib that is inside the armeabi folder will not be installed on a armeabi-v7a device if there are any libs inside the armeabi-v7a folder from the APK.

What are .a and .so files?

.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.

.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).

Python: finding lowest integer

Python has a built in min function to help you with finding the smallest.

However, you need to convert your list items to numbers before you can find the lowest integer( what, isn't that float? )

min(float(i) for i in l)

Should I use `import os.path` or `import os`?

Interestingly enough, importing os.path will import all of os. try the following in the interactive prompt:

import os.path
dir(os)

The result will be the same as if you just imported os. This is because os.path will refer to a different module based on which operating system you have, so python will import os to determine which module to load for path.

reference

With some modules, saying import foo will not expose foo.bar, so I guess it really depends the design of the specific module.


In general, just importing the explicit modules you need should be marginally faster. On my machine:

import os.path: 7.54285810068e-06 seconds

import os: 9.21904878972e-06 seconds

These times are close enough to be fairly negligible. Your program may need to use other modules from os either now or at a later time, so usually it makes sense just to sacrifice the two microseconds and use import os to avoid this error at a later time. I usually side with just importing os as a whole, but can see why some would prefer import os.path to technically be more efficient and convey to readers of the code that that is the only part of the os module that will need to be used. It essentially boils down to a style question in my mind.

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

"SP25 work on Visual Studio 2019" is an exaggeration. It is extremely unreliable and should be avoided at all costs. I currently have to maintain a second development environment with V2015 for report development.

Bash loop ping successful

I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.

echo "Testing..."

PING_CMD="ping -t 3 -c 1 google.com > /dev/null 2>&1"

eval $PING_CMD

if [[ $? -eq 0 ]]; then
    echo "Already connected."
else
    echo -n "Waiting for connection..."

    while true; do
        eval $PING_CMD

        if [[ $? -eq 0 ]]; then
            echo
            echo Connected.
            break
        else
            sleep 0.5
            echo -n .
        fi
    done
fi

I also have a Gist of this script which I'll update with fixes and improvements as needed.

'ssh' is not recognized as an internal or external command

For Windows, first install the git base from here: https://git-scm.com/downloads

Next, set the environment variable:

  1. Press Windows+R and type sysdm.cpl
  2. Select advance -> Environment variable
  3. Select path-> edit the path and paste the below line:
C:\Program Files\Git\git-bash.exe

To test it, open the command window: press Windows+R, type cmd and then type ssh.

Waiting for HOME ('android.process.acore') to be launched

Options:

  • Click on the HOME Button on the Emulator. Wait for may be 2 seconds.... This always works for me!!!

or

  • Go with Shreya's suggestion (one with most suggestions and edited by Gray).

not-null property references a null or transient value

I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)

Classes cannot be accessed from outside package

Note that the default when you make a class is not public as far as packages are considered. Make sure that you actually write public class [MyClass] { when defining your class. I've made this mistake more times than I care to admit.

Prevent the keyboard from displaying on activity start

If you are using API level 21, you can use editText.setShowSoftInputOnFocus(false);

SQL Server: combining multiple rows into one row

There are several methods.

If you want just the consolidated string value returned, this is a good quick and easy approach

DECLARE @combinedString VARCHAR(MAX)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + stringvalue
FROM jira.customfieldValue
WHERE customfield = 12534
    AND ISSUE = 19602

SELECT @combinedString as StringValue 

Which will return your combined string.

You can also try one of the XML methods e.g.

SELECT DISTINCT Issue, Customfield, StringValues
FROM Jira.customfieldvalue v1
CROSS APPLY ( SELECT StringValues + ',' 
              FROM jira.customfieldvalue v2
              WHERE v2.Customfield = v1.Customfield 
                  AND v2.Issue = v1.issue 
              ORDER BY ID 
                  FOR XML PATH('') )  D ( StringValues )
WHERE customfield = 12534
    AND ISSUE = 19602

Where is database .bak file saved from SQL Server Management Studio?

Set registry item for your server instance. For example:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.2\MSSQLServer\BackupDirectory

Why does this CSS margin-top style not work?

I guess setting the position property of the #inner div to relative may also help achieve the effect. But anyways I tried the original code pasted in the Question on IE9 and latest Google Chrome and they already give the desirable effect without any modifications.

Generate war file from tomcat webapp folder

You can create .war file back from your existing folder.

Using this command

cd /to/your/folder/location
jar -cvf my_web_app.war *

Is there an easy way to reload css without reloading the page?

i now have this:

    function swapStyleSheet() {
        var old = $('#pagestyle').attr('href');
        var newCss = $('#changeCss').attr('href');
        var sheet = newCss +Math.random(0,10);
        $('#pagestyle').attr('href',sheet);
        $('#profile').attr('href',old);
        }
    $("#changeCss").on("click", function(event) { 
        swapStyleSheet();
    } );

make any element in your page with id changeCss with a href attribute with the new css url in it. and a link element with the starting css:

<link id="pagestyle" rel="stylesheet" type="text/css" href="css1.css?t=" />

<img src="click.jpg" id="changeCss" href="css2.css?t=">

Why do people say that Ruby is slow?

I would say Ruby is slow because not much effort has been spent in making the interpreter faster. Same applies to Python. Smalltalk is just as dynamic as Ruby or Python but performs better by a magnitude, see http://benchmarksgame.alioth.debian.org. Since Smalltalk was more or less replaced by Java and C# (that is at least 10 years ago) no more performance optimization work had been done for it and Smalltalk is still ways faster than Ruby and Python. The people at Xerox Parc and at OTI/IBM had the money to pay the people that work on making Smalltalk faster. What I don't understand is why Google doesn't spend the money for making Python faster as they are a big Python shop. Instead they spend money on development of languages like Go...

How to format JSON in notepad++

I was unable to find JSTool. Please see below url to see how I installed Notepad++

How to view Plugin Manager in Notepad++

I created JSMinNPP folder in C:\Program Files (x86)\Notepad++\plugins and copied JSMinNPP to it.

enter image description here

enter image description here

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The in operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each. In this specific case, you have to parse the JSON:

$.each(JSON.parse(myData), ...);

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

You can use numpy.ravel to return a flattened array from n-dimensional array:

>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values.

Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.

I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution: @Enumerated(EnumType.STRING)

Change mysql user password using command line

Before MySQL 5.7.6 this works from the command line:

mysql -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$w0rdf1sh');"

I don't have a mysql install to test on but I think in your case it would be

mysql -e "UPDATE mysql.user SET Password=PASSWORD('$w0rdf1sh') WHERE User='tate256';"

Infinite Recursion with Jackson JSON and Hibernate JPA issue

JsonIgnoreProperties [2017 Update]:

You can now use JsonIgnoreProperties to suppress serialization of properties (during serialization), or ignore processing of JSON properties read (during deserialization). If this is not what you're looking for, please keep reading below.

(Thanks to As Zammel AlaaEddine for pointing this out).


JsonManagedReference and JsonBackReference

Since Jackson 1.6 you can use two annotations to solve the infinite recursion problem without ignoring the getters/setters during serialization: @JsonManagedReference and @JsonBackReference.

Explanation

For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the infite loop that causes your stackoverflow error.

So, Jackson takes the forward part of the reference (your Set<BodyStat> bodyStats in Trainee class), and converts it in a json-like storage format; this is the so-called marshalling process. Then, Jackson looks for the back part of the reference (i.e. Trainee trainee in BodyStat class) and leaves it as it is, not serializing it. This part of the relationship will be re-constructed during the deserialization (unmarshalling) of the forward reference.

You can change your code like this (I skip the useless parts):

Business Object 1:

@Entity
@Table(name = "ta_trainee", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class Trainee extends BusinessObject {

    @OneToMany(mappedBy = "trainee", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @Column(nullable = true)
    @JsonManagedReference
    private Set<BodyStat> bodyStats;

Business Object 2:

@Entity
@Table(name = "ta_bodystat", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class BodyStat extends BusinessObject {

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name="trainee_fk")
    @JsonBackReference
    private Trainee trainee;

Now it all should work properly.

If you want more informations, I wrote an article about Json and Jackson Stackoverflow issues on Keenformatics, my blog.

EDIT:

Another useful annotation you could check is @JsonIdentityInfo: using it, everytime Jackson serializes your object, it will add an ID (or another attribute of your choose) to it, so that it won't entirely "scan" it again everytime. This can be useful when you've got a chain loop between more interrelated objects (for example: Order -> OrderLine -> User -> Order and over again).

In this case you've got to be careful, since you could need to read your object's attributes more than once (for example in a products list with more products that share the same seller), and this annotation prevents you to do so. I suggest to always take a look at firebug logs to check the Json response and see what's going on in your code.

Sources:

Unable to compile class for JSP

<pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>       
                <version>2.2</version>
            </plugin>
        </plugins>

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

Using setattr() in python

The Python docs say all that needs to be said, as far as I can see.

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

If this isn't enough, explain what you don't understand.

How can you tell if a value is not numeric in Oracle?

The best answer I found on internet:

SELECT case when trim(TRANSLATE(col1, '0123456789-,.', ' ')) is null
            then 'numeric'
            else 'alpha'
       end
FROM tab1;

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Here's my spin on @drzaus's answer. I modified it to use rounding errors to our advantage and correctly manage issues around unit boundaries. It also handles negative values.

Drop this C# Program into LinqPad:

// Kudos: https://stackoverflow.com/a/48467634/117797

void Main()
{
    0.ToFriendly().Dump();                      // 0 B
    857.ToFriendly().Dump();                    // 857 B
    (173*1024).ToFriendly().Dump();             // 173 KB
    (9541*1024).ToFriendly().Dump();            // 9.32 MB
    (5261890L*1024).ToFriendly().Dump();        // 5.02 GB

    1.ToFriendly().Dump();                      // 1 B
    1024.ToFriendly().Dump();                   // 1 KB
    1048576.ToFriendly().Dump();                // 1 MB
    1073741824.ToFriendly().Dump();             // 1 GB
    1099511627776.ToFriendly().Dump();          // 1 TB
    1125899906842620.ToFriendly().Dump();       // 1 PB
    1152921504606850000.ToFriendly().Dump();    // 1 EB
}

public static class Extensions
{
    static string[] _byteUnits = new[] { "B", "KB", "MB", "GB", "TB", "PB", "EB" };

    public static string ToFriendly(this int number, int decimals = 2)
    {
        return ((double)number).ToFriendly(decimals);
    }

    public static string ToFriendly(this long number, int decimals = 2)
    {
        return ((double)number).ToFriendly(decimals);
    }

    public static string ToFriendly(this double number, int decimals = 2)
    {
        const double divisor = 1024;

        int unitIndex = 0;
        var sign = number < 0 ? "-" : string.Empty;
        var value = Math.Abs(number);
        double lastValue = number;

        while (value > 1)
        {
            lastValue = value;

            // NOTE
            // The following introduces ever increasing rounding errors, but at these scales we don't care.
            // It also means we don't have to deal with problematic rounding errors due to dividing doubles.
            value = Math.Round(value / divisor, decimals);

            unitIndex++;
        }

        if (value < 1 && number != 0)
        {
            value = lastValue;
            unitIndex--;
        }

        return $"{sign}{value} {_byteUnits[unitIndex]}";
    }
}

Output is:

0 B
857 B
173 KB
9.32 MB
1.34 MB
5.02 GB
1 B
1 KB
1 MB
1 GB
1 TB
1 PB
1 EB

How can I make content appear beneath a fixed DIV element?

What you need is an extra spacing div (as far as I understood your question).

This div will be placed between the menu and content and be the same height as the menu div, paddings included.

HTML

<div id="fixed-menu">
    Navigation options or whatever.
</div>
<div class="spacer">
    &nbsp;
</div>
<div id="content">
    Content.
</div>

CSS

#fixed-menu
{
    position: fixed;
    width: 100%;
    height: 75px;
    background-color: #f00;
    padding: 10px;
}

.spacer
{
    width: 100%;
    height: 95px;
}

See my example here.

This works by offsetting the space that would have been occupied by the nav div, but as it has position: fixed; it has been taken out of the document flow.


The preferred method of achieving this effect is by using margin-top: 95px;/*your nav height*/ on your content wrapper.

WARNING: sanitizing unsafe style value url

Based on the docs at https://angular.io/api/platform-browser/DomSanitizer, the right way to do this seems to be to use sanitize. At least in Angular 7 (don't know if this changed from before). This worked for me:

import { Component, OnInit, Input, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

constructor(
    private sanitizer: DomSanitizer
) { }

this.sanitizer.sanitize(SecurityContext.STYLE, 'url(' + this.image + ')');

Re SecurityContext, see https://angular.io/api/core/SecurityContext. Basically it's just this enum:

enum SecurityContext {
  NONE: 0
  HTML: 1
  STYLE: 2
  SCRIPT: 3
  URL: 4
  RESOURCE_URL: 5
}

Run Java Code Online

there is also http://ideone.com/ (supports many languages)

JavaScript check if variable exists (is defined/initialized)

Short way to test a variable is not declared (not undefined) is

if (typeof variable === "undefined") {
  ...
}

I found it useful for detecting script running outside a browser (not having declared window variable).

Thread-safe List<T> property

In .NET Core (any version), you can use ImmutableList, which has all the functionality of List<T>.

Compiling dynamic HTML strings from database

Try this below code for binding html through attr

.directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'attrs.dynamic' , function(html){
          element.html(scope.dynamic);
          $compile(element.contents())(scope);
        });
      }
    };
  });

Try this element.html(scope.dynamic); than element.html(attr.dynamic);

Getting last month's date in php

public function getLastMonth() {
    $now = new DateTime();
    $lastMonth = $now->sub(new DateInterval('P1M'));
    return $lastMonth->format('Ym');
}

Check div is hidden using jquery

Try:

if(!$('#car2').is(':visible'))
{  
    alert('car 2 is hidden');       
}

Code-first vs Model/Database-first

Quoting the relevant parts from http://www.itworld.com/development/405005/3-reasons-use-code-first-design-entity-framework

3 reasons to use code first design with Entity Framework

1) Less cruft, less bloat

Using an existing database to generate a .edmx model file and the associated code models results in a giant pile of auto generated code. You’re implored never to touch these generated files lest you break something, or your changes get overwritten on the next generation. The context and initializer are jammed together in this mess as well. When you need to add functionality to your generated models, like a calculated read only property, you need to extend the model class. This ends up being a requirement for almost every model and you end up with an extension for everything.

With code first your hand coded models become your database. The exact files that you’re building are what generate the database design. There are no additional files and there is no need to create a class extension when you want to add properties or whatever else that the database doesn't need to know about. You can just add them into the same class as long as you follow the proper syntax. Heck, you can even generate a Model.edmx file to visualize your code if you want.

2) Greater Control

When you go DB first, you’re at the mercy of what gets generated for your models for use in your application. Occasionally the naming convention is undesirable. Sometimes the relationships and associations aren't quite what you want. Other times non transient relationships with lazy loading wreak havoc on your API responses.

While there is almost always a solution for model generation problems you might run into, going code first gives you complete and fine grained control from the get go. You can control every aspect of both your code models and your database design from the comfort of your business object. You can precisely specify relationships, constraints, and associations. You can simultaneously set property character limits and database column sizes. You can specify which related collections are to be eager loaded, or not be serialized at all. In short, you are responsible for more stuff but you’re in full control of your app design.

3)Database Version Control

This is a big one. Versioning databases is hard, but with code first and code first migrations, it’s much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database. You’re responsible for controlling your context initialization which can help you do things like seed fixed business data. You’re also responsible for creating code first migrations.

When you first enable migrations, a configuration class and an initial migration are generated. The initial migration is your current schema or your baseline v1.0. From that point on you will add migrations which are timestamped and labeled with a descriptor to help with ordering of versions. When you call add-migration from the package manager, a new migration file will be generated containing everything that has changed in your code model automatically in both an UP() and DOWN() function. The UP function applies the changes to the database, the DOWN function removes those same changes in the event you want to rollback. What’s more, you can edit these migration files to add additional changes such as new views, indexes, stored procedures, and whatever else. They will become a true versioning system for your database schema.

How to model type-safe enum types?

just discovered enumeratum. it's pretty amazing and equally amazing it's not more well known!

What is the difference between `sorted(list)` vs `list.sort()`?

What is the difference between sorted(list) vs list.sort()?

  • list.sort mutates the list in-place & returns None
  • sorted takes any iterable & returns a new list, sorted.

sorted is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:

def sorted(iterable, key=None):
    new_list = list(iterable)    # make a new list
    new_list.sort(key=key)       # sort it
    return new_list              # return it

when to use which?

  • Use list.sort when you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.)
  • Use sorted when you want to retain the original sort order or when you wish to create a new list that only your local code owns.

Can a list's original positions be retrieved after list.sort()?

No - unless you made a copy yourself, that information is lost because the sort is done in-place.

"And which is faster? And how much faster?"

To illustrate the penalty of creating a new list, use the timeit module, here's our setup:

import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)]  # list of lists
for l in lists:
    random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""

And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:

Python 2.7

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]

Python 3

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]

After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.

import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""

I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%

>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]

I also ran the above on a much smaller sort, and saw that the new sorted copy version still takes about 2% longer running time on a sort of 1000 length.

Poke ran his own code as well, here's the code:

setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
    print(t)
    print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))

He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:

10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655

Conclusion:

A large sized list being sorted with sorted making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted when I need a new sorted list of the data, and I would use list.sort when I need to sort a list in-place, and let that determine my usage.

Passing command line arguments from Maven as properties in pom.xml

For your property example do:

mvn install "-Dmyproperty=my property from command line"

Note quotes around whole property definition. You'll need them if your property contains spaces.

Making view resize to its parent when added with addSubview

Swift 4 extension using explicit constraints:

import UIKit.UIView

extension UIView {
    public func addSubview(_ subview: UIView, stretchToFit: Bool = false) {
        addSubview(subview)
        if stretchToFit {
            subview.translatesAutoresizingMaskIntoConstraints = false
            leftAnchor.constraint(equalTo: subview.leftAnchor).isActive = true
            rightAnchor.constraint(equalTo: subview.rightAnchor).isActive = true
            topAnchor.constraint(equalTo: subview.topAnchor).isActive = true
            bottomAnchor.constraint(equalTo: subview.bottomAnchor).isActive = true
        }
    }
}

Usage:

parentView.addSubview(childView) // won't resize (default behavior unchanged)
parentView.addSubview(childView, stretchToFit: false) // won't resize
parentView.addSubview(childView, stretchToFit: true) // will resize

C++ Erase vector element by value rather than by position?

You can not do that directly. You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());. See this erasing elements from vector for more details.

How to get text in QlineEdit when QpushButton is pressed in a string?

Acepted solution implemented in PyQt5

import sys
from PyQt5.QtWidgets import QApplication, QDialog, QFormLayout
from PyQt5.QtWidgets import (QPushButton, QLineEdit)

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect")
        self.pb.clicked.connect(self.button_click)

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)
        self.setLayout(layout)

        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print (shost)


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

How do I fix "Expected to return a value at the end of arrow function" warning?

The warning indicates that you're not returning something at the end of your map arrow function in every case.

A better approach to what you're trying to accomplish is first using a .filter and then a .map, like this:

this.props.comments
  .filter(commentReply => commentReply.replyTo === comment.id)
  .map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);

check if a file is open in Python

None of the other provided examples would work for me when dealing with this specific issue with excel on windows 10. The only other option I could think of was to try and rename the file or directory containing the file temporarily, then rename it back.

import os

try: 
    os.rename('file.xls', 'tempfile.xls')
    os.rename('tempfile.xls', 'file.xls')
except OSError:
    print('File is still open.')

How do I make a Windows batch script completely silent?

Just add a >NUL at the end of the lines producing the messages.

For example,

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL

Expand a div to fill the remaining width

I don't understand why people are willing to work so hard to find a pure-CSS solution for simple columnar layouts that are SO EASY using the old TABLE tag.

All Browsers still have the table layout logic... Call me a dinosaur perhaps, but I say let it help you.

_x000D_
_x000D_
<table WIDTH=100% border=0 cellspacing=0 cellpadding=2>_x000D_
  <tr>_x000D_
    <td WIDTH="1" NOWRAP bgcolor="#E0E0E0">Tree</td>_x000D_
    <td bgcolor="#F0F0F0">View</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Much less risky in terms of cross-browser compatibility too.

How do I call ::CreateProcess in c++ to launch a Windows executable?

On a semi-related note, if you want to start a process that has more privileges than your current process (say, launching an admin app, which requires Administrator rights, from the main app running as a normal user), you can't do so using CreateProcess() on Vista since it won't trigger the UAC dialog (assuming it is enabled). The UAC dialog is triggered when using ShellExecute(), though.

ORA-28001: The password has expired

you are in wrong cdb/pdb so connect to right pdb

Java: Find .txt files in specified folder

import org.apache.commons.io.filefilter.WildcardFileFilter;

.........
.........

File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);

The code above works great for me

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

You are probably missing gradle-wrapper.jar file under directory gradle/wrapper in your project.

You need to generate this file via this script in build.gradle file as below,

task wrapper(type: Wrapper) {
   gradleVersion = '2.0' // version required
}

and run task:

gradle wrapper

With gradle 2.4 (or higher) you can set up a wrapper without adding a dedicated task:

gradle wrapper --gradle-version 2.3

OR

gradle wrapper --gradle-distribution-url https://myEnterpriseRepository:7070/gradle/distributions/gradle-2.3-bin.zip

All the details can be found this link

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

How to check for valid email address?

email validation

import re
def validate(email): 
    match=re.search(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9.]*\.*[com|org|edu]{3}$)",email)
    if match:
        return 'Valid email.'
    else:
        return 'Invalid email.'

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I was having a similar issue with a customer and none of the posted resolutions did the trick. I granted the "Log on as a batch job" permission via the Local Security Policy and that finally made the Central Administration web page come up properly.

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

In [1]: 59**3*61**4*2*3*5*7*3*5*7
Out[1]: 62702371781194950
In [2]: _ % 61**4
Out[2]: 0

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

The developers of this app have not set up this app properly for Facebook Login?

If the app is still in private mode (Status and Review set to NO), then only Facebook users with role in the app can login. That unless you set it to public (Status and Review set to YES).

To add more users to be able to login to a private app:

  1. Go to https://developer.facebook.com
  2. Go to Apps -> "Your app" -> Roles
  3. Choose Add Administrator,Developer or Tester.

Subtract 1 day with PHP

How to add 1 year to a date and then subtract 1 day from it in asp.net c#

Convert.ToDateTime(txtDate.Value.Trim()).AddYears(1).AddDays(-1);

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

We can do it with another approach too, Like first of all get the hash value from js and call the ajax using that parameter and can do whatever we want

Ignore 'Security Warning' running script from command line

This is touched in "PowerShell Execution Policies in Standard Images" on Lee Holmes' Blog and "PowerShell’s Security Guiding Principles" on the Windows Power Shell Blog .

Summary Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,) or add the remote machines to your trusted hosts.

If you want to do neither, PowerShell v2 supports an -ExecutionPolicy parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...).

Android Preventing Double Click On A Button

Generic Solution

@Override
        public void onClick(View v) {
            tempDisableButton(v);
            //all the buttons view..
        }

public void tempDisableButton(View viewBtn) {
        final View button = viewBtn;

        button.setEnabled(false);
        button.postDelayed(new Runnable() {
            @Override
            public void run() {
                button.setEnabled(true);
            }
        }, 3000);
    }

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

I want to calculate the distance between two points in Java

You could also you Point2D Java API class:

public static double distance(double x1, double y1, double x2, double y2)

Example:

double distance = Point2D.distance(3.0, 4.0, 5.0, 6.0);
System.out.println("The distance between the points is " + distance);

How to flip background image using CSS?

You can flip both vertical and horizontal at the same time

    -moz-transform: scaleX(-1) scaleY(-1);
    -o-transform: scaleX(-1) scaleY(-1);
    -webkit-transform: scaleX(-1) scaleY(-1);
    transform: scaleX(-1) scaleY(-1);

And with the transition property you can get a cool flip

    -webkit-transition: transform .4s ease-out 0ms;
    -moz-transition: transform .4s ease-out 0ms;
    -o-transition: transform .4s ease-out 0ms;
    transition: transform .4s ease-out 0ms;
    transition-property: transform;
    transition-duration: .4s;
    transition-timing-function: ease-out;
    transition-delay: 0ms;

Actually it flips the whole element, not just the background-image

SNIPPET

_x000D_
_x000D_
function flip(){_x000D_
 var myDiv = document.getElementById('myDiv');_x000D_
 if (myDiv.className == 'myFlipedDiv'){_x000D_
  myDiv.className = '';_x000D_
 }else{_x000D_
  myDiv.className = 'myFlipedDiv';_x000D_
 }_x000D_
}
_x000D_
#myDiv{_x000D_
  display:inline-block;_x000D_
  width:200px;_x000D_
  height:20px;_x000D_
  padding:90px;_x000D_
  background-color:red;_x000D_
  text-align:center;_x000D_
  -webkit-transition:transform .4s ease-out 0ms;_x000D_
  -moz-transition:transform .4s ease-out 0ms;_x000D_
  -o-transition:transform .4s ease-out 0ms;_x000D_
  transition:transform .4s ease-out 0ms;_x000D_
  transition-property:transform;_x000D_
  transition-duration:.4s;_x000D_
  transition-timing-function:ease-out;_x000D_
  transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
  -moz-transform:scaleX(-1) scaleY(-1);_x000D_
  -o-transform:scaleX(-1) scaleY(-1);_x000D_
  -webkit-transform:scaleX(-1) scaleY(-1);_x000D_
  transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
_x000D_
_x000D_

How do you parse and process HTML/XML in PHP?

There are several reasons to not parse HTML by regular expression. But, if you have total control of what HTML will be generated, then you can do with simple regular expression.

Above it's a function that parses HTML by regular expression. Note that this function is very sensitive and demands that the HTML obey certain rules, but it works very well in many scenarios. If you want a simple parser, and don't want to install libraries, give this a shot:

function array_combine_($keys, $values) {
    $result = array();
    foreach ($keys as $i => $k) {
        $result[$k][] = $values[$i];
    }
    array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));

    return $result;
}

function extract_data($str) {
    return (is_array($str))
        ? array_map('extract_data', $str)
        : ((!preg_match_all('#<([A-Za-z0-9_]*)[^>]*>(.*?)</\1>#s', $str, $matches))
            ? $str
            : array_map(('extract_data'), array_combine_($matches[1], $matches[2])));
}

print_r(extract_data(file_get_contents("http://www.google.com/")));

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

You can find information and a little description of the MBDB/MBDX format here:

http://code.google.com/p/iphonebackupbrowser/

This is my application to browse the backup files. I have tried to document the format of the new files that come with iTunes 9.2.

What's wrong with nullable columns in composite primary keys?

Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input.

Per definition, NULL cannot be part of a successful comparison. Even a comparison to itself (NULL = NULL) will fail. This means a key containing NULL would not work.

Additonally, NULL is allowed in a foreign key, to mark an optional relationship.(*) Allowing it in the PK as well would break this.


(*)A word of caution: Having nullable foreign keys is not clean relational database design.

If there are two entities A and B where A can optionally be related to B, the clean solution is to create a resolution table (let's say AB). That table would link A with B: If there is a relationship then it would contain a record, if there isn't then it would not.

Joining two lists together

The two options I use are:

list1.AddRange(list2);

or

list1.Concat(list2);

However I noticed as I used that when using the AddRange method with a recursive function, that calls itself very often I got an SystemOutOfMemoryException because the maximum number of dimensions was reached.

(Message Google Translated)
The array dimensions exceeded the supported range.

Using Concat solved that issue.

Cannot connect to repo with TortoiseSVN

Run ipconfig /flushdns from a command prompt. Apparently some people seem to think I posted this answer for sheer fun. That's why they down voted my answer. Perhaps an explanation would help them. When I used "SVN Update" it said it can't connect to the SVN repository although I could ping the server. After running ipconfig /flushdns the issue was fixed.

How to use WebRequest to POST some data and read response?

Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
try
{       
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
    {
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
            sw.Write(jsonData);
    }

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
        {
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
        }
    }
}
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

How to change the MySQL root account password on CentOS7?

All,

Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.

step1. 1st stop your databases

service mysqld stop

step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"

vi /etc/my.cnf

[mysqld] skip-grant-tables

step3. 3rd start mysql

service mysqld start

step4. select mysql default database

mysql -u root

mysql>use mysql;

step4. set a new password

mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root';

step5 restart mysql database

service mysqld restart

 mysql -u root -p

enjoy :)

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

I used com.android.support.constraint:constraint-layout:1.0.0-alpha2 with classpath 'com.android.tools.build:gradle:2.1.0', it worked like charm.

How to disable the resize grabber of <textarea>?

<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>

Just an example

Web link to specific whatsapp contact

I've tried this:

<a href="whatsapp://send?abid=phonenumber&text=Hello%2C%20World!">whatsapp</a>

changing 'phonenumber' into a specific phonenumber. This doesn't work completely, but when they click on the link it does open whatsapp and if they click on a contact the message is filled in.

If you want to open a specific person in chat you can, but without text filled in.

<a href="intent://send/phonenumber#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end">test</a>

You'll probably have to make a choice between the two.

some links to help you Sharing link on WhatsApp from mobile website (not application) for Android https://www.whatsapp.com/faq/nl/android/28000012

Hope this helps

(I tested this with google chrome on an android phone)

Decrementing for loops

a = " ".join(str(i) for i in range(10, 0, -1))
print (a)

Why shouldn't `&apos;` be used to escape single quotes?

&apos; is not part of the HTML 4 standard.

&quot; is, though, so is fine to use.

How do I put a border around an Android textview?

You can set the border by two methods. One is by drawable and the second is programmatic.

Using Drawable

<shape>
    <solid android:color="@color/txt_white"/>
    <stroke android:width="1dip" android:color="@color/border_gray"/>
    <corners android:bottomLeftRadius="10dp"
             android:bottomRightRadius="0dp"
             android:topLeftRadius="10dp"
             android:topRightRadius="0dp"/>
    <padding android:bottom="0dip"
             android:left="0dip"
             android:right="0dip"
             android:top="0dip"/>
</shape>

Programmatic


public static GradientDrawable backgroundWithoutBorder(int color) {

    GradientDrawable gdDefault = new GradientDrawable();
    gdDefault.setColor(color);
    gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
                                           radius, radius });
    return gdDefault;
}

Adding a right click menu to an item

Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).

Hope this helps:

ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");

pictureBox1.ContextMenu = cm;

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

Check if all values in list are greater than a certain number

You can use all():

my_list1 = [30,34,56]
my_list2 = [29,500,43]
if all(i >= 30 for i in my_list1):
    print 'yes'
if all(i >= 30 for i in my_list2):
    print 'no'

Note that this includes all numbers equal to 30 or higher, not strictly above 30.

error::make_unique is not a member of ‘std’

This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:

set(CMAKE_CXX_STANDARD 14).

Example:

cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)

# Rest of your declarations...

Take a list of numbers and return the average

You want to iterate through the list, sum all the numbers, and then divide the sum by the number of elements in the list. You can use a for loop to accomplish this.

average = 0
sum = 0    
for n in numbers:
    sum = sum + n
average = sum / len(numbers)

The for loop looks at each element in the list, and then adds it to the current sum. You then divide by the length of the list (or the number of elements in the list) to find the average.

I would recommend googling a python reference to find out how to use common programming concepts like loops and conditionals so that you feel comfortable when starting out. There are lots of great resources online that you could look up.

Good luck!

How to set image width to be 100% and height to be auto in react native?

"resizeMode" isn't style property. Should move to Image component's Props like below code.

const win = Dimensions.get('window');

const styles = StyleSheet.create({
    image: {
        flex: 1,
        alignSelf: 'stretch',
        width: win.width,
        height: win.height,
    }
});

...
    <Image 
       style={styles.image}
       resizeMode={'contain'}   /* <= changed  */
       source={require('../../../images/collection-imag2.png')} /> 
...

Image's height won't become automatically because Image component is required both width and height in style props. So you can calculate by using getSize() method for remote images like this answer and you can also calculate image ratio for static images like this answer.

There are a lot of useful open source libraries -

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

As mentioned in the comments, the Starting Guide is the place to start with Java 11 and JavaFX 11.

The key to work as you did before Java 11 is to understand that:

  • JavaFX 11 is not part of the JDK anymore
  • You can get it in different flavors, either as an SDK or as regular dependencies (maven/gradle).
  • You will need to include it to the module path of your project, even if your project is not modular.

JavaFX project

If you create a regular JavaFX default project in IntelliJ (without Maven or Gradle) I'd suggest you download the SDK from here. Note that there are jmods as well, but for a non modular project the SDK is preferred.

These are the easy steps to run the default project:

  1. Create a JavaFX project
  2. Set JDK 11 (point to your local Java 11 version)
  3. Add the JavaFX 11 SDK as a library. The URL could be something like /Users/<user>/Downloads/javafx-sdk-11/lib/. Once you do this you will notice that the JavaFX classes are now recognized in the editor.

JavaFX 11 Project

  1. Before you run the default project, you just need to add these to the VM options:

    --module-path /Users/<user>/Downloads/javafx-sdk-11/lib --add-modules=javafx.controls,javafx.fxml

  2. Run

Maven

If you use Maven to build your project, follow these steps:

  1. Create a Maven project with JavaFX archetype
  2. Set JDK 11 (point to your local Java 11 version)
  3. Add the JavaFX 11 dependencies.

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>11</version>
        </dependency>
    </dependencies>
    

Once you do this you will notice that the JavaFX classes are now recognized in the editor.

JavaFX 11 Maven project

You will notice that Maven manages the required dependencies for you: it will add javafx.base and javafx.graphics for javafx.controls, but most important, it will add the required classifier based on your platform. In my case, Mac.

This is why your jars org.openjfx:javafx-controls:11 are empty, because there are three possible classifiers (windows, linux and mac platforms), that contain all the classes and the native implementation.

In case you still want to go to your .m2 repo and take the dependencies from there manually, make sure you pick the right one (for instance .m2/repository/org/openjfx/javafx-controls/11/javafx-controls-11-mac.jar)

  1. Replace default maven plugins with those from here.

  2. Run mvn compile javafx:run, and it should work.

Similar works as well for Gradle projects, as explained in detail here.

EDIT

The mentioned Getting Started guide contains updated documentation and sample projects for IntelliJ:

Postgres user does not exist?

By psql --help, when you didn't set options for database name (without -d option) it would be your username, if you didn't do -U, the database username would be your username too, etc.

But by initdb (to create the first database) command it doesn't have your username as any database name. It has a database named postgres. The first database is always created by the initdb command when the data storage area is initialized. This database is called postgres.

So if you don't have another database named your username, you need to do psql -d postgres for psql command to work. And it seems it gives -d option by default, psql postgres also works.

If you have created another database names the same to your username, (it should be done with createdb) then you may command psql only. And it seems the first database user name sets as your machine username by brew.

psql -d <first database name> -U <first database user name>

or,

psql -d postgres -U <your machine username>
psql -d postgres

would work by default.

Truncate a string straight JavaScript

_x000D_
_x000D_
var pa = document.getElementsByTagName('p')[0].innerHTML;_x000D_
var rpa = document.getElementsByTagName('p')[0];_x000D_
// console.log(pa.slice(0, 30));_x000D_
var newPa = pa.slice(0, 29).concat('...');_x000D_
rpa.textContent = newPa;_x000D_
console.log(newPa)
_x000D_
<p>_x000D_
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here_x000D_
</p>
_x000D_
_x000D_
_x000D_

C/C++ include header file order

I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:

#include <set>
#include <vector>
#include <algorithm>
#include <functional>

I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.

Error Code: 1005. Can't create table '...' (errno: 150)

I had the very same error message. Finally I figured out I misspelled the name of the table in the command:

ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES country (id);

versus

ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES countries (id);

I wonder why on earth MySQL cannot tell such a table does not exist...

How to check if a Unix .tar.gz file is a valid file without uncompressing?

> use the -O option. [...] If the tar file is corrupt, the process will abort with an error.

Sometimes yes, but sometimes not. Let's see an example of a corrupted file:

echo Pete > my_name
tar -cf my_data.tar my_name 

# // Simulate a corruption
sed < my_data.tar 's/Pete/Fool/' > my_data_now.tar
# // "my_data_now.tar" is the corrupted file

tar -xvf my_data_now.tar -O

It shows:

my_name
Fool  

Even if you execute

echo $?

tar said that there was no error:

0

but the file was corrupted, it has now "Fool" instead of "Pete".

How to get all Errors from ASP.Net MVC modelState?

As I discovered having followed the advice in the answers given so far, you can get exceptions occuring without error messages being set, so to catch all problems you really need to get both the ErrorMessage and the Exception.

String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors)
                                                           .Select( v => v.ErrorMessage + " " + v.Exception));

or as an extension method

public static IEnumerable<String> GetErrors(this ModelStateDictionary modelState)
{
      return modelState.Values.SelectMany(v => v.Errors)
                              .Select( v => v.ErrorMessage + " " + v.Exception).ToList();

}

adding directory to sys.path /PYTHONPATH

As to me, i need to caffe to my python path. I can add it's path to the file /home/xy/.bashrc by add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH.

to my /home/xy/.bashrc file.

But when I use pycharm, the path is still not in.

So I can add path to PYTHONPATH variable, by run -> edit Configuration.

enter image description here

Border Radius of Table is not working

<div class="leads-search-table">
                    <div class="row col-md-6 col-md-offset-2 custyle">
                    <table class="table custab bordered">
                    <thead>

                        <tr>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Parent ID</th>
                            <th class="text-center">Action</th>
                        </tr>
                    </thead>
                            <tr>
                                <td>1</td>
                                <td>News</td>
                                <td>News Cate</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                            <tr>
                                <td>2</td>
                                <td>Products</td>
                                <td>Main Products</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                            <tr>
                                <td>3</td>
                                <td>Blogs</td>
                                <td>Parent Blogs</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                    </table>
                    </div>
                </div>

Css

.custab{
    border: 1px solid #ccc;
    margin: 5% 0;
    transition: 0.5s;
    background-color: #fff;
    -webkit-border-radius:4px;
    border-radius: 4px;
    border-collapse: separate;
}

Invalid shorthand property initializer

In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas "," after each property. but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

MySQL Great Circle Distance (Haversine formula)

$greatCircleDistance = acos( cos($latitude0) * cos($latitude1) * cos($longitude0 - $longitude1) + sin($latitude0) * sin($latitude1));

with latitude and longitude in radian.

so

SELECT 
  acos( 
      cos(radians( $latitude0 ))
    * cos(radians( $latitude1 ))
    * cos(radians( $longitude0 ) - radians( $longitude1 ))
    + sin(radians( $latitude0 )) 
    * sin(radians( $latitude1 ))
  ) AS greatCircleDistance 
 FROM yourTable;

is your SQL query

to get your results in Km or miles, multiply the result with the mean radius of Earth (3959 miles,6371 Km or 3440 nautical miles)

The thing you are calculating in your example is a bounding box. If you put your coordinate data in a spatial enabled MySQL column, you can use MySQL's build in functionality to query the data.

SELECT 
  id
FROM spatialEnabledTable
WHERE 
  MBRWithin(ogc_point, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))

Adding a favicon to a static HTML page

Actually, to make your favicon work in all browsers, you must have more than 10 images in the correct sizes and formats.

I created an App (faviconit.com) so people don´t have to create all these images and the correct tags by hand.

Hope you like it.

Regex: match everything but specific pattern

Just match /^index\.php/ then reject whatever matches it.

DataTables fixed headers misaligned with columns in wide tables

The following is a way to achieve a fixed header table, I don't know if it will be enough for your purpose. Changes are:

  1. use "bScrollCollapse" instead of "sScrollXInner"
  2. don't use fieldset to wrap table
  3. add a "div.box" css class

It seems fully working on my local machine, but it's not fully working using Fiddle. It seems that Fiddle adds a css file (normalize.css) that in some way broke the plugin css (quite sure I can make fully working also in Fiddle adding some css clear rules, but not have time to investigate further now)

My working code snippet is below. Hope this can help.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
  <script type='text/javascript' src="http://datatables.net/release-datatables/media/js/jquery.dataTables.min.js"></script>

 <style type='text/css'>
       div.box {
       height: 100px;
       padding: 10px;
       overflow: auto;
       border: 1px solid #8080FF;
       background-color: #E5E5FF;
   }

  .standard-grid1, .standard-grid1 td, .standard-grid1 th {
    border: solid black thin;
   }
</style>

<script type='text/javascript'> 
$(window).load(function(){
$(document).ready(function() {
    var stdTable1 = $(".standard-grid1").dataTable({
        "iDisplayLength": -1,
        "bPaginate": true,
        "iCookieDuration": 60,
        "bStateSave": false,
        "bAutoWidth": false,
        //true
        "bScrollAutoCss": true,
        "bProcessing": true,
        "bRetrieve": true,
        "bJQueryUI": true,
        "sDom": '<"H"CTrf>t<"F"lip>',
        "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
        "sScrollX": "100%",
        //"sScrollXInner": "110%",
        "bScrollCollapse": true,
        "fnInitComplete": function() {
            this.css("visibility", "visible");
        }
    });
});
});

</script>


</head>
<body>
<div>
    <table class="standard-grid1 full-width content-scrollable" id="PeopleIndexTable">
        <thead>
          <!-- put your table header HTML here -->
       </thead>
       <tbody>
          <!-- put your table body HTML here -->
        </tbody>
    </table>
</div>
</body>
</html>

How do you do a deep copy of an object in .NET?

You can try this

    public static object DeepCopy(object obj)
    {
        if (obj == null)
            return null;
        Type type = obj.GetType();

        if (type.IsValueType || type == typeof(string))
        {
            return obj;
        }
        else if (type.IsArray)
        {
            Type elementType = Type.GetType(
                 type.FullName.Replace("[]", string.Empty));
            var array = obj as Array;
            Array copied = Array.CreateInstance(elementType, array.Length);
            for (int i = 0; i < array.Length; i++)
            {
                copied.SetValue(DeepCopy(array.GetValue(i)), i);
            }
            return Convert.ChangeType(copied, obj.GetType());
        }
        else if (type.IsClass)
        {

            object toret = Activator.CreateInstance(obj.GetType());
            FieldInfo[] fields = type.GetFields(BindingFlags.Public |
                        BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (FieldInfo field in fields)
            {
                object fieldValue = field.GetValue(obj);
                if (fieldValue == null)
                    continue;
                field.SetValue(toret, DeepCopy(fieldValue));
            }
            return toret;
        }
        else
            throw new ArgumentException("Unknown type");
    }

Thanks to DetoX83 article on code project.

Use multiple @font-face rules in CSS

Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}

Declared rules can be used by following

/* Regular */
font-family: Montserrat;


/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;

When to use the JavaScript MIME type application/javascript instead of text/javascript?

The problem with Javascript's MIME type is that there hasn't been a standard for years. Now we've got application/javascript as an official MIME type.

But actually, the MIME type doesn't matter at all, as the browser can determine the type itself. That's why the HTML5 specs state that the type="text/javascript" is no longer required.

Authorize a non-admin developer in Xcode / Mac OS

For me, I found the suggestion in the following thread helped:

Stop "developer tools access needs to take control of another process for debugging to continue" alert

It suggested running the following command in the Terminal application:

sudo /usr/sbin/DevToolsSecurity --enable

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

Check that you are extending CI_Controller class in your controller and in the view you have to echo base_url($path) function, otherwise it will not work.

angular js unknown provider

This took me way too long to track down. Make sure you minisafe your controller within your directive.

.directive('my_directive', ['injected_item', function (injected_item){

  return {

    controller: ['DO_IT_HERE_TOO', function(DO_IT_HERE_TOO){

    }]
  }
}

Hope that helps

String to HashMap JAVA

You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted

Example:

Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");

JSONObject json= new JSONObject(map);

String result= json.toString();

System.out.print(result);

result:

{'myNumber':100, 'myString':'String'}

Your can also get key from it like

System.out.print(json.get("myNumber"));

result:

100

Redirect From Action Filter Attribute

Here is a solution that also takes in account if you are using Ajax requests.

using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace YourNamespace{        
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizeCustom : ActionFilterAttribute {
        public override void OnActionExecuting(ActionExecutingContext context) {
            if (YourAuthorizationCheckGoesHere) {               
                string area = "";// leave empty if not using area's
                string controller = "ControllerName";
                string action = "ActionName";
                var urlHelper = new UrlHelper(context.RequestContext);                  
                if (context.HttpContext.Request.IsAjaxRequest()){ // Check if Ajax
                    if(area == string.Empty)
                        context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(controller, action))}');</script>");
                    else
                        context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(area, controller, action))}');</script>");
                } else   // Non Ajax Request                      
                    context.Result = new RedirectToRouteResult(new RouteValueDictionary( new{ area, controller, action }));             
            }
            base.OnActionExecuting(context);
        }
    }
}

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

How to get the selected date value while using Bootstrap Datepicker?

Try this using HTML like here:

var myDate = window.document.getElementById("startdate").value;

How can I count the number of elements with same class?

With jQuery you can use

$('#main-div .specific-class').length

otherwise in VanillaJS (from IE8 included) you may use

document.querySelectorAll('#main-div .specific-class').length;