Programs & Examples On #Config files

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

systemd

sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

sysvinit

sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

Language Books/Tutorials for popular languages

Python: http://diveintopython.net/

JS: a re-introduction to JavaScript is the introduction to the language (not the browser specifics) for programmers. Don't know a good tutorial on JS in browser.

Great idea by the way!

Bootstrap 3 navbar active li not changing background-color

In my own bootstrap.css that I load after the bootstrap.min.css only that, switch of the background image with !important works for me:

.navbar-nav li a:hover, .navbar-nav > .active > a {
  color: #fff !important;

  background-color:#f4511e !important;
  background-image: none !important;
}

Switch tabs using Selenium WebDriver with Java

This will work for the MacOS for Firefox and Chrome:

// opens the default browser tab with the first webpage
driver.get("the url 1");
thread.sleep(2000);

// opens the second tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND + "t");
driver.get("the url 2");
Thread.sleep(2000);

// comes back to the first tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND, Keys.SHIFT, "{");

C++ equivalent of java's instanceof

dynamic_cast is known to be inefficient. It traverses up the inheritance hierarchy, and it is the only solution if you have multiple levels of inheritance, and need to check if an object is an instance of any one of the types in its type hierarchy.

But if a more limited form of instanceof that only checks if an object is exactly the type you specify, suffices for your needs, the function below would be a lot more efficient:

template<typename T, typename K>
inline bool isType(const K &k) {
    return typeid(T).hash_code() == typeid(k).hash_code();
}

Here's an example of how you'd invoke the function above:

DerivedA k;
Base *p = &k;

cout << boolalpha << isType<DerivedA>(*p) << endl;  // true
cout << boolalpha << isType<DerivedB>(*p) << endl;  // false

You'd specify template type A (as the type you're checking for), and pass in the object you want to test as the argument (from which template type K would be inferred).

How to determine equality for two JavaScript objects?

Why reinvent the wheel? Give Lodash a try. It has a number of must-have functions such as isEqual().

_.isEqual(object, other);

It will brute force check each key value - just like the other examples on this page - using ECMAScript 5 and native optimizations if they're available in the browser.

Note: Previously this answer recommended Underscore.js, but lodash has done a better job of getting bugs fixed and addressing issues with consistency.

How to check that an element is in a std::set?

I use

if(!my_set.count(that_element)) //Element is present...
;

But it is not as efficient as

if(my_set.find(that_element)!=my_set.end()) ....;

My version only saves my time in writing the code. I prefer it this way for competitive coding.

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I experienced the same issue when trying to install tensorflow from a jupyter notebook using Anaconda. --user did not work.

conda install tensorflow worked for me, and I didn't have to change any security settings.

Comparing Arrays of Objects in JavaScript

There`s my solution. It will compare arrays which also have objects and arrays. Elements can be stay in any positions. Example:

const array1 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];
const array2 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];

const arraysCompare = (a1, a2) => {
  if (a1.length !== a2.length) return false;
  const objectIteration = (object) => {
    const result = [];
    const objectReduce = (obj) => {
      for (let i in obj) {
        if (typeof obj[i] !== 'object') {
          result.push(`${i}${obj[i]}`);
        } else {
          objectReduce(obj[i]);
        }
      }
    };
    objectReduce(object);
    return result;
  };
  const reduceArray1 = a1.map(item => {
    if (typeof item !== 'object') return item;
    return objectIteration(item).join('');
  });
  const reduceArray2 = a2.map(item => {
    if (typeof item !== 'object') return item;
    return objectIteration(item).join('');
  });
  const compare =  reduceArray1.map(item => reduceArray2.includes(item));
  return compare.reduce((acc, item) => acc + Number(item)) === a1.length;
};

console.log(arraysCompare(array1, array2));

Receive result from DialogFragment

In Kotlin

    // My DialogFragment
class FiltroDialogFragment : DialogFragment(), View.OnClickListener {
    
    var listener: InterfaceCommunicator? = null

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        listener = context as InterfaceCommunicator
    }

    interface InterfaceCommunicator {
        fun sendRequest(value: String)
    }   

    override fun onClick(v: View) {
        when (v.id) {
            R.id.buttonOk -> {    
        //You can change value             
                listener?.sendRequest('send data')
                dismiss()
            }
            
        }
    }
}

// My Activity

class MyActivity: AppCompatActivity(),FiltroDialogFragment.InterfaceCommunicator {

    override fun sendRequest(value: String) {
    // :)
    Toast.makeText(this, value, Toast.LENGTH_LONG).show()
    }
}
 

I hope it serves, if you can improve please edit it. My English is not very good

Quicker way to get all unique values of a column in VBA?

PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options

The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values

Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String

Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True

End Sub

Using logging in multiple modules

Best practice is, in each module, to have a logger defined like this:

import logging
logger = logging.getLogger(__name__)

near the top of the module, and then in other code in the module do e.g.

logger.debug('My message with %s', 'variable data')

If you need to subdivide logging activity inside a module, use e.g.

loggerA = logging.getLogger(__name__ + '.A')
loggerB = logging.getLogger(__name__ + '.B')

and log to loggerA and loggerB as appropriate.

In your main program or programs, do e.g.:

def main():
    "your program code"

if __name__ == '__main__':
    import logging.config
    logging.config.fileConfig('/path/to/logging.conf')
    main()

or

def main():
    import logging.config
    logging.config.fileConfig('/path/to/logging.conf')
    # your program code

if __name__ == '__main__':
    main()

See here for logging from multiple modules, and here for logging configuration for code which will be used as a library module by other code.

Update: When calling fileConfig(), you may want to specify disable_existing_loggers=False if you're using Python 2.6 or later (see the docs for more information). The default value is True for backward compatibility, which causes all existing loggers to be disabled by fileConfig() unless they or their ancestor are explicitly named in the configuration. With the value set to False, existing loggers are left alone. If using Python 2.7/Python 3.2 or later, you may wish to consider the dictConfig() API which is better than fileConfig() as it gives more control over the configuration.

JavaScript window resize event

The following blog post may be useful to you: Fixing the window resize event in IE

It provides this code:

Sys.Application.add_load(function(sender, args) {
    $addHandler(window, 'resize', window_resize);
});

var resizeTimeoutId;

function window_resize(e) {
     window.clearTimeout(resizeTimeoutId);
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10);
}

What is the difference between Bootstrap .container and .container-fluid classes?

From a display perspective .container gives you more control over the what the users are seeing, and makes it easier to see what the users will see as you only have 4 variations of display (5 in the case of bootstrap 5) because the sizes relate to the same as the grid sizes. e.g. .col-xs, .col-sm, .col, and .col-lg.

What this means, is that when you are doing user testing if you test on a displays with the 4 different sizes you see all the veriations in display.

When using .container-fluid because the witdh is related to the viewport width the display is dynamic, so the varations are much greater and users with very large screens or uncommon screen widths may see results you weren't expecting.

MySQL: Can't create table (errno: 150)

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails due to Error 150, this means that a foreign key definition would be incorrectly formed for the altered table.

How to Load an Assembly to AppDomain with all references recursively?

You need to handle the AppDomain.AssemblyResolve or AppDomain.ReflectionOnlyAssemblyResolve events (depending on which load you're doing) in case the referenced assembly is not in the GAC or on the CLR's probing path.

AppDomain.AssemblyResolve

AppDomain.ReflectionOnlyAssemblyResolve

Linux command-line call not returning what it should from os.system?

For your requirement, Popen function of subprocess python module is the answer. For example,

import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout

TransactionRequiredException Executing an update/delete query

Using @PersistenceContext with @Modifying as below fixes error while using createNativeQuery

    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.transaction.annotation.Transactional;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    @Modifying
    public <S extends T> S save(S entity) {
         Query q = entityManager.createNativeQuery(...);
         q.setParameter...
         q.executeUpdate();
         return entity;
    }

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

Put buttons at bottom of screen with LinearLayout?

You need to ensure four things:

  • Your outside LinearLayout has layout_height="match_parent"
  • Your inside LinearLayout has layout_weight="1" and layout_height="0dp"
  • Your TextView has layout_weight="0"
  • You've set the gravity properly on your inner LinearLayout: android:gravity="center|bottom"

Notice that fill_parent does not mean "take up all available space". However, if you use layout_height="0dp" with layout_weight="1", then a view will take up all available space (Can't get proper layout with "fill_parent").

Here is some code I quickly wrote up that uses two LinearLayouts in a similar fashion to your code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/db1_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/cow"
        android:layout_weight="0"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:gravity="center|bottom"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="145dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center"
            android:text="1" />

        <Button
            android:id="@+id/button2"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="145dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center"
            android:text="2" />

        <Button
            android:id="@+id/button3"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="145dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center"
            android:text="3" />
    </LinearLayout>

</LinearLayout>

The result looks like similar to this:

enter image description here

scrollIntoView Scrolls just too far

So, perhaps this is a bit clunky but so far so good. Im working in angular 9.

file .ts

scroll(el: HTMLElement) {
  el.scrollIntoView({ block: 'start',  behavior: 'smooth' });   
}

file .html

<button (click)="scroll(target)"></button>
<div  #target style="margin-top:-50px;padding-top: 50px;" ></div>

I adjust the offset with margin and padding top.

Saludos!

Force decimal point instead of comma in HTML5 number input (client-side)

Sadly, the coverage of this input field in the modern browsers is very low:

http://caniuse.com/#feat=input-number

Therefore, I recommend to expect the fallback and rely on a heavy-programmatically-loaded input[type=text] to do the job, until the field is generally accepted.

So far, only Chrome, Safari and Opera have a neat implementation, but all other browsers are buggy. Some of them, don't even seem to support decimals (like BB10)!

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

For anchors, you should use title instead. alt is not valid atribute of a. See http://w3schools.com/tags/tag_a.asp

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} 
   };

User $resource("apiUrl").query();

Bind TextBox on Enter-key press

This works for me:

        <TextBox                 
            Text="{Binding Path=UserInput, UpdateSourceTrigger=PropertyChanged}">
            <TextBox.InputBindings>
                <KeyBinding Key="Return" 
                            Command="{Binding Ok}"/>
            </TextBox.InputBindings>
        </TextBox>

How do I ignore a directory with SVN?

Remove it first...

If your directory foo is already under version control, remove it first with:

svn rm --keep-local foo

...then ignore:

svn propset svn:ignore foo .

Stacked bar chart

You need to transform your data to long format and shouldn't use $ inside aes:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

INSERT INTO TABLE from comma separated varchar-list

Since there's no way to just pass this "comma-separated list of varchars", I assume some other system is generating them. If you can modify your generator slightly, it should be workable. Rather than separating by commas, you separate by union all select, and need to prepend a select also to the list. Finally, you need to provide aliases for the table and column in you subselect:

Create Table #IMEIS(
    imei varchar(15)
)
INSERT INTO #IMEIS(imei)
    SELECT * FROM (select '012251000362843' union all select '012251001084784' union all select '012251001168744' union all
                   select '012273007269862' union all select '012291000080227' union all select '012291000383084' union all
                   select '012291000448515') t(Col)
SELECT * from #IMEIS
DROP TABLE #IMEIS;

But noting your comment to another answer, about having 5000 entries to add. I believe the 256 tables per select limitation may kick in with the above "union all" pattern, so you'll still need to do some splitting of these values into separate statements.

Create ul and li elements in javascript.

Here is my working code :

<!DOCTYPE html>
<html>
<head>
<style>
   ul#proList{list-style-position: inside}
   li.item{list-style:none; padding:5px;}
</style>
</head>
<body>
    <div id="renderList"></div>
</body>
<script>
    (function(){
        var ul = document.createElement('ul');
        ul.setAttribute('id','proList');

        productList = ['Electronics Watch','House wear Items','Kids wear','Women Fashion'];

        document.getElementById('renderList').appendChild(ul);
        productList.forEach(renderProductList);

        function renderProductList(element, index, arr) {
            var li = document.createElement('li');
            li.setAttribute('class','item');

            ul.appendChild(li);

            li.innerHTML=li.innerHTML + element;
        }
    })();
</script>
</html>

working jsfiddle example here

Spring @PropertySource using YAML

Spring-boot has a helper for this, just add

@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)

at the top of your test classes or an abstract test superclass.

Edit: I wrote this answer five years ago. It doesn't work with recent versions of Spring Boot. This is what I do now (please translate the Kotlin to Java if necessary):

@TestPropertySource(locations=["classpath:application.yml"])
@ContextConfiguration(
        initializers=[ConfigFileApplicationContextInitializer::class]
)

is added to the top, then

    @Configuration
    open class TestConfig {

        @Bean
        open fun propertiesResolver(): PropertySourcesPlaceholderConfigurer {
            return PropertySourcesPlaceholderConfigurer()
        }
    }

to the context.

What are database constraints?

  1. UNIQUE constraint (of which a PRIMARY KEY constraint is a variant). Checks that all values of a given field are unique across the table. This is X-axis constraint (records)

  2. CHECK constraint (of which a NOT NULL constraint is a variant). Checks that a certain condition holds for the expression over the fields of the same record. This is Y-axis constraint (fields)

  3. FOREIGN KEY constraint. Checks that a field's value is found among the values of a field in another table. This is Z-axis constraint (tables).

Sorting an Array of int using BubbleSort

Here we go

static String arrayToString(int[] array) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < array.length; i++) {
      stringBuilder.append(array[i]).append(",");
    }
    return stringBuilder.deleteCharAt(stringBuilder.length()-1).toString();
  }

  public static void main(String... args){
    int[] unsorted = {9,2,1,4,0};
    System.out.println("Sorting an array of Length "+unsorted.length);
    enhancedBubbleSort(unsorted);
    //dumbBubbleSort(unsorted);
    //bubbleSort(unsorted);
    //enhancedBubbleSort(unsorted);
    //enhancedBubbleSortBetterStructured(unsorted);
    System.out.println("Sorted Array: "+arrayToString(unsorted));

  }

  // this is the dumbest BubbleSort
  static int[] dumbBubbleSort(int[] array){
    for (int i = 0; i<array.length-1 ; i++) {
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          // Just swap
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
      }
      System.out.println("After "+(i+1)+" pass: "+arrayToString(array));
    }
    return array;
  }

  //this "-i" in array.length - 1-i brings some improvement.
  // Then for making our bestcase scenario better ( o(n) , we will introduce isswapped flag) that's enhanced bubble sort

  static int[] bubbleSort(int[] array){
    for (int i = 0; i<array.length-1 ; i++) {
      for (int j = 0; j < array.length - 1-i; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
      }
      System.out.println("After "+(i+1)+" pass: "+arrayToString(array));
    }
    return array;
  }

  static int[] enhancedBubbleSort(int[] array){
    int i=0;
    while (true) {
      boolean swapped = false;
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped =true;
        }
      }
      i++;
      System.out.println("After "+(i)+" pass: "+arrayToString(array));
      if(!swapped){
        // Last iteration (of outer loop) didnot result in any swaps. so stopping here
        break;
      }
    }
    return array;
  }

  static int[] enhancedBubbleSortBetterStructured(int[] array){
    int i=0;
    boolean swapped = true;
    while (swapped) {
      swapped = false;
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped = true;
        }
      }
      i++;
      System.out.println("After "+(i)+" pass: "+arrayToString(array));
    }
    return array;
  }

Binding ConverterParameter

No, unfortunately this will not be possible because ConverterParameter is not a DependencyProperty so you won't be able to use bindings

But perhaps you could cheat and use a MultiBinding with IMultiValueConverter to pass in the 2 Tag properties.

How to get the path of running java program

    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader)cl).getURLs();

    for(URL url: urls){
        System.out.println(url.getFile());
    }

System.Data.OracleClient requires Oracle client software version 8.1.7

Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.

Is it possible to decompile an Android .apk file?

I may also add, that nowadays it is possible to decompile Android application online, no software needed!

Here are 2 options for you:

How to connect to Oracle 11g database remotely

# . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh  

#  sqlplus /nolog  

SQL> connect sys/password as sysdba                                           

SQL>  EXEC DBMS_XDB.SETLISTENERLOCALACCESS(FALSE);  

SQL> CONNECT sys/password@hostname:1521 as sysdba

how to delete default values in text field using selenium?

The following function will delete the input character one by one till the input field is empty using PromiseWhile

driver.clearKeys = function(element, value){
  return element.getAttribute('value').then(function(val) {
    if (val.length > 0) {
      return new Promise(function(resolve, reject) {
        var len;
        len = val.length;
        return promiseWhile(function() { 
          return 0 < len;
        }, function() {
          return new Promise(function(resolve, reject) {
            len--;
            return element.sendKeys(webdriver.Key.BACK_SPACE).then(function()              {
              return resolve(true);
            });
          });
        }).then(function() {
          return resolve(true);
        });
      });
    }

ASP.NET Setting width of DataBound column in GridView

<asp:GridView ID="GridView1" AutoGenerateEditButton="True" 
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" width="600px">

<Columns>
                <asp:BoundField HeaderText="UserId" 
                DataField="UserId" 
                SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
   </Columns>
</asp:GridView>

How to get keyboard input in pygame?

Just fyi, if you're trying to ensure the ship doesn't go off of the screen with

location-=1
if location==-1:
    location=0

you can probably better use

location -= 1
location = max(0, location)

This way if it skips -1 your program doesn't break

#ifdef in C#

#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

Make sure you have the checkbox to define DEBUG checked in your build properties.

No Persistence provider for EntityManager named

I also had this error but the issue was the namespace uri in the persistence.xml.

I replaced http://xmlns.jcp.org/xml/ns/persistence to http://java.sun.com/xml/ns/persistence and the version 2.1 to 2.0.

It's now working.

error LNK2005, already defined?

And if you want these translation units to share this variable, define int k; in A.cpp and put extern int k; in B.cpp.

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

jQuery form validation on button click

You can also achieve other way using button tag

According new html5 attribute you also can add a form attribute like

<form id="formId">
    <input type="text" name="fname">
</form>

<button id="myButton" form='#formId'>My Awesome Button</button>

So the button will be attached to the form.

This should work with the validate() plugin of jQuery like :

var validator = $( "#formId" ).validate();
validator.element( "#myButton" );

It's working too with input tag

Source :

https://developer.mozilla.org/docs/Web/HTML/Element/Button

Restricting JTextField input to Integers

I used to use the Key Listener for this but I failed big time with that approach. Best approach as recommended already is to use a DocumentFilter. Below is a utility method I created for building textfields with only number input. Just beware that it'll also take single '.' character as well since it's usable for decimal input.

public static void installNumberCharacters(AbstractDocument document) {
        document.setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset,
                    String string, AttributeSet attr)
                    throws BadLocationException {
                try {
                    if (string.equals(".")
                            && !fb.getDocument()
                                    .getText(0, fb.getDocument().getLength())
                                    .contains(".")) {
                        super.insertString(fb, offset, string, attr);
                        return;
                    }
                    Double.parseDouble(string);
                    super.insertString(fb, offset, string, attr);
                } catch (Exception e) {
                    Toolkit.getDefaultToolkit().beep();
                }

            }

            @Override
            public void replace(FilterBypass fb, int offset, int length,
                    String text, AttributeSet attrs)
                    throws BadLocationException {
                try {
                    if (text.equals(".")
                            && !fb.getDocument()
                                    .getText(0, fb.getDocument().getLength())
                                    .contains(".")) {
                        super.insertString(fb, offset, text, attrs);
                        return;
                    }
                    Double.parseDouble(text);
                    super.replace(fb, offset, length, text, attrs);
                } catch (Exception e) {
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        });
    }

How to get current user in asp.net core

Taking IdentityUser would also work. This is a current user object and all values of user can be retrieved.

private readonly UserManager<IdentityUser> _userManager;
public yourController(UserManager<IdentityUser> userManager)
{
    _userManager = userManager;
}

var user = await _userManager.GetUserAsync(HttpContext.User);

How to make HTTP Post request with JSON body in Swift

func fucntion()
{

    var parameters = [String:String]()
    let apiToken = "Bearer \(ApiUtillity.sharedInstance.getUserData(key: "vAuthToken"))"
    let headers = ["Vauthtoken":apiToken]

    parameters = ["firstname":name,"lastname":last_name,"mobile":mobile_number,"email":emails_Address]


    Alamofire.request(ApiUtillity.sharedInstance.API(Join: "user/edit_profile"), method: .post, parameters: parameters, encoding: URLEncoding.default,headers:headers).responseJSON { response in
        debugPrint(response)
        if let json = response.result.value {
            let dict:NSDictionary = (json as? NSDictionary)!
            print(dict)
            //                print(response)

            let StatusCode = dict.value(forKey: "status") as! Int

            if StatusCode==200
            {
                ApiUtillity.sharedInstance.dismissSVProgressHUDWithSuccess(success: "Success")
                let UserData = dict.value(forKey: "data") as! NSDictionary
                print(UserData)

            }

            else if StatusCode==401
            {
                let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
                let ErrorMessage = ErrorDic.value(forKey: "error") as! String

            }
            else
            {

                let ErrorDic:NSDictionary = dict.value(forKey: "message") as! NSDictionary
                let ErrorMessage = ErrorDic.value(forKey: "error") as! String
            }

        }
        else
        {
            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: "Something went wrong")
        }
    }

How do I check when a UITextField changes?

Swift 4

textField.addTarget(self, action: #selector(textIsChanging), for: UIControlEvents.editingChanged)

@objc func textIsChanging(_ textField:UITextField) {

 print ("TextField is changing")

}

If you want to make a change once the user has typed in completely (It will be called once user dismiss keyboard or press enter).

textField.addTarget(self, action: #selector(textDidChange), for: UIControlEvents.editingDidEnd)

 @objc func textDidChange(_ textField:UITextField) {

       print ("TextField did changed") 
 }

Drawing circles with System.Drawing

PictureBox circle = new PictureBox();
circle.Paint += new PaintEventHandler(circle_Paint);        

void circle_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawEllipse(Pens.Red, 0, 0, 30, 30);
        }

XAMPP installation on Win 8.1 with UAC Warning

There are two things you need to check:

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC (User Account Control) as it restricts certain administrative function needed to run a web server.

To ensure that your user account has administrator privilege, run lusrmgr.msc from the Windows Start > Run menu to bring up the Local Users and Groups Windows. Double-click on your user account that appears under Users, and verifies that it is a member of Administrators.

To disable UAC (as an administrator), from Control Panel:

  1. Type UAC in the search field in the upper right corner.
  2. Click Change User Account Control settings in the search results.
  3. Drag the slider down to Never notifyand click OK.

open up the User Accounts window from Control Panel. Click on the Turn User Account Control on or off option, and un-check the checkbox.

Alternately, if you don't want to disable UAC, you will have to install XAMPP in a different folder, outside of C:\Program Files (x86), such as C:\xampp.

Hope this helps.

How do AX, AH, AL map onto EAX?

| 0000 0001 0010 0011 0100 0101 0110 0111 | ------> EAX

|                     0100 0101 0110 0111 | ------> AX

|                               0110 0111 | ------> AL

|                     0100 0101           | ------> AH

How to automatically convert strongly typed enum into int?

Strongly typed enums aiming to solve multiple problems and not only scoping problem as you mentioned in your question:

  1. Provide type safety, thus eliminating implicit conversion to integer by integral promotion.
  2. Specify underlying types.
  3. Provide strong scoping.

Thus, it is impossible to implicitly convert a strongly typed enum to integers, or even its underlying type - that's the idea. So you have to use static_cast to make conversion explicit.

If your only problem is scoping and you really want to have implicit promotion to integers, then you better off using not strongly typed enum with the scope of the structure it is declared in.

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

How do you clear Apache Maven's cache?

To clean the local cache try using the dependency plug-in.

  1. mvn dependency:purge-local-repository: This is an attempt to delete the local repository files but it always goes and fills up the local repository after things have been removed.
  2. mvn dependency:purge-local-repository -DreResolve=false: This avoids the re-resolving of the dependencies but seems to still go to the network at times.
  3. mvn dependency:purge-local-repository -DactTransitively=false -DreResolve=false: This was added by Pawel Prazak and seems to work well. I'd use the third if you want the local repo emptied, and the first if you just want to throw out the local repo and get the dependencies again.

Write string to text file and ensure it always overwrites the existing content.

Generally, FileMode.Create is what you're looking for.

Drawing a dot on HTML5 canvas

This should do the job

//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

How can I know if Object is String type object?

Use the instanceof syntax.

Like so:

Object foo = "";

if( foo instanceof String ) {
  // do something String related to foo
}

Take a list of numbers and return the average

Simple math..

def average(n):
    result = 0
    for i in n:
      result += i
      ave_num = result / len(n)
    return ave_num

input -> [1,2,3,4,5]
output -> 3.0

Display a message in Visual Studio's output window when not debug mode?

The Trace messages can occur in the output window as well, even if you're not in debug mode. You just have to make sure the the TRACE compiler constant is defined.

CSS hide scroll bar if not needed

.container {overflow:auto;} will do the trick. If you want to control specific direction, you should set auto for that specific axis. A.E.

.container {overflow-y:auto;} .container {overflow-x:hidden;}

The above code will hide any overflow in the x-axis and generate a scroll-bar when needed on the y-axis.But you have to make sure that you content default height smaller than the container height; if not, the scroll-bar will not be hidden.

How to enable explicit_defaults_for_timestamp?

On a Windows platform,

  1. Find your my.ini configuration file.
  2. In my.ini go to the [mysqld] section.
  3. Add explicit_defaults_for_timestamp=true without quotes and save the change.
  4. Start mysqld

This worked for me (windows 7 Ultimate 32bit)

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

How to make in CSS an overlay over an image?

You could use a pseudo element for this, and have your image on a hover:

_x000D_
_x000D_
.image {_x000D_
  position: relative;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  background: url(http://lorempixel.com/300/300);_x000D_
}_x000D_
.image:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  transition: all 0.8s;_x000D_
  opacity: 0;_x000D_
  background: url(http://lorempixel.com/300/200);_x000D_
  background-size: 100% 100%;_x000D_
}_x000D_
.image:hover:before {_x000D_
  opacity: 0.8;_x000D_
}
_x000D_
<div class="image"></div>
_x000D_
_x000D_
_x000D_

How does OkHttp get Json string?

Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

Log.e("Main",response.body!!.string())

in above line !! is the thing using which you can get the json from response body

val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })

Make a negative number positive

if(arr[i]<0)

Math.abs(arr[i]);  //1st way (taking absolute value)

arr[i]=-(arr[i]); //2nd way (taking -ve of -ve no. yields a +ve no.)

arr[i]= ~(arr[i]-1);   //3rd way (taking negation)

NSUserDefaults - How to tell if a key exists

Swift 3.0

if NSUserDefaults.standardUserDefaults().dictionaryRepresentation().contains({ $0.0 == "Your_Comparison_Key" }){
                    result = NSUserDefaults.standardUserDefaults().objectForKey(self.ticketDetail.ticket_id) as! String
                }

Javascript : natural sort of alphanumerical strings

The most fully-featured library to handle this as of 2019 seems to be natural-orderby.

const { orderBy } = require('natural-orderby')

const unordered = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12'
]

const ordered = orderBy(unordered)

// [ '19asd',
//   '123asd',
//   '12345asd',
//   'asd12',
//   'asd123' ]

It not only takes arrays of strings, but also can sort by the value of a certain key in an array of objects. It can also automatically identify and sort strings of: currencies, dates, currency, and a bunch of other things.

Surprisingly, it's also only 1.6kB when gzipped.

What is difference between Axios and Fetch?

One more major difference between fetch API & axios API

  • While using service worker, you have to use fetch API only if you want to intercept the HTTP request
  • Ex. While performing caching in PWA using service worker you won't be able to cache if you are using axios API (it works only with fetch API)

Java get String CompareTo as a comparator object

The Arrays class has versions of sort() and binarySearch() which don't require a Comparator. For example, you can use the version of Arrays.sort() which just takes an array of objects. These methods call the compareTo() method of the objects in the array.

Passing vector by reference

You don't need to use **arr, you can either use:

void do_something(int el, std::vector<int> *arr){
    arr->push_back(el);
}

or:

 void do_something(int el, std::vector<int> &arr){
    arr.push_back(el);
}

**arr makes no sense but if you insist using it, do it this way:

void do_something(int el, std::vector<int> **arr){
    (*arr)->push_back(el);
}

but again there is no reason to do so...

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

How can I calculate the difference between two dates?

You may want to use something like this:

NSDateComponents *components;
NSInteger days;

components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit 
        fromDate: startDate toDate: endDate options: 0];
days = [components day];

I believe this method accounts for situations such as dates that span a change in daylight savings.

How can prevent a PowerShell window from closing so I can see the error?

this will make the powershell window to wait until you press any key:

pause

Update One

Thanks to Stein. it is the Enter key not any key.

mysql update column with value from another table

If you have common field in both table then it's so easy !....

Table-1 = table where you want to update. Table-2 = table where you from take data.

  1. make query in Table-1 and find common field value.
  2. make a loop and find all data from Table-2 according to table 1 value.
  3. again make update query in table 1.

$qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`");

$resultArray = array();
while ($row = mysql_fetch_array($qry_asseet_list)) {
$resultArray[] = $row;
}



foreach($resultArray as $rec) {

    $a = $rec['primary key field'];

    $cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a");

    $cuttable = mysql_fetch_assoc($cuttable_qry);



    echo $x= $cuttable['Table-2 field']; echo " ! ";
    echo $y= $cuttable['Table-2 field'];echo " ! ";
    echo $z= $cuttable['Table-2 field'];echo " ! ";


    $k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;");

    if ($k) {
        echo "done";
    } else {
        echo mysql_error();
    }


}

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField
FROM MyTable
GROUP BY CAST(Datetimefield AS DATE)

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

Tower of Hanoi: Recursive Algorithm

In simple sense the idea is to fill another tower among the three defined towers in the same order of discs as present without a larger disc overlapping a small disc at any time during the procedure.

Let 'A' , 'B' and 'C' be three towers. 'A' will be the tower containing 'n' discs initially. 'B' can be used as intermediate tower and 'C' is the target tower.

The algo is as follows:

  1. Move n-1 discs from tower 'A' to 'B' using 'C'
  2. Move a disc from 'A' to 'C'
  3. Move n-1 discs from tower 'B' to 'C' using 'A'

The code is as follows in java:

public class TowerOfHanoi {

public void TOH(int n, int A , int B , int C){
    if (n>0){
        TOH(n-1,A,C,B);
        System.out.println("Move a disk from tower "+A +" to tower " + C);
        TOH(n-1,B,A,C);
    }
}

public static void main(String[] args) {
    new TowerOfHanoi().TOH(3, 1, 2, 3);
}   

}

Apache Name Virtual Host with SSL

As far as I know, Apache supports SNI since Version 2.2.12 Sadly the documentation does not yet reflect that change.

Go for http://wiki.apache.org/httpd/NameBasedSSLVHostsWithSNI until that is finished

Disable arrow key scrolling in users browser

For maintainability, I would attach the "blocking" handler on the element itself (in your case, the canvas).

theCanvas.onkeydown = function (e) {
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
        e.view.event.preventDefault();
    }
}

Why not simply do window.event.preventDefault()? MDN states:

window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled.

Further readings:

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

How to get current value of RxJS Subject or Observable?

const observable = of('response')

function hasValue(value: any) {
  return value !== null && value !== undefined;
}

function getValue<T>(observable: Observable<T>): Promise<T> {
  return observable
    .pipe(
      filter(hasValue),
      first()
    )
    .toPromise();
}

const result = await getValue(observable)
// Do the logic with the result
// .................
// .................
// .................

You can check the full article on how to implement it from here. https://www.imkrish.com/blog/development/simple-way-get-value-from-observable

Get next / previous element using JavaScript?

use the nextSibling and previousSibling properties:

<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>

document.getElementById('foo2').nextSibling; // #foo3
document.getElementById('foo2').previousSibling; // #foo1

However in some browsers (I forget which) you also need to check for whitespace and comment nodes:

var div = document.getElementById('foo2');
var nextSibling = div.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
    nextSibling = nextSibling.nextSibling
}

Libraries like jQuery handle all these cross-browser checks for you out of the box.

Convert Mercurial project to Git

Ok I finally worked this out. This is using TortoiseHg on Windows. If you're not using that you can do it on the command line.

  1. Install TortoiseHg
  2. Right click an empty space in explorer, and go to the TortoiseHg settings:

TortoiseHg Settings

  1. Enable hggit:

enter image description here

  1. Open a command line, enter an empty directory.

  2. git init --bare .git (If you don't use a bare repo you'll get an error like abort: git remote error: refs/heads/master failed to update

  3. cd to your Mercurial repository.

  4. hg bookmarks hg

  5. hg push c:/path/to/your/git/repo

  6. In the Git directory: git config --bool core.bare false (Don't ask me why. Something about "work trees". Git is seriously unfriendly. I swear writing the actual code is easier than using Git.)

Hopefully it will work and then you can push from that new git repo to a non-bare one.

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Tank´s Yogihosting

I have in my database one goups of tables from Open Streep Maps and I tested successful.

Distance work fine in meters.

SET @orig_lat=-8.116137;
SET @orig_lon=-34.897488;
SET @dist=1000;

SELECT *,(((acos(sin((@orig_lat*pi()/180)) * sin((dest.latitude*pi()/180))+cos((@orig_lat*pi()/180))*cos((dest.latitude*pi()/180))*cos(((@orig_lon-dest.longitude)*pi()/180))))*180/pi())*60*1.1515*1609.344) as distance FROM nodes AS dest HAVING distance < @dist ORDER BY distance ASC LIMIT 100;

Truststore and Keystore Definitions

A keystore contains private keys, and the certificates with their corresponding public keys.

A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

CABForum Baseline Requirements

I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.

Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.

(So this means I can't answer the "Edit" to your question. Only the original question.)

CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:

9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).

EDIT: Links from @Bruno's comment

RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:

[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).

HTML how to clear input using javascript?

instead of clearing the name text use placeholder attribute it is good practice

<input type="text" placeholder="name"  name="name">

Best way to read a large file into a byte array in C#?

I'd say BinaryReader is fine, but can be refactored to this, instead of all those lines of code for getting the length of the buffer:

public byte[] FileToByteArray(string fileName)
{
    byte[] fileData = null;

    using (FileStream fs = File.OpenRead(fileName)) 
    { 
        using (BinaryReader binaryReader = new BinaryReader(fs))
        {
            fileData = binaryReader.ReadBytes((int)fs.Length); 
        }
    }
    return fileData;
}

Should be better than using .ReadAllBytes(), since I saw in the comments on the top response that includes .ReadAllBytes() that one of the commenters had problems with files > 600 MB, since a BinaryReader is meant for this sort of thing. Also, putting it in a using statement ensures the FileStream and BinaryReader are closed and disposed.

How do I add one month to current date in Java?

(adapted from Duggu)

public static Date addOneMonth(Date date)
{
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.MONTH, 1);
    return cal.getTime();
}

Rails Model find where not equal

In Rails 3, I don't know anything fancier. However, I'm not sure if you're aware, your not equal condition does not match for (user_id) NULL values. If you want that, you'll have to do something like this:

GroupUser.where("user_id != ? OR user_id IS NULL", me)

align divs to the bottom of their container

The way I solved this was using flexbox. By using flexbox to layout the contents of your container div, you can have flexbox automatically distribute free space to an item above the one you want to have "stick to the bottom".

For example, say this is your container div with some other block elements inside it, and that the blue box (third one down) is a paragraph and the purple box (last one) is the one you want to have "stick to the bottom".

enter image description here

By setting this layout up with flexbox, you can set flex-grow: 1; on just the paragraph (blue box) and, if it is the only thing with flex-grow: 1;, it will be allocated ALL of the remaining space, pushing the element(s) after it to the bottom of the container like this:

enter image description here

(apologies for the terrible, quick-and-dirty graphics)

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

this error I was able to remove after adding profile:

<profile>
            <id>surefire-windows-fork-disable</id>
            <activation>
                <os>
                    <family>Windows</family>
                </os>
            </activation>
            <build>
                <pluginManagement>
                    <plugins>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-surefire-plugin</artifactId>
                            <configuration>
                                <forkCount>0</forkCount>
                                <useSystemClassLoader>false</useSystemClassLoader>
                            </configuration>
                        </plugin>
                    </plugins>
                </pluginManagement>
            </build>
        </profile>

seems that this is a windows problem regarding maven surefire forks

How to include Javascript file in Asp.Net page

add like

<head runat="server">
<script src="Registration.js" type="text/javascript"></script>
</head>

OR can add in code behind.

Page.ClientScript.RegisterClientScriptInclude("Registration", ResolveUrl("~/js/Registration.js"));

Is there a C# String.Format() equivalent in JavaScript?

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

_x000D_
_x000D_
String.prototype.format = function(placeholders) {_x000D_
    var s = this;_x000D_
    for(var propertyName in placeholders) {_x000D_
        var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
        s = s.replace(re, placeholders[propertyName]);_x000D_
    }    _x000D_
    return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How to find length of digits in an integer?

Here is a bulky but fast version :

def nbdigit ( x ):
    if x >= 10000000000000000 : # 17 -
        return len( str( x ))
    if x < 100000000 : # 1 - 8
        if x < 10000 : # 1 - 4
            if x < 100             : return (x >= 10)+1 
            else                   : return (x >= 1000)+3
        else: # 5 - 8                                                 
            if x < 1000000         : return (x >= 100000)+5 
            else                   : return (x >= 10000000)+7
    else: # 9 - 16 
        if x < 1000000000000 : # 9 - 12
            if x < 10000000000     : return (x >= 1000000000)+9 
            else                   : return (x >= 100000000000)+11
        else: # 13 - 16
            if x < 100000000000000 : return (x >= 10000000000000)+13 
            else                   : return (x >= 1000000000000000)+15

Only 5 comparisons for not too big numbers. On my computer it is about 30% faster than the math.log10 version and 5% faster than the len( str()) one. Ok... no so attractive if you don't use it furiously.

And here is the set of numbers I used to test/measure my function:

n = [ int( (i+1)**( 17/7. )) for i in xrange( 1000000 )] + [0,10**16-1,10**16,10**16+1]

NB: it does not manage negative numbers, but the adaptation is easy...

how to File.listFiles in alphabetical order?

I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();
 Arrays.sort(dirListing);
 System.out.println(Arrays.deepToString(dirListing));

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

A much more simple solution (thanks to http://daniel.fone.net.nz/blog/2014/12/01/fixing-connection-errors-after-upgrading-postgres/) . I had upgraded to postgres 9.4. In my case, all I needed to do (after a day of googling and not succeeding)

gem uninstall pg
gem uninstall activerecord-postgresql-adapter
bundle install

Restart webrick, and done!

Easy way of running the same junit test over and over?

Inspired by the following resources:

Example

Create and use a @Repeat annotation as follows:

public class MyTestClass {

    @Rule
    public RepeatRule repeatRule = new RepeatRule();

    @Test
    @Repeat(10)
    public void testMyCode() {
        //your test code goes here
    }
}

Repeat.java

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention( RetentionPolicy.RUNTIME )
@Target({ METHOD, ANNOTATION_TYPE })
public @interface Repeat {
    int value() default 1;
}

RepeatRule.java

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RepeatRule implements TestRule {

    private static class RepeatStatement extends Statement {
        private final Statement statement;
        private final int repeat;    

        public RepeatStatement(Statement statement, int repeat) {
            this.statement = statement;
            this.repeat = repeat;
        }

        @Override
        public void evaluate() throws Throwable {
            for (int i = 0; i < repeat; i++) {
                statement.evaluate();
            }
        }

    }

    @Override
    public Statement apply(Statement statement, Description description) {
        Statement result = statement;
        Repeat repeat = description.getAnnotation(Repeat.class);
        if (repeat != null) {
            int times = repeat.value();
            result = new RepeatStatement(statement, times);
        }
        return result;
    }
}

PowerMock

Using this solution with @RunWith(PowerMockRunner.class), requires updating to Powermock 1.6.5 (which includes a patch).

Number of visitors on a specific page

Go to Behavior > Site Content > All Pages and put your URI into the search box.enter image description here

Linux/Unix command to determine if process is running?

This prints the number of processes whose basename is "chromium-browser":

ps -e -o args= | awk 'BEGIN{c=0}{
 if(!match($1,/^\[.*\]$/)){sub(".*/","",$1)} # Do not strip process names enclosed by square brackets.
 if($1==cmd){c++}
}END{print c}' cmd="chromium-browser"

If this prints "0", the process is not running. The command assumes process path does not contain breaking space. I have not tested this with suspended processes or zombie processes.

Tested using gwak as the awk alternative in Linux.

Here is a more versatile solution with some example usage:

#!/bin/sh
isProcessRunning() {
if [ "${1-}" = "-q" ]; then
 local quiet=1;
 shift
else
 local quiet=0;
fi
ps -e -o pid,args= | awk 'BEGIN{status=1}{
 name=$2
 if(name !~ /^\[.*\]$/){sub(".*/","",name)} # strip dirname, if process name is not enclosed by square brackets.
 if(name==cmd){status=0; if(q){exit}else{print $0}}
}END{exit status}' cmd="$1" q=$quiet
}

process='chromium-browser'

printf "Process \"${process}\" is "
if isProcessRunning -q "$process" 
 then printf "running.\n"
 else printf "not running.\n"; fi

printf "Listing of matching processes (PID and process name with command line arguments):\n"
isProcessRunning "$process"

Disable ScrollView Programmatically?

Does this help?

((ScrollView)findViewById(R.id.QuranGalleryScrollView)).setOnTouchListener(null);

"Initializing" variables in python?

Python treats comma on the left hand side of equal sign ( = ) as an input splitter, Very useful for functions that return a tuple.

e.g,

x,y = (5,2)

What you want to do is:

grade_1 = grade_2 = grade_3 = average = 0.0

though that might not be the most clear way to write it.

Apply CSS rules if browser is IE

I prefer using a separate file for ie rules, as described earlier.

<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->

And inside it you can set up rules for different versions of ie using this:

.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */

How to get the system uptime in Windows?

Two ways to do that..

Option 1:

1.  Go to "Start" -> "Run".

2.  Write "CMD" and press on "Enter" key.

3.  Write the command "net statistics server" and press on "Enter" key.

4.  The line that start with "Statistics since …" provides the time that the server was up from.


  The command "net stats srv" can be use instead.

Option 2:

Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher

http://support.microsoft.com/kb/232243

Hope it helped you!!

How to export and import environment variables in windows?

To export user variables, open a command prompt and use regedit with /e

Example :

regedit /e "%userprofile%\Desktop\my_user_env_variables.reg" "HKEY_CURRENT_USER\Environment"

Finding the next available id in MySQL

Given what you said in a comment:

my id coloumn is auto increment i have to get the id and convert it to another base.So i need to get the next id before insert cause converted code will be inserted too.

There is a way to do what you're asking, which is to ask the table what the next inserted row's id will be before you actually insert:

SHOW TABLE STATUS WHERE name = "myTable"

there will be a field in that result set called "Auto_increment" which tells you the next auto increment value.

How does @synchronized lock/unlock in Objective-C?

The Objective-C language level synchronization uses the mutex, just like NSLock does. Semantically there are some small technical differences, but it is basically correct to think of them as two separate interfaces implemented on top of a common (more primitive) entity.

In particular with a NSLock you have an explicit lock whereas with @synchronized you have an implicit lock associated with the object you are using to synchronize. The benefit of the language level locking is the compiler understands it so it can deal with scoping issues, but mechanically they behave basically the same.

You can think of @synchronized as a compiler rewrite:

- (NSString *)myString {
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

is transformed into:

- (NSString *)myString {
  NSString *retval = nil;
  pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
  pthread_mutex_lock(self_mutex);
  retval = [[myString retain] autorelease];
  pthread_mutex_unlock(self_mutex);
  return retval;
}

That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.

How do I download a file with Angular2 or greater

To download and show PDF files, a very similar code snipped is like below:

  private downloadFile(data: Response): void {
    let blob = new Blob([data.blob()], { type: "application/pdf" });
    let url = window.URL.createObjectURL(blob);
    window.open(url);
  }

  public showFile(fileEndpointPath: string): void {
    let reqOpt: RequestOptions = this.getAcmOptions();  //  getAcmOptions is our helper method. Change this line according to request headers you need.
    reqOpt.responseType = ResponseContentType.Blob;
    this.http
      .get(fileEndpointPath, reqOpt)
      .subscribe(
        data => this.downloadFile(data),
        error => alert("Error downloading file!"),
        () => console.log("OK!")
      );
  }

HTTP 404 when accessing .svc file in IIS

There are 2 .net framework version are given under the features in add role/ features in server 2012

a. 3.5

b. 4.5

Depending up on used framework you can enable HTTP-Activation under WCF services. :)

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Opening port 80 EC2 Amazon web services

Some quick tips:

  1. Disable the inbuilt firewall on your Windows instances.
  2. Use the IP address rather than the DNS entry.
  3. Create a security group for tcp ports 1 to 65000 and for source 0.0.0.0/0. It's obviously not to be used for production purposes, but it will help avoid the Security Groups as a source of problems.
  4. Check that you can actually ping your server. This may also necessitate some Security Group modification.

Entity Framework : How do you refresh the model when the db changes?

I just had to update an .edmx model. The model/Run Custom Tool option was not refreshing the fields for me, but once I had the graphical designer open, I was able to manually rename the fields.

getActivity() returns null in Fragment function

Those who still have the problem with onAttach(Activity activity), Its just changed to Context -

    @Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context = context;
}

In most cases saving the context will be enough for you - for example if you want to do getResources() you can do it straight from the context. If you still need to make the context into your Activity do so -

 @Override
public void onAttach(Context context) {
    super.onAttach(context);
    mActivity a; //Your activity class - will probably be a global var.
    if (context instanceof mActivity){
        a=(mActivity) context;
    }
}

As suggested by user1868713.

Regex AND operator

Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:

String to match: "my word"

String to search: "I'm searching for my funny words inside this text"

You need the following regex: /^(?=.*my)(?=.*word).*$/im

Explaining:

^ assert position at start of a line

?= Positive Lookahead

.* matches any character (except newline)

() Groups

$ assert position at end of a line

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Test the Regex here: https://regex101.com/r/iS5jJ3/1

So, you can create a javascript function that:

  1. Replace regex reserved characters to avoid errors
  2. Split your string at spaces
  3. Encapsulate your words inside regex groups
  4. Create a regex pattern
  5. Execute the regex match

Example:

_x000D_
_x000D_
function fullTextCompare(myWords, toMatch){_x000D_
    //Replace regex reserved characters_x000D_
    myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
    //Split your string at spaces_x000D_
    arrWords = myWords.split(" ");_x000D_
    //Encapsulate your words inside regex groups_x000D_
    arrWords = arrWords.map(function( n ) {_x000D_
        return ["(?=.*"+n+")"];_x000D_
    });_x000D_
    //Create a regex pattern_x000D_
    sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
    //Execute the regex match_x000D_
    return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
    fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
    fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
_x000D_
_x000D_

Set value for particular cell in pandas DataFrame using index

Soo, your question to convert NaN at ['x',C] to value 10

the answer is..

df['x'].loc['C':]=10
df

alternative code is

df.loc['C', 'x']=10
df

Customize Bootstrap checkboxes

_x000D_
_x000D_
/* The customcheck */_x000D_
.customcheck {_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    padding-left: 35px;_x000D_
    margin-bottom: 12px;_x000D_
    cursor: pointer;_x000D_
    font-size: 22px;_x000D_
    -webkit-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
    position: absolute;_x000D_
    opacity: 0;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 25px;_x000D_
    width: 25px;_x000D_
    background-color: #eee;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
    background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
    background-color: #02cf32;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
    content: "";_x000D_
    position: absolute;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
    left: 9px;_x000D_
    top: 5px;_x000D_
    width: 5px;_x000D_
    height: 10px;_x000D_
    border: solid white;_x000D_
    border-width: 0 3px 3px 0;_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
 <h1>Custom Checkboxes</h1></br>_x000D_
 _x000D_
        <label class="customcheck">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Three_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Four_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I set the max-width of a table cell using percentages?

According to the definition of max-width in the CSS 2.1 spec, “the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.” So you cannot directly set max-width on a td element.

If you just want the second column to take up at most 67%, then you can set the width (which is in effect minimum width, for table cells) to 33%, e.g. in the example case

td:first-child { width: 33% ;}

Setting that for both columns won’t work that well, since it tends to make browsers give the columns equal width.

How can we stop a running java process through Windows cmd?

In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.

wmic Path win32_process Where "CommandLine Like '%YourJarName.jar%'" Call Terminate

Else taskkill /im java.exe will work to kill all java processes

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

Create the symlink to latest version

 ln -s -f /usr/local/bin/python3.8 /usr/local/bin/python

Close and open a new terminal

and try

 python --version

Determining 32 vs 64 bit in C++

Unfortunately there is no cross platform macro which defines 32 / 64 bit across the major compilers. I've found the most effective way to do this is the following.

First I pick my own representation. I prefer ENVIRONMENT64 / ENVIRONMENT32. Then I find out what all of the major compilers use for determining if it's a 64 bit environment or not and use that to set my variables.

// Check windows
#if _WIN32 || _WIN64
#if _WIN64
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif

// Check GCC
#if __GNUC__
#if __x86_64__ || __ppc64__
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif

Another easier route is to simply set these variables from the compiler command line.

How to implement band-pass Butterworth filter with Scipy.signal.butter

You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high] (expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band".

Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.

from scipy.signal import butter, lfilter


def butter_bandpass(lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a


def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
    b, a = butter_bandpass(lowcut, highcut, fs, order=order)
    y = lfilter(b, a, data)
    return y


if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import freqz

    # Sample rate and desired cutoff frequencies (in Hz).
    fs = 5000.0
    lowcut = 500.0
    highcut = 1250.0

    # Plot the frequency response for a few different orders.
    plt.figure(1)
    plt.clf()
    for order in [3, 6, 9]:
        b, a = butter_bandpass(lowcut, highcut, fs, order=order)
        w, h = freqz(b, a, worN=2000)
        plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)

    plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
             '--', label='sqrt(0.5)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.legend(loc='best')

    # Filter a noisy signal.
    T = 0.05
    nsamples = T * fs
    t = np.linspace(0, T, nsamples, endpoint=False)
    a = 0.02
    f0 = 600.0
    x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
    x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
    x += a * np.cos(2 * np.pi * f0 * t + .11)
    x += 0.03 * np.cos(2 * np.pi * 2000 * t)
    plt.figure(2)
    plt.clf()
    plt.plot(t, x, label='Noisy signal')

    y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
    plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
    plt.xlabel('time (seconds)')
    plt.hlines([-a, a], 0, T, linestyles='--')
    plt.grid(True)
    plt.axis('tight')
    plt.legend(loc='upper left')

    plt.show()

Here are the plots that are generated by this script:

Frequency response for several filter orders

enter image description here

git command to move a folder inside another

I'm sorry I don't have enough reputation to comment the "answer" of "Andres Jaan Tack".

I think my messege will be deleted (( But I just want to warn "lurscher" and others who got the same error: be carefull doing

$ mkdir include
$ mv common include
$ git rm -r common
$ git add include/common

It may cause you will not see the git history of your project in new folder.

I tryed

$ git mv oldFolderName newFolderName

got

fatal: bad source, source=oldFolderName/somepath/__init__.py, dest
ination=ESWProj_Base/ESWProj_DebugControlsMenu/somepath/__init__.py

I did

git rm -r oldFolderName

and

git add newFolderName

and I don't see old git history in my project. At least my project is not lost. Now I have my project in newFolderName, but without the history (

Just want to warn, be carefull using advice of "Andres Jaan Tack", if you dont want to lose your git hsitory.

Is key-value pair available in Typescript?

Another simple way is to use a tuple:

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);

Output:

First: hello Second: 10

Getting list of pixel values from PIL

Looks like PILlow may have changed tostring() to tobytes(). When trying to extract RGBA pixels to get them into an OpenGL texture, the following worked for me (within the glTexImage2D call which I omit for brevity).

from PIL import Image
img = Image.open("mandrill.png").rotate(180).transpose(Image.FLIP_LEFT_RIGHT)

# use img.convert("RGBA").tobytes() as texels

How to check if any fields in a form are empty in php

your form is missing the method...

<form name="registrationform" action="register.php" method="post"> //here

anywyas to check the posted data u can use isset()..

Determine if a variable is set and is not NULL

if(!isset($firstname) || trim($firstname) == '')
{
   echo "You did not fill out the required fields.";
}

How do I perform a JAVA callback between classes?

Define an interface, and implement it in the class that will receive the callback.

Have attention to the multi-threading in your case.

Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html

interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
    void methodToCallBack();
}

class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
        caller.register(callBack);
    }
} 

In your case, apart from multi-threading you could do like this:

interface ServerInterface {
    void newSeverConnection(Socket socket);
}

public class Server implements ServerInterface {

    public Server(int _address) {
        System.out.println("Starting Server...");
        serverConnectionHandler = new ServerConnections(_address, this);
        workers.execute(serverConnectionHandler);
        System.out.println("Do something else...");
    }

    void newServerConnection(Socket socket) {
        System.out.println("A function of my child class was called.");
    }

}

public class ServerConnections implements Runnable {

    private ServerInterface serverInterface;

    public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
      serverPort = _serverPort;
      serverInterface = _serverInterface;
    }

    @Override
    public void run() {
        System.out.println("Starting Server Thread...");

        if (serverInterface == null) {
            System.out.println("Server Thread error: callback null");
        }

        try {
            mainSocket = new ServerSocket(serverPort);

            while (true) {
                serverInterface.newServerConnection(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Multi-threading

Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.

The observer-pattern

The observer-pattern does nearly this, the major difference is the use of an ArrayList for adding more than one listener. Where this is not needed, you get better performance with one reference.

Function of Project > Clean in Eclipse

There's another problem at work here. The Clean functionality of Eclipse is broken. If you delete files outside of Eclipse it will not pick up on the fact that the files are now missing, and you'll get build errors until you delete the files manually. Even then, that will not necessarily work either, especially if there are a lot of files missing. This happens to me rather often when I check out a branch of code that has had a lot of changes since the last time I built it. In that case, the only recourse I've found is to start a brand new workspace and reload the project from scratch.

How to do jquery code AFTER page loading?

You can avoid get undefined in '$' this way

window.addEventListener("DOMContentLoaded", function(){
    // Your code
});

EDIT: Using 'DOMContentLoaded' is faster than just 'load' because load wait page fully loaded, imgs included... while DomContentLoaded waits just the structure

How to exclude property from Json Serialization

If you are using Json.Net attribute [JsonIgnore] will simply ignore the field/property while serializing or deserialising.

public class Car
{
  // included in JSON
  public string Model { get; set; }
  public DateTime Year { get; set; }
  public List<string> Features { get; set; }

  // ignored
  [JsonIgnore]
  public DateTime LastModified { get; set; }
}

Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.

[DataContract]
public class Computer
{
  // included in JSON
  [DataMember]
  public string Name { get; set; }
  [DataMember]
  public decimal SalePrice { get; set; }

  // ignored
  public string Manufacture { get; set; }
  public int StockCount { get; set; }
  public decimal WholeSalePrice { get; set; }
  public DateTime NextShipmentDate { get; set; }
}

Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details

How do I divide in the Linux console?

Better way is to use "bc", an arbitrary precision calculator.

variable=$(echo "OPTIONS; OPERATIONS" | bc)

ex:

my_var=$(echo "scale=5; $temp_var/100 + $temp_var2" | bc)

where "scale=5" is accuracy.

man bc 

comes with several usage examples.

How to enable relation view in phpmyadmin

first select the table you you would like to make the relation with >> then go to operation , for each table there is difference operation setting, >> inside operation "storage engine" choose innoDB option

innoDB will allow you to view the "relation view" which will help you make the foreign key

enter image description here

Angular 4: How to include Bootstrap?

Step 1 : npm install bootstrap --save

Step : 2 : Paste below code in angular.json node_modules/bootstrap/dist/css/bootstrap.min.css

Step 3 : ng serve

enter image description here

Android BroadcastReceiver within Activity

I think your problem is that you send the broadcast before the other activity start ! so the other activity will not receive anything .

  1. The best practice to test your code is to sendbroadcast from thread or from a service so the activity is opened and its registered the receiver and the background process sends a message.
  2. start the ToastDisplay activity from the sender activity ( I didn't test that but it may work probably )

Scale image to fit a bounding box

This helped me:

.img-class {
  width: <img width>;
  height: <img height>;
  content: url('/path/to/img.png');
}

Then on the element (you can use javascript or media queries to add responsiveness):

<div class='img-class' style='transform: scale(X);'></div>

Hope this helps!

Pygame Drawing a Rectangle

here's how:

import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
pygame.quit()

Mips how to store user input string

Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:

         .text
         .globl __start
    __start:
         la $a0,str1 #Load and print string asking for string
         li $v0,4
         syscall

         li $v0,8 #take in input
         la $a0, buffer #load byte space into address
         li $a1, 20 # allot the byte space for string
         move $t0,$a0 #save string to t0
         syscall

         la $a0,str2 #load and print "you wrote" string
         li $v0,4
         syscall

         la $a0, buffer #reload byte space to primary address
         move $a0,$t0 # primary address = t0 address (load pointer)
         li $v0,4 # print string
         syscall

         li $v0,10 #end program
         syscall


               .data
             buffer: .space 20
             str1:  .asciiz "Enter string(max 20 chars): "
             str2:  .asciiz "You wrote:\n"
             ###############################
             #Output:
             #Enter string(max 20 chars): qwerty 123
             #You wrote:
             #qwerty 123
             #Enter string(max 20 chars):   new world oreddeYou wrote:
             #  new world oredde //lol special character
             ###############################

Combating AngularJS executing controller twice

Just adding my case here as well:

I was using angular-ui-router with $state.go('new_state', {foo: "foo@bar"})

Once I added encodeURIComponent to the parameter, the problem was gone: $state.go('new_state', {foo: encodeURIComponent("foo@bar")}).

What happened? The character "@" in the parameter value is not allowed in URLs. As a consequence, angular-ui-router created my controller twice: during first creation it passed the original "foo@bar", during second creation it would pass the encoded version "foo%40bar". Once I explicitly encoded the parameter as shown above, the problem went away.

char *array and char array[]

No, you're creating an array, but there's a big difference:

char *string = "Some CONSTANT string";
printf("%c\n", string[1]);//prints o
string[1] = 'v';//INVALID!!

The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:

char string[] = "Some string";

creates the same, read only, constant string, and copies it to the stack array. That's why:

string[1] = 'v';

Is valid in the latter case.
If you write:

char string[] = {"some", " string"};

the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:

char string[] = {'s','o','m', 'e', ' ', 's', 't','r','i','n','g', '\o'};
//this is a bit silly, because it's the same as char string[] = "some string";
//or
char *string[] = {"some", " string"};//array of pointers to CONSTANT strings
//or
char string[][10] = {"some", " string"};

Where the last version gives you an array of strings (arrays of chars) that you actually can edit...

Smart way to truncate long strings

Best function I have found. Credit to text-ellipsis.

function textEllipsis(str, maxLength, { side = "end", ellipsis = "..." } = {}) {
  if (str.length > maxLength) {
    switch (side) {
      case "start":
        return ellipsis + str.slice(-(maxLength - ellipsis.length));
      case "end":
      default:
        return str.slice(0, maxLength - ellipsis.length) + ellipsis;
    }
  }
  return str;
}

Examples:

var short = textEllipsis('a very long text', 10);
console.log(short);
// "a very ..."

var short = textEllipsis('a very long text', 10, { side: 'start' });
console.log(short);
// "...ng text"

var short = textEllipsis('a very long text', 10, { textEllipsis: ' END' });
console.log(short);
// "a very END"

How to read a list of files from a folder using PHP?

There is a glob. In this webpage there are good article how to list files in very simple way:

How to read a list of files from a folder using PHP

How to remove underline from a link in HTML?

This will remove all underlines from all links:

a {text-decoration: none; }

If you have specific links that you want to apply this to, give them a class name, like nounderline and do this:

a.nounderline {text-decoration: none; }

That will apply only to those links and leave all others unaffected.

This code belongs in the <head> of your document or in a stylesheet:

<head>
    <style type="text/css">
        a.nounderline {text-decoration: none; }
    </style>
</head>

And in the body:

<a href="#" class="nounderline">Link</a>

Adding item to Dictionary within loop

# Let's add key:value to a dictionary, the functional way 
# Create your dictionary class 
class my_dictionary(dict): 
    # __init__ function 
    def __init__(self): 
        self = dict()   
    # Function to add key:value 
    def add(self, key, value): 
        self[key] = value 
# Main Function 
dict_obj = my_dictionary() 
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :   
    dict_obj.key = input("Enter the key: ") 
    dict_obj.value = input("Enter the value: ") 
    dict_obj.add(dict_obj.key, dict_obj.value) 
    c += 1
print(dict_obj) 

How to select a div element in the code-behind page?

@CarlosLanderas is correct depending on where you've placed the DIV control. The DIV by the way is not technically an ASP control, which is why you cannot find it directly like other controls. But the best way around this is to turn it into an ASP control.

Use asp:Panel instead. It is rendered into a <div> tag anyway...

<asp:Panel id="divSubmitted" runat="server" style="text-align:center" visible="false">
   <asp:Label ID="labSubmitted" runat="server" Text="Roll Call Submitted"></asp:Label>
</asp:Panel>

And in code behind, simply find the Panel control as per normal...

Panel DivCtl1 = (Panel)gvRollCall.FooterRow.FindControl("divSubmitted");
if (DivCtl1 != null)
    DivCtl1.Visible = true;

Please note that I've used FooterRow, as my "psuedo div" is inside the footer row of a Gridview control.

Good coding!

How to use goto statement correctly

If you look up continue and break they accept a "Label". Experiment with that. Goto itself won't work.

public class BreakContinueWithLabel {

    public static void main(String args[]) {

        int[] numbers= new int[]{100,18,21,30};

        //Outer loop checks if number is multiple of 2
        OUTER:  //outer label
        for(int i = 0; i<numbers.length; i++){
            if(i % 2 == 0){
                System.out.println("Odd number: " + i +
                                   ", continue from OUTER label");
                continue OUTER;
            }

            INNER:
            for(int j = 0; j<numbers.length; j++){
                System.out.println("Even number: " + i +
                                   ", break  from INNER label");
                break INNER;
            }
        }      
    }
}

Read more

How do I preserve line breaks when getting text from a textarea?

Here is an idea as you may have multiple newline in a textbox:

 var text=document.getElementById('post-text').value.split('\n');
 var html = text.join('<br />');

This HTML value will preserve newline. Hope this helps.

Entity framework left join

It might be a bit of an overkill, but I wrote an extension method, so you can do a LeftJoin using the Join syntax (at least in method call notation):

persons.LeftJoin(
    phoneNumbers,
    person => person.Id,
    phoneNumber => phoneNumber.PersonId,
    (person, phoneNumber) => new
        {
            Person = person,
            PhoneNumber = phoneNumber?.Number
        }
);

My code does nothing more than adding a GroupJoin and a SelectMany call to the current expression tree. Nevertheless, it looks pretty complicated because I have to build the expressions myself and modify the expression tree specified by the user in the resultSelector parameter to keep the whole tree translatable by LINQ-to-Entities.

public static class LeftJoinExtension
{
    public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
        this IQueryable<TOuter> outer,
        IQueryable<TInner> inner,
        Expression<Func<TOuter, TKey>> outerKeySelector,
        Expression<Func<TInner, TKey>> innerKeySelector,
        Expression<Func<TOuter, TInner, TResult>> resultSelector)
    {
        MethodInfo groupJoin = typeof (Queryable).GetMethods()
                                                 .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
                                                 .MakeGenericMethod(typeof (TOuter), typeof (TInner), typeof (TKey), typeof (LeftJoinIntermediate<TOuter, TInner>));
        MethodInfo selectMany = typeof (Queryable).GetMethods()
                                                  .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
                                                  .MakeGenericMethod(typeof (LeftJoinIntermediate<TOuter, TInner>), typeof (TInner), typeof (TResult));

        var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
                                      ((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> {OneOuter = oneOuter, ManyInners = manyInners});

        MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);

        var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
                                           (t => t.ManyInners.DefaultIfEmpty());

        ParameterExpression paramUser = resultSelector.Parameters.First();

        ParameterExpression paramNew = Expression.Parameter(typeof (LeftJoinIntermediate<TOuter, TInner>), "t");
        MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");

        LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body), paramNew, resultSelector.Parameters.Skip(1).First());

        MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);

        return outer.Provider.CreateQuery<TResult>(exprSelectMany);
    }

    private class LeftJoinIntermediate<TOuter, TInner>
    {
        public TOuter OneOuter { get; set; }
        public IEnumerable<TInner> ManyInners { get; set; }
    }

    private class Replacer : ExpressionVisitor
    {
        private readonly ParameterExpression _oldParam;
        private readonly Expression _replacement;

        public Replacer(ParameterExpression oldParam, Expression replacement)
        {
            _oldParam = oldParam;
            _replacement = replacement;
        }

        public override Expression Visit(Expression exp)
        {
            if (exp == _oldParam)
            {
                return _replacement;
            }

            return base.Visit(exp);
        }
    }
}

Difference between <input type='submit' /> and <button type='submit'>text</button>

Not sure where you get your legends from but:

Submit button with <button>

As with:

<button type="submit">(html content)</button>

IE6 will submit all text for this button between the tags, other browsers will only submit the value. Using <button> gives you more layout freedom over the design of the button. In all its intents and purposes, it seemed excellent at first, but various browser quirks make it hard to use at times.

In your example, IE6 will send text to the server, while most other browsers will send nothing. To make it cross-browser compatible, use <button type="submit" value="text">text</button>. Better yet: don't use the value, because if you add HTML it becomes rather tricky what is received on server side. Instead, if you must send an extra value, use a hidden field.

Button with <input>

As with:

<input type="button" />

By default, this does next to nothing. It will not even submit your form. You can only place text on the button and give it a size and a border by means of CSS. Its original (and current) intent was to execute a script without the need to submit the form to the server.

Normal submit button with <input>

As with:

<input type="submit" />

Like the former, but actually submits the surrounding form.

Image submit button with <input>

As with:

<input type="image" />

Like the former (submit), it will also submit a form, but you can use any image. This used to be the preferred way to use images as buttons when a form needed submitting. For more control, <button> is now used. This can also be used for server side image maps but that's a rarity these days. When you use the usemap-attribute and (with or without that attribute), the browser will send the mouse-pointer X/Y coordinates to the server (more precisely, the mouse-pointer location inside the button of the moment you click it). If you just ignore these extras, it is nothing more than a submit button disguised as an image.

There are some subtle differences between browsers, but all will submit the value-attribute, except for the <button> tag as explained above.

reading HttpwebResponse json response, C#

If you're getting source in Content Use the following method

try
{
    var response = restClient.Execute<List<EmpModel>>(restRequest);

    var jsonContent = response.Content;

    var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);

    foreach (EmpModel item in data)
    {
        listPassingData?.Add(item);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Data get mathod problem {ex} ");
}

Finding the median of an unsorted array

The answer is "No, one can't find the median of an arbitrary, unsorted dataset in linear time". The best one can do as a general rule (as far as I know) is Median of Medians (to get a decent start), followed by Quickselect. Ref: [https://en.wikipedia.org/wiki/Median_of_medians][1]

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

Kotlin:

var list=ArrayList<Your class name>()
val listresult: Array<YOUR CLASS NAME> = Gson().fromJson(
                YOUR JSON RESPONSE IN STRING,
                Array<Your class name>:: class.java)

list.addAll(listresult)

Trust Anchor not found for Android SSL Connection

If you use retrofit, you need to customize your OkHttpClient.

retrofit = new Retrofit.Builder()
                        .baseUrl(ApplicationData.FINAL_URL)
                        .client(getUnsafeOkHttpClient().build())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

Full code are as below.

    public class RestAdapter {

    private static Retrofit retrofit = null;
    private static ApiInterface apiInterface;

    public static OkHttpClient.Builder getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            return builder;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static ApiInterface getApiClient() {
        if (apiInterface == null) {

            try {
                retrofit = new Retrofit.Builder()
                        .baseUrl(ApplicationData.FINAL_URL)
                        .client(getUnsafeOkHttpClient().build())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

            } catch (Exception e) {

                e.printStackTrace();
            }


            apiInterface = retrofit.create(ApiInterface.class);
        }
        return apiInterface;
    }

}

ExecuteNonQuery: Connection property has not been initialized.

just try this..

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

Change div height on button click

You have to set height as a string value when you use pixels.

document.getElementById('chartdiv').style.height = "200px"

Also try adding a DOCTYPE to your HTML for Internet Explorer.

<!DOCTYPE html>
<html> ...

onKeyDown event not working on divs in React

You're missing the binding of the method in the constructor. This is how React suggests that you do it:

class Whatever {
  constructor() {
    super();
    this.onKeyPressed = this.onKeyPressed.bind(this);
  }

  onKeyPressed(e) {
    // your code ...
  }

  render() {
    return (<div onKeyDown={this.onKeyPressed} />);
  }
}

There are other ways of doing this, but this will be the most efficient at runtime.

How to display the first few characters of a string in Python?

If you want first 2 letters and last 2 letters of a string then you can use the following code: name = "India" name[0:2]="In" names[-2:]="ia"

Run an Ansible task only when the variable contains a specific string

use this

when: "{{ 'value' in variable1}}"

instead of

when: "'value' in {{variable1}}"

Also for string comparison you can use

when: "{{ variable1 == 'value' }}"

Depend on a branch or tag using a git URL in a package.json?

If you want to use devel or feature branch, or you haven’t published a certain package to the NPM registry, or you can’t because it’s a private module, then you can point to a git:// URI instead of a version number in your package.json:

"dependencies": {
   "public": "git://github.com/user/repo.git#ref",
   "private": "git+ssh://[email protected]:user/repo.git#ref"
}

The #ref portion is optional, and it can be a branch (like master), tag (like 0.0.1) or a partial or full commit id.

Bootstrap 3: Text overlay on image

Set the position to absolute; to move the caption area in the correct position

CSS

.post-content {
    background: none repeat scroll 0 0 #FFFFFF;
    opacity: 0.5;
    margin: -54px 20px 12px; 
    position: absolute;
}

Bootply

displayname attribute vs display attribute

DisplayName sets the DisplayName in the model metadata. For example:

[DisplayName("foo")]
public string MyProperty { get; set; }

and if you use in your view the following:

@Html.LabelFor(x => x.MyProperty)

it would generate:

<label for="MyProperty">foo</label>

Display does the same, but also allows you to set other metadata properties such as Name, Description, ...

Brad Wilson has a nice blog post covering those attributes.

Xcode 6: Keyboard does not show up in simulator

You can use : ?+?+K to show keyboard on simulator.

psql: FATAL: Peer authentication failed for user "dev"

For people in the future seeing this, postgres is in the /usr/lib/postgresql/10/bin on my Ubuntu server.

I added it to the PATH in my .bashrc file, and add this line at the end

PATH=$PATH:/usr/lib/postgresql/10/bin

then on the command line

$> source ./.bashrc

I refreshed my bash environment. Now I can use postgres -D /wherever from any directory

how to disable DIV element and everything inside

You can't use "disable" to disable a click event. I don't know how or if it worked in IE6-9, but it didn't work on Chrome, and it shouldn't work on IE10 like that.

You can disable the onclick event, too, by attaching an event that cancels:

;(function () {
    function cancel () { return false; };
    document.getElementById("test").disabled = true;
    var nodes = document.getElementById("test").getElementsByTagName('*');
    console.log(nodes);
    for (var i = 0; i < nodes.length; i++) {
        nodes[i].setAttribute('disabled', true);
        nodes[i].onclick = cancel;
    }
}());

Furthermore, setting "disabled" on a node directly doesn't necessarily add the attribute- using setAttribute does.

http://jsfiddle.net/2fPZu/

How to handle anchor hash linking in AngularJS

Try to set a hash prefix for angular routes $locationProvider.hashPrefix('!')

Full example:

angular.module('app', [])
  .config(['$routeProvider', '$locationProvider', 
    function($routeProvider, $locationProvider){
      $routeProvider.when( ... );
      $locationProvider.hashPrefix('!');
    }
  ])

use a javascript array to fill up a drop down select box

Use a for loop to iterate through your array. For each string, create a new option element, assign the string as its innerHTML and value, and then append it to the select element.

var cuisines = ["Chinese","Indian"];     
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisines[i];
    opt.value = cuisines[i];
    sel.appendChild(opt);
}

DEMO

UPDATE: Using createDocumentFragment and forEach

If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild operation so that the DOM only updates once, instead of n times.

var cuisines = ["Chinese","Indian"];     

var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();

cuisines.forEach(function(cuisine, index) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisine;
    opt.value = cuisine;
    fragment.appendChild(opt);
});

sel.appendChild(fragment);

DEMO

Pass Javascript variable to PHP via ajax

Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset is a function to check if something exists and has a value, not to get access to the value.

Change your PHP to be:

$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;

The above line will check to see if the post variable exists. If it does exist it will set $uid to equal the posted value. If it does not exist then it will set $uid equal to 0.

Later in your code you can check the value of $uid and react accordingly

if($uid==0) {
    echo 'User ID not found';
}

This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.

How to automatically generate getters and setters in Android Studio

You can use AndroidAccessors Plugin of Android Studio to generate getter and setter without m as prefix to methods

Ex: mId; Will generate getId() and setId() instead of getmId() and setmId()

plugin screenshot

Can you call ko.applyBindings to bind a partial view?

ko.applyBindings accepts a second parameter that is a DOM element to use as the root.

This would let you do something like:

<div id="one">
  <input data-bind="value: name" />
</div>

<div id="two">
  <input data-bind="value: name" />
</div>

<script type="text/javascript">
  var viewModelA = {
     name: ko.observable("Bob")
  };

  var viewModelB = {
     name: ko.observable("Ted")
  };

  ko.applyBindings(viewModelA, document.getElementById("one"));
  ko.applyBindings(viewModelB, document.getElementById("two"));
</script>

So, you can use this technique to bind a viewModel to the dynamic content that you load into your dialog. Overall, you just want to be careful not to call applyBindings multiple times on the same elements, as you will get multiple event handlers attached.

Completely removing phpMyAdmin

If your system is using dpkg and apt (debian, ubuntu, etc), try running the following commands in that order (be careful with the sudo rm commands):

sudo apt-get -f install
sudo dpkg -P phpmyadmin  
sudo rm -vf /etc/apache2/conf.d/phpmyadmin.conf
sudo rm -vfR /usr/share/phpmyadmin
sudo service apache2 restart

How to set a default entity property value with Hibernate

To use default value from any column of table. then you must need to define @DynamicInsert as true or else you just define @DynamicInsert. Because hibernate takes by default as a true. Consider as the given example:

@AllArgsConstructor
@Table(name = "core_contact")
@DynamicInsert
public class Contact implements Serializable {

    @Column(name = "status", columnDefinition = "int default 100")
    private Long status;

}

How to show hidden divs on mouseover?

You could wrap the hidden div in another div that will toggle the visibility with onMouseOver and onMouseOut event handlers in JavaScript:

<style type="text/css">
  #div1, #div2, #div3 {  
    visibility: hidden;  
  }
</style>
<script>
  function show(id) {
    document.getElementById(id).style.visibility = "visible";
  }
  function hide(id) {
    document.getElementById(id).style.visibility = "hidden";
  }
</script>

<div onMouseOver="show('div1')" onMouseOut="hide('div1')">
  <div id="div1">Div 1 Content</div>
</div>
<div onMouseOver="show('div2')" onMouseOut="hide('div2')">
  <div id="div2">Div 2 Content</div>
</div>
<div onMouseOver="show('div3')" onMouseOut="hide('div3')">
  <div id="div3">Div 3 Content</div>
</div>

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Consider this snippet of code. Modify as you see fit, or to fit your requirements. You'll need to have Imports statements for System.IO and System.Data.OleDb.

Dim fi As New FileInfo("c:\foo.csv")
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName

Dim conn As New OleDbConnection(connectionString)
conn.Open()

'the SELECT statement is important here, 
'and requires some formatting to pull dates and deal with headers with spaces.
Dim cmdSelect As New OleDbCommand("SELECT Foo, Bar, FORMAT(""SomeDate"",'YYYY/MM/DD') AS SomeDate, ""SOME MULTI WORD COL"", FROM " & fi.Name, conn)

Dim adapter1 As New OleDbDataAdapter
adapter1.SelectCommand = cmdSelect

Dim ds As New DataSet
adapter1.Fill(ds, "DATA")

myDataGridView.DataSource = ds.Tables(0).DefaultView 
myDataGridView.DataBind
conn.Close()

"Fatal error: Cannot redeclare <function>"

you can check first if name of your function isn`t exists or not before you write function By

  if (!function_exists('generate_salt'))
{
    function generate_salt()
    {
    ........
    }
}

OR you can change name of function to another name

Default visibility for C# classes and members (fields, methods, etc.)?

All of the information you are looking for can be found here and here (thanks Reed Copsey):

From the first link:

Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.

...

The access level for class members and struct members, including nested classes and structs, is private by default.

...

interfaces default to internal access.

...

Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.


From the second link:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.

And for nested types:

Members of    Default member accessibility
----------    ----------------------------
enum          public
class         private
interface     public
struct        private

IIS: Display all sites and bindings in PowerShell

Try this

function DisplayLocalSites
{

try{

Set-ExecutionPolicy unrestricted

$list = @()
foreach ($webapp in get-childitem IIS:\Sites\)
{
    $name = "IIS:\Sites\" + $webapp.name
    $item = @{}

$item.WebAppName = $webapp.name

foreach($Bind in $webapp.Bindings.collection)
{
    $item.SiteUrl = $Bind.Protocol +'://'+         $Bind.BindingInformation.Split(":")[-1]
}


$obj = New-Object PSObject -Property $item
$list += $obj
}

$list | Format-Table -a -Property "WebAppName","SiteUrl"

$list | Out-File -filepath C:\websites.txt

Set-ExecutionPolicy restricted

}
catch
{
$ExceptionMessage = "Error in Line: " + $_.Exception.Line + ". " +     $_.Exception.GetType().FullName + ": " + $_.Exception.Message + " Stacktrace: "    + $_.Exception.StackTrace
$ExceptionMessage
}
}

make a phone call click on a button

None of the above worked so with a bit of tinkering here's code that did for me

        Intent i = new Intent(Intent.ACTION_DIAL);
        String p = "tel:" + getString(R.string.phone_number);
        i.setData(Uri.parse(p));
        startActivity(i);

Make a float only show two decimal places

 lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];

momentJS date string add 5 days

The function add() returns the old date, but changes the original date :)

startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days');
alert(new_date);

EF 5 Enable-Migrations : No context type was found in the assembly

My problem was link----> problem1

I solved that problem with one simple command line

Install-Package EntityFramework-IncludePrerelease

After that, i needed to face with one more problem, something like:

"No context type was found in assembly"

I solve this really easy. This "No context" that mean you need to create class in "Model" folder in your app with suffix like DbContext ... like this MyDbContext. There you need to include some library using System.Data.Entity;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;


namespace Oceans.Models
{
    public class MyDbContext:DbContext
    {
        public MyDbContext()
        {
        }
    }
}

After that,i just needed this command line:

Enable-Migrations -ProjectName <YourProjectName> -ContextTypeName <YourContextName>

Jquery - How to get the style display attribute "none / block"

//animated show/hide

function showHide(id) {
      var hidden= ("none" == $( "#".concat(id) ).css("display"));
      if(hidden){
          $( "#".concat(id) ).show(1000);
      }else{
          $("#".concat(id) ).hide(1000);
      }
  }

Iterating over dictionaries using 'for' loops

key is simply a variable.

For Python2.X:

d = {'x': 1, 'y': 2, 'z': 3} 
for my_var in d:
    print my_var, 'corresponds to', d[my_var]

... or better,

d = {'x': 1, 'y': 2, 'z': 3} 
for the_key, the_value in d.iteritems():
    print the_key, 'corresponds to', the_value

For Python3.X:

d = {'x': 1, 'y': 2, 'z': 3} 
for the_key, the_value in d.items():
    print(the_key, 'corresponds to', the_value)

DateTime.TryParseExact() rejecting valid formats

Here you can check for couple of things.

  1. Date formats you are using correctly. You can provide more than one format for DateTime.TryParseExact. Check the complete list of formats, available here.
  2. CultureInfo.InvariantCulture which is more likely add problem. So instead of passing a NULL value or setting it to CultureInfo provider = new CultureInfo("en-US"), you may write it like. .

    if (!DateTime.TryParseExact(txtStartDate.Text, formats, 
                    System.Globalization.CultureInfo.InvariantCulture,
                    System.Globalization.DateTimeStyles.None, out startDate))
    {
        //your condition fail code goes here
        return false;
    }
    else
    {
        //success code
    }
    

Load arrayList data into JTable

I created an arrayList from it and I somehow can't find a way to store this information into a JTable.

The DefaultTableModel doesn't support displaying custom Objects stored in an ArrayList. You need to create a custom TableModel.

You can check out the Bean Table Model. It is a reusable class that will use reflection to find all the data in your FootballClub class and display in a JTable.

Or, you can extend the Row Table Model found in the above link to make is easier to create your own custom TableModel by implementing a few methods. The JButtomTableModel.java source code give a complete example of how you can do this.

How to prevent a click on a '#' link from jumping to top of page?

So this is old but... just in case someone finds this in a search.

Just use "#/" instead of "#" and the page won't jump.

how to have two headings on the same line in html

You'd need to wrap the two headings in a div tag, and have that div tag use a style that does clear: both. e.g:

<div style="clear: both">
    <h2 style="float: left">Heading 1</h2>
    <h3 style="float: right">Heading 2</h3>
</div>
<hr />

Having the hr after the div tag will ensure that it is pushed beneath both headers.

Or something very similar to that. Hope this helps.

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

PHP foreach with Nested Array?

As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}


public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

and if you want to have all of children IDs as an Array , This approach is fine and working for me :

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

the allChildren() returns , all of childrens as a simple Array .

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

Copy files to network computers on windows command line

check Robocopy:

ROBOCOPY \\server-source\c$\VMExports\ C:\VMExports\ /E /COPY:DAT

make sure you check what robocopy parameter you want. this is just an example. type robocopy /? in a comandline/powershell on your windows system.

Android: No Activity found to handle Intent error? How it will resolve

Add the below to your manifest:

  <activity   android:name=".AppPreferenceActivity" android:label="@string/app_name">  
     <intent-filter> 
       <action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />  
       <category android:name="android.intent.category.DEFAULT" />  
     </intent-filter>   
  </activity>

How to set a ripple effect on textview or imageview on Android?

Add android:clickable="true" android:focusable="true"

For Ripple Effect

android:background="?attr/selectableItemBackgroundBorderless"

For Selectable Effect

android:background="?android:attr/selectableItemBackground"

For Button effect

android:adjustViewBounds="true" style="?android:attr/borderlessButtonStyle"

Regular expression to extract URL from an HTML link

this should work, although there might be more elegant ways.

import re
url='<a href="http://www.ptop.se" target="_blank">http://www.ptop.se</a>'
r = re.compile('(?<=href=").*?(?=")')
r.findall(url)

List of standard lengths for database fields

W3C's recommendation:

If designing a form or database that will accept names from people with a variety of backgrounds, you should ask yourself whether you really need to have separate fields for given name and family name.

… Bear in mind that names in some cultures can be quite a lot longer than your own. … Avoid limiting the field size for names in your database. In particular, do not assume that a four-character Japanese name in UTF-8 will fit in four bytes – you are likely to actually need 12.

https://www.w3.org/International/questions/qa-personal-names

For database fields, VARCHAR(255) is a safe default choice, unless you can actually come up with a good reason to use something else. For typical web applications, performance won't be a problem. Don't prematurely optimize.

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

What is the equivalent of Select Case in Access SQL?

You can use IIF for a similar result.

Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

Jupyter Users

Whenever I need this for just one cell, I use this:

with pd.option_context('display.max_colwidth', None):
  display(df)

batch file - counting number of files in folder and storing in a variable

The mugume david answer fails on an empty folder; Count is 1 instead of a 0 when looking for a pattern rather than all files. For example *.xml

This works for me:

attrib.exe /s ./*.xml | find /v "File not found - " | find /c /v ""

Convert or extract TTC font to TTF - how to?

If you've got a Mac the easiest way to split those would be to use DfontSplitter, available at https://peter.upfold.org.uk/projects/dfontsplitter

The Windows version they provide doesn't work with ttc files.