Programs & Examples On #Appcmd

The command line utility for configuring IIS 7.

(413) Request Entity Too Large | uploadReadAheadSize

That is not problem of IIS but the problem of WCF. WCF by default limits messages to 65KB to avoid denial of service attack with large messages. Also if you don't use MTOM it sends byte[] to base64 encoded string (33% increase in size) => 48KB * 1,33 = 64KB

To solve this issue you must reconfigure your service to accept larger messages. This issue previously fired 400 Bad Request error but in newer version WCF started to use 413 which is correct status code for this type of error.

You need to set maxReceivedMessageSize in your binding. You can also need to set readerQuotas.

<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding maxReceivedMessageSize="10485760">
        <readerQuotas ... />
      </binding>
    </basicHttpBinding>
  </bindings>  
</system.serviceModel>

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

I ran into this problem and inspired by @Jeremy Cook's answer, I bit the bullet to find out what the heck caused IIS 7 Integrated mode to not like my web.config. Here's my scenario:

  1. Web API (version 4.0.030506.0 aka the old one)
  2. .NET 4.0
  3. Attribute Routing 3.5.6 for Web API [spoiler alert: it was this guy!]

I wanted to use attribute routing in a project that (unfortunately) had to use .NET 4 and hence could not use Web API 2.2 (which needs .NET 4.5). The well meaning NuGet package added this section under the <system.web> section:

<system.web>
<httpHandlers>
      <add verb="*" path="routes.axd" type="AttributeRouting.Web.Logging.LogRoutesHandler, AttributeRouting.Web" />
    </httpHandlers>
</system.web>

[I say well meaning, because this part is required on older versions of IIS]

Removing this section got me past the HTTP 500.23!!

Summary: I second Jeremy's words that it is important to understand why things don't work rather than just "masking the symptom". Even if you have to mask the symptom, you know what you are doing (and why) :-)

How do you migrate an IIS 7 site to another server?

use appcmd to export one or all the sites out then reimport into the new server. It could be iis7.0 or 7.5 When you export out using appcmd, the passwords are decrypted, then reimport and they will reencrypt.

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

You must define Full-Text-Index on all tables in database where you require to use a query with CONTAINS which will take sometime.

Instead you can use the LIKE which will give you instant results without the need to adjust any settings for the tables.

Example:

SELECT * FROM ChartOfAccounts WHERE AccountName LIKE '%Tax%'

The same result obtained with CONTAINS can be obtained with LIKE.

see the result: enter image description here

PermissionError: [Errno 13] Permission denied

I had a similar problem. I thought it might be with the system. But, using shutil.copytree() from the shutil module solved the problem for me!

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

The tendency to avoid stuff because it takes longer to type is a bad thing, try to root it out. That said, overly verbose things are also difficult to read, so small and simple is important, but it's readability not writability that's important. Concise one-liners can often be more difficult to read than a simple well laid out 3 or 4 lines.

Use whichever construct best descibes the logic of the operation.

How do I pass a variable by reference?

Here is the simple (I hope) explanation of the concept pass by object used in Python.
Whenever you pass an object to the function, the object itself is passed (object in Python is actually what you'd call a value in other programming languages) not the reference to this object. In other words, when you call:

def change_me(list):
   list = [1, 2, 3]

my_list = [0, 1]
change_me(my_list)

The actual object - [0, 1] (which would be called a value in other programming languages) is being passed. So in fact the function change_me will try to do something like:

[0, 1] = [1, 2, 3]

which obviously will not change the object passed to the function. If the function looked like this:

def change_me(list):
   list.append(2)

Then the call would result in:

[0, 1].append(2)

which obviously will change the object. This answer explains it well.

How to get multiline input from user

raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:

Python 3

print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
    try:
        line = input()
    except EOFError:
        break
    contents.append(line)

Python 2

print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
    try:
        line = raw_input("")
    except EOFError:
        break
    contents.append(line)

Get div to take up 100% body height, minus fixed-height header and footer

This question has been pretty well answered, but I'm taking the liberty of adding a javascript solution. Just give the element that you want to 'expand' the id footerspacerdiv, and this javascript snippet will expand that div until the page takes up the full height of the browser window.

It works based on the observation that, when a page is less than the full height of the browser window, document.body.scrollHeight is equal to document.body.clientHeight. The while loop increases the height of footerspacerdiv until document.body.scrollHeight is greater than document.body.clientHeight. At this point, footerspacerdiv will actually be 1 pixel too tall, and the browser will show a vertical scroll bar. So, the last line of the script reduces the height of footerspacerdiv by one pixel to make the page height exactly the height of the browser window.

By placing footerspacerdiv just above the 'footer' of the page, this script can be used to 'push the footer down' to the bottom of the page, so that on short pages, the footer is flush with the bottom of the browser window.

<script>    
//expand footerspacer div so that footer goes to bottom of page on short pages        
  var objSpacerDiv=document.getElementById('footerspacer');          
  var bresize=0;   

  while(document.body.scrollHeight<=document.body.clientHeight) {
    objSpacerDiv.style.height=(objSpacerDiv.clientHeight+1)+"px";
    bresize=1;
  }             
  if(bresize) { objSpacerDiv.style.height=(objSpacerDiv.clientHeight-1)+"px"; }               
 </script>

adb remount permission denied, but able to access super user in shell -- android

Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.

Set a cookie to never expire

I'm not sure but aren't cookies deleted at browser close? I somehow did a never expiring cookie and chrome recognized expired date as "at browser close" ...

How can I remove all objects but one from the workspace in R?

From within a function, rm all objects in .GlobalEnv except the function

initialize <- function(country.name) {

  if (length(setdiff(ls(pos = .GlobalEnv), "initialize")) > 0) {
    rm(list=setdiff(ls(pos = .GlobalEnv), "initialize"), pos = .GlobalEnv)
  }

}

Animated GIF in IE stopping

Related to this I had to find a fix where animated gifs were used as a background image to ensure styling was kept to the stylesheet. A similar fix worked for me there too... my script went something like this (I'm using jQuery to make it easier to get the computed background style - how to do that without jQuery is a topic for another post):

var spinner = <give me a spinner element>

window.onbeforeunload = function() {
  bg_image = $(spinner).css('background-image');
  spinner.style.backgroundImage = 'none';
  spinner.style.backgroundImage = bg_image;
}

[EDIT] With a bit more testing I've just realised that this doesn't work with background images in IE8. I've been trying everything I can think of to get IE8 to render a gif animation wile loading a page, but it doesn't look possible at this time.

Check if a String contains numbers Java

Below code snippet will tell whether the String contains digit or not

str.matches(".*\\d.*")
or
str.matches(.*[0-9].*)

For example

String str = "abhinav123";

str.matches(".*\\d.*") or str.matches(.*[0-9].*)  will return true 

str = "abhinav";

str.matches(".*\\d.*") or str.matches(.*[0-9].*)  will return false

Register 32 bit COM DLL to 64 bit Windows 7

http://onerkaya.blogspot.com/2013/03/register-com-dll-on-windows-64-bit.html

Retrieving the COM class factory for component with CLSID {...} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

if you try this;

c:\windows\system32\regsvr32.exe < filename >.dll

you can still take this exception. so IIS- pool Advanced settings, Enable 32 bit application : true ;)

Get size of an Iterable in Java

I would go for it.next() for the simple reason that next() is guaranteed to be implemented, while remove() is an optional operation.

E next()

Returns the next element in the iteration.

void remove()

Removes from the underlying collection the last element returned by the iterator (optional operation).

Passing headers with axios POST request

When using axios, in order to pass custom headers, supply an object containing the headers as the last argument

Modify your axios request like:

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'JWT fefege...'
}

axios.post(Helper.getUserAPI(), data, {
    headers: headers
  })
  .then((response) => {
    dispatch({
      type: FOUND_USER,
      data: response.data[0]
    })
  })
  .catch((error) => {
    dispatch({
      type: ERROR_FINDING_USER
    })
  })

Custom alert and confirm box in jquery

I made custom messagebox using jquery UI component. Here is demo http://jsfiddle.net/eraj2587/Pm5Fr/14/

You have to pass just the parameters like caption name, message, button's text. You can specify trigger function on any button click. This will helpful for you.

React.js: onChange event for contentEditable

Since when the edit is complete the focus from the element is always lost you could simply use the onBlur hook.

<div onBlur={(e)=>{console.log(e.currentTarget.textContent)}} contentEditable suppressContentEditableWarning={true}>
     <p>Lorem ipsum dolor.</p>
</div>

Git add all files modified, deleted, and untracked?

git add --all or git add -A or git add -A . Stages All

git add . Stages New & Modified But Without Deleted

git add -u Stages Modified & Deleted But Without New

git commit -a Means git add -u And git commit -m "message"

After writing this command follow these steps:-

  1. press i
  2. write your message
  3. press esc
  4. press :wq
  5. press enter

git add <list of files> add specific file

git add *.txt add all the txt files in current directory

git add docs/*/txt add all txt files in docs directory

git add docs/ add all files in docs directory

git add "*.txt" or git add '*.txt' add all the files in the whole project

JavaScript - cannot set property of undefined

In javascript almost everything is an object, null and undefined are exception.

Instances of Array is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object

How to return history of validation loss in Keras

For plotting the loss directly the following works:

model_ = model.fit(X, Y, epochs= ..., verbose=1 )
plt.plot(list(model_.history.values())[0],'k-o')

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

If you really want it to look more semantic like having the <body> in the middle you can use the <main> element. With all the recent advances the <body>element is not as semantic as it once was but you just have to think of it as a wrapper in which the view port sees.

<html>
    <head>
    </head>
    <body>
        <header>
        </header>
        <main>
            <section></section>
            <article></article>
        </main>
        <footer>
        </footer>
    <body>
</html>

When restoring a backup, how do I disconnect all active connections?

To add to advice already given, if you have a web app running through IIS that uses the DB, you may also need to stop (not recycle) the app pool for the app while you restore, then re-start. Stopping the app pool kills off active http connections and doesn't allow any more, which could otherwise end up allowing processes to be triggered that connect to and thereby lock the database. This is a known issue for example with the Umbraco Content Management System when restoring its database

SQL Server format decimal places with commas

without considering this to be a good idea...

select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))

Function

-- Author:      bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50)) 
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int

Select @i=CHARINDEX('.',@NumStr)
if @i=0 
    begin
    set @i=LEN(@NumStr)
    Set @Outstr=''
    end
else
    begin   
     Set @Outstr=SUBSTRING(@NUmStr,@i,50)
     Set @i=@i -1
    end 


Set @run=0

While @i>0
    begin
      if @Run=3
        begin
          Set @Outstr=','+@Outstr
          Set @run=0
        end
      Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr  
      Set @i=@i-1
      Set @run=@run + 1     
    end

    RETURN @OutStr

END
GO

Linking a qtDesigner .ui file to python/pyqt?

Combining Max's answer and Shriramana Sharma's mailing list post, I built a small working example for loading a mywindow.ui file containing a QMainWindow (so just choose to create a Main Window in Qt Designer's File-New dialog).

This is the code that loads it:

import sys
from PyQt4 import QtGui, uic

class MyWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        uic.loadUi('mywindow.ui', self)
        self.show()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = MyWindow()
    sys.exit(app.exec_())

Soft keyboard open and close listener in an activity in Android

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/addresses_confirm_root_view"
android:orientation="vertical">

<---In the xml root use the id--->

final LinearLayout activityRootView = view.findViewById(R.id.addresses_confirm_root_view); activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect r = new Rect(); //r will be populated with the coordinates of your view that area still visible. activityRootView.getWindowVisibleDisplayFrame(r);

            int heightDiff = activityRootView.getRootView().getHeight() - r.height();
            if (heightDiff > 0.25 * activityRootView.getRootView().getHeight()) {
                // if more than 25% of the screen, its probably a keyboard...
                onkeyboard();

            } else {
                //Keyboard not visible
                offkeyboard();
            }
        }
    });

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

Sending multipart/formdata with jQuery.ajax

The FormData class does work, however in iOS Safari (on the iPhone at least) I wasn't able to use Raphael Schweikert's solution as is.

Mozilla Dev has a nice page on manipulating FormData objects.

So, add an empty form somewhere in your page, specifying the enctype:

<form enctype="multipart/form-data" method="post" name="fileinfo" id="fileinfo"></form>

Then, create FormData object as:

var data = new FormData($("#fileinfo"));

and proceed as in Raphael's code.

how to make a countdown timer in java

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
static int interval;
static Timer timer;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Input seconds => : ");
    String secs = sc.nextLine();
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = Integer.parseInt(secs);
    System.out.println(secs);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            System.out.println(setInterval());

        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}
}

Try this.

Iterating over Numpy matrix rows to apply a function each?

Use numpy.apply_along_axis(). Assuming your matrix is 2D, you can use like:

import numpy as np
mymatrix = np.matrix([[11,12,13],
                      [21,22,23],
                      [31,32,33]])
def myfunction( x ):
    return sum(x)

print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.

If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.

Error message "Strict standards: Only variables should be passed by reference"

The cause of the error is the use of the internal PHP programming data structures function, array_shift() [php.net/end].

The function takes an array as a parameter. Although an ampersand is indicated in the prototype of array_shift() in the manual", there isn't any cautionary documentation following in the extended definition of that function, nor is there any apparent explanation that the parameter is in fact passed by reference.

Perhaps this is /understood/. I did not understand, however, so it was difficult for me to detect the cause of the error.

Reproduce code:

function get_arr()
{
    return array(1, 2);
}
$array = get_arr();
$el = array_shift($array);

What's the difference between isset() and array_key_exists()?

Answer to an old question as no answer here seem to address the 'warning' problem (explanation follows)

Basically, in this case of checking if a key exists in an array, isset

  • tells if the expression (array) is defined, and the key is set
  • no warning or error if the var is not defined, not an array ...
  • but returns false if the value for that key is null

and array_key_exists

  • tells if a key exists in an array as the name implies
  • but gives a warning if the array parameter is not an array

So how do we check if a key exists which value may be null in a variable

  • that may or may not be an array
  • (or similarly is a multidimensional array for which the key check happens at dim 2 and dim 1 value may not be an array for the 1st dim (etc...))

without getting a warning, without missing the existing key when its value is null (what were the PHP devs thinking would also be an interesting question, but certainly not relevant on SO). And of course we don't want to use @

isset($var[$key]);            // silent but misses null values
array_key_exists($key, $var); // works but warning if $var not defined/array

It seems is_array should be involved in the equation, but it gives a warning if $var is not defined, so that could be a solution:

if (isset($var[$key]) || 
    isset($var) && is_array($var) && array_key_exists($key, $var)) ...

which is likely to be faster if the tests are mainly on non-null values. Otherwise for an array with mostly null values

if (isset($var) && is_array($var) && array_key_exists($key, $var)) ...

will do the work.

Combine or merge JSON on node.js without jQuery

You can also use this lightweight npm package called absorb

It is 27 lines of code, 1kb and uses recursion to perform deep object merges.

var absorb = require('absorb');
var obj1, obj2;

obj1 = { foo: 123, bar: 456 };
obj2 = { bar: 123, key: 'value' }

absorb(obj1, obj2);

console.log(obj1); // Output: { foo: 123, bar: 123, key: 'value' }

You can also use it to make a clone or only transfer values if they don't exist in the source object, how to do this is detailed in the link provided.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

C# declare empty string array

The following should work fine.

string[] arr = new string[] {""};

Using Eloquent ORM in Laravel to perform search of database using LIKE

If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:

public  function scopeLike($query, $field, $value){
        return $query->where($field, 'LIKE', "%$value%");
}

So then you can use this method in such way:

User::like('name', 'Tomas')->get();

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

How to compare 2 files fast using .NET?

The slowest possible method is to compare two files byte by byte. The fastest I've been able to come up with is a similar comparison, but instead of one byte at a time, you would use an array of bytes sized to Int64, and then compare the resulting numbers.

Here's what I came up with:

    const int BYTES_TO_READ = sizeof(Int64);

    static bool FilesAreEqual(FileInfo first, FileInfo second)
    {
        if (first.Length != second.Length)
            return false;

        if (string.Equals(first.FullName, second.FullName, StringComparison.OrdinalIgnoreCase))
            return true;

        int iterations = (int)Math.Ceiling((double)first.Length / BYTES_TO_READ);

        using (FileStream fs1 = first.OpenRead())
        using (FileStream fs2 = second.OpenRead())
        {
            byte[] one = new byte[BYTES_TO_READ];
            byte[] two = new byte[BYTES_TO_READ];

            for (int i = 0; i < iterations; i++)
            {
                 fs1.Read(one, 0, BYTES_TO_READ);
                 fs2.Read(two, 0, BYTES_TO_READ);

                if (BitConverter.ToInt64(one,0) != BitConverter.ToInt64(two,0))
                    return false;
            }
        }

        return true;
    }

In my testing, I was able to see this outperform a straightforward ReadByte() scenario by almost 3:1. Averaged over 1000 runs, I got this method at 1063ms, and the method below (straightforward byte by byte comparison) at 3031ms. Hashing always came back sub-second at around an average of 865ms. This testing was with an ~100MB video file.

Here's the ReadByte and hashing methods I used, for comparison purposes:

    static bool FilesAreEqual_OneByte(FileInfo first, FileInfo second)
    {
        if (first.Length != second.Length)
            return false;

        if (string.Equals(first.FullName, second.FullName, StringComparison.OrdinalIgnoreCase))
            return true;

        using (FileStream fs1 = first.OpenRead())
        using (FileStream fs2 = second.OpenRead())
        {
            for (int i = 0; i < first.Length; i++)
            {
                if (fs1.ReadByte() != fs2.ReadByte())
                    return false;
            }
        }

        return true;
    }

    static bool FilesAreEqual_Hash(FileInfo first, FileInfo second)
    {
        byte[] firstHash = MD5.Create().ComputeHash(first.OpenRead());
        byte[] secondHash = MD5.Create().ComputeHash(second.OpenRead());

        for (int i=0; i<firstHash.Length; i++)
        {
            if (firstHash[i] != secondHash[i])
                return false;
        }
        return true;
    }

How do I find out my root MySQL password?

For RHEL-mysql 5.5:

/etc/init.d/mysql stop

/etc/init.d/mysql start --skip-grant-tables

 mysql> UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
 mysql> FLUSH PRIVILEGES;
 mysql> exit;

mysql -uroot -pnewpwd

mysql>  

How to programmatically clear application data

The Simplest way to do this is

private void deleteAppData() {
         try {
        // clearing app data
        String packageName = getApplicationContext().getPackageName();
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("pm clear "+packageName);

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

This will clear the data and remove your app from memory. It is equivalent to clear data option under Settings --> Application Manager --> Your App --> Clear data.

This will remove the data completely as well as force close the app

Specified cast is not valid.. how to resolve this

If you are expecting double, decimal, float, integer why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).

instead of (double)value use decimal.Parse(value.ToString()) or Convert.ToDecimal(value)

Capitalize the first letter of string in AngularJs

{{ uppercase_expression | capitaliseFirst}} should work

window.location.href not working

Try this

`var url = "http://stackoverflow.com";    
$(location).attr('href',url);`

Or you can do something like this

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

and add a return false at the end of your function call

What is the difference between Document style and RPC style communication?

Can some body explain me the differences between a Document style and RPC style webservices?

There are two communication style models that are used to translate a WSDL binding to a SOAP message body. They are: Document & RPC

The advantage of using a Document style model is that you can structure the SOAP body any way you want it as long as the content of the SOAP message body is any arbitrary XML instance. The Document style is also referred to as Message-Oriented style.

However, with an RPC style model, the structure of the SOAP request body must contain both the operation name and the set of method parameters. The RPC style model assumes a specific structure to the XML instance contained in the message body.

Furthermore, there are two encoding use models that are used to translate a WSDL binding to a SOAP message. They are: literal, and encoded

When using a literal use model, the body contents should conform to a user-defined XML-schema(XSD) structure. The advantage is two-fold. For one, you can validate the message body with the user-defined XML-schema, moreover, you can also transform the message using a transformation language like XSLT.

With a (SOAP) encoded use model, the message has to use XSD datatypes, but the structure of the message need not conform to any user-defined XML schema. This makes it difficult to validate the message body or use XSLT based transformations on the message body.

The combination of the different style and use models give us four different ways to translate a WSDL binding to a SOAP message.

Document/literal
Document/encoded
RPC/literal
RPC/encoded

I would recommend that you read this article entitled Which style of WSDL should I use? by Russell Butek which has a nice discussion of the different style and use models to translate a WSDL binding to a SOAP message, and their relative strengths and weaknesses.

Once the artifacts are received, in both styles of communication, I invoke the method on the port. Now, this does not differ in RPC style and Document style. So what is the difference and where is that difference visible?

The place where you can find the difference is the "RESPONSE"!

RPC Style:

package com.sample;

import java.util.ArrayList;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.RPC)
public interface StockPrice { 

    public String getStockPrice(String stockName); 

    public ArrayList getStockPriceList(ArrayList stockNameList); 
}

The SOAP message for second operation will have empty output and will look like:

RPC Style Response:

<ns2:getStockPriceListResponse 
       xmlns:ns2="http://sample.com/">
    <return/>
</ns2:getStockPriceListResponse>
</S:Body>
</S:Envelope>

Document Style:

package com.sample;

import java.util.ArrayList;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.DOCUMENT)
public interface StockPrice {

    public String getStockPrice(String stockName);

    public ArrayList getStockPriceList(ArrayList stockNameList);
}

If we run the client for the above SEI, the output is:

123 [123, 456]

This output shows that ArrayList elements are getting exchanged between the web service and client. This change has been done only by the changing the style attribute of SOAPBinding annotation. The SOAP message for the second method with richer data type is shown below for reference:

Document Style Response:

<ns2:getStockPriceListResponse 
       xmlns:ns2="http://sample.com/">
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xsi:type="xs:string">123</return>
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xsi:type="xs:string">456</return>
</ns2:getStockPriceListResponse>
</S:Body>
</S:Envelope>

Conclusion

  • As you would have noticed in the two SOAP response messages that it is possible to validate the SOAP response message in case of DOCUMENT style but not in RPC style web services.
  • The basic disadvantage of using RPC style is that it doesn’t support richer data types and that of using Document style is that it brings some complexity in the form of XSD for defining the richer data types.
  • The choice of using one out of these depends upon the operation/method requirements and the expected clients.

Similarly, in what way SOAP over HTTP differ from XML over HTTP? After all SOAP is also XML document with SOAP namespace. So what is the difference here?

Why do we need a standard like SOAP? By exchanging XML documents over HTTP, two programs can exchange rich, structured information without the introduction of an additional standard such as SOAP to explicitly describe a message envelope format and a way to encode structured content.

SOAP provides a standard so that developers do not have to invent a custom XML message format for every service they want to make available. Given the signature of the service method to be invoked, the SOAP specification prescribes an unambiguous XML message format. Any developer familiar with the SOAP specification, working in any programming language, can formulate a correct SOAP XML request for a particular service and understand the response from the service by obtaining the following service details.

  • Service name
  • Method names implemented by the service
  • Method signature of each method
  • Address of the service implementation (expressed as a URI)

Using SOAP streamlines the process for exposing an existing software component as a Web service since the method signature of the service identifies the XML document structure used for both the request and the response.

How to use particular CSS styles based on screen size / device

Use @media queries. They serve this exact purpose. Here's an example how they work:

@media (max-width: 800px) {
  /* CSS that should be displayed if width is equal to or less than 800px goes here */
}

This would work only on devices whose width is equal to or less than 800px.

Read up more about media queries on the Mozilla Developer Network.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

In my case a has to add my classes, when building the SessionFactory, with addAnnotationClass

Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
            .addAnnotatedClass(MyEntity1.class)
            .addAnnotatedClass(MyEntity2.class)
            .buildSessionFactory(builder.build());

How do I convert a column of text URLs into active hyperlinks in Excel?

If you copy the text contents into a new column and use:

=HYPERLINK("http://"&B10,B10) 

on your original column. Then use the $ for the column so it looks like this:

=HYPERLINK("http://"&$B10,$B10)

That's the only way it worked for me on Excel 2010 on Windows 7. You can copy down the formula.

C# elegant way to check if a property's property is null

You're obviously looking for the Nullable Monad:

string result = new A().PropertyB.PropertyC.Value;

becomes

string result = from a in new A()
                from b in a.PropertyB
                from c in b.PropertyC
                select c.Value;

This returns null, if any of the nullable properties are null; otherwise, the value of Value.

class A { public B PropertyB { get; set; } }
class B { public C PropertyC { get; set; } }
class C { public string Value { get; set; } }

LINQ extension methods:

public static class NullableExtensions
{
    public static TResult SelectMany<TOuter, TInner, TResult>(
        this TOuter source,
        Func<TOuter, TInner> innerSelector,
        Func<TOuter, TInner, TResult> resultSelector)
        where TOuter : class
        where TInner : class
        where TResult : class
    {
        if (source == null) return null;
        TInner inner = innerSelector(source);
        if (inner == null) return null;
        return resultSelector(source, inner);
    }
}

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

ModuleNotFoundError: No module named 'sklearn'

SOLVED:

The above did not help. Then I simply installed sklearn from within Jypyter-lab, even though sklearn 0.0 shows in 'pip list':

!pip install sklearn
import sklearn

What I learned later is that pip installs, in my case, packages in a different folder than Jupyter. This can be seen by executing:

import sys
print(sys.path)

Once from within Jupyter_lab notebook, and once from the command line using 'py notebook.py'.

In my case Jupyter list of paths where subfolders of 'anaconda' whereas Python list where subfolders of c:\users[username]...

Select row with most recent date per user

select b.* from 

    (select 
        `lms_attendance`.`user` AS `user`,
        max(`lms_attendance`.`time`) AS `time`
    from `lms_attendance` 
    group by 
        `lms_attendance`.`user`) a

join

    (select * 
    from `lms_attendance` ) b

on a.user = b.user
and a.time = b.time

When should I use Lazy<T>?

You typically use it when you want to instantiate something the first time its actually used. This delays the cost of creating it till if/when it's needed instead of always incurring the cost.

Usually this is preferable when the object may or may not be used and the cost of constructing it is non-trivial.

SQL GROUP BY CASE statement with aggregate function

While Shannon's answer is technically correct, it looks like overkill.

The simple solution is that you need to put your summation outside of the case statement. This should do the trick:

sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product

Basically, your old code tells SQL to execute the sum(X*Y) for each line individually (leaving each line with its own answer that can't be grouped).

The code line I have written takes the sum product, which is what you want.

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

Wolfram has a closed form solution for fitting an exponential. They also have similar solutions for fitting a logarithmic and power law.

I found this to work better than scipy's curve_fit. Especially when you don't have data "near zero". Here is an example:

import numpy as np
import matplotlib.pyplot as plt

# Fit the function y = A * exp(B * x) to the data
# returns (A, B)
# From: https://mathworld.wolfram.com/LeastSquaresFittingExponential.html
def fit_exp(xs, ys):
    S_x2_y = 0.0
    S_y_lny = 0.0
    S_x_y = 0.0
    S_x_y_lny = 0.0
    S_y = 0.0
    for (x,y) in zip(xs, ys):
        S_x2_y += x * x * y
        S_y_lny += y * np.log(y)
        S_x_y += x * y
        S_x_y_lny += x * y * np.log(y)
        S_y += y
    #end
    a = (S_x2_y * S_y_lny - S_x_y * S_x_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
    b = (S_y * S_x_y_lny - S_x_y * S_y_lny) / (S_y * S_x2_y - S_x_y * S_x_y)
    return (np.exp(a), b)


xs = [33, 34, 35, 36, 37, 38, 39, 40, 41, 42]
ys = [3187, 3545, 4045, 4447, 4872, 5660, 5983, 6254, 6681, 7206]

(A, B) = fit_exp(xs, ys)

plt.figure()
plt.plot(xs, ys, 'o-', label='Raw Data')
plt.plot(xs, [A * np.exp(B *x) for x in xs], 'o-', label='Fit')

plt.title('Exponential Fit Test')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
plt.tight_layout()
plt.show()

enter image description here

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

clearInterval() not working

You're using clearInterval incorrectly.

This is the proper use:

Set the timer with

var_name = setInterval(fontChange, 500);

and then

clearInterval(var_name);

Get single row result with Doctrine NativeQuery

I use fetchObject() here a small example using Symfony 4.4

    <?php 
    use Doctrine\DBAL\Driver\Connection;

    class MyController{

    public function index($username){
      $queryBuilder = $connection->createQueryBuilder();
      $queryBuilder
        ->select('id', 'name')
        ->from('app_user')
        ->where('name = ?')
        ->setParameter(0, $username)
        ->setMaxResults(1);
      $stmUser = $queryBuilder->execute();

      dump($stmUser->fetchObject());

      //get_class_methods($stmUser) -> to see all methods
    }
  }

Response:

{ 
"id": "2", "name":"myuser"
}

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Below is a workaround demo image of ; Uncheck Offline work option by going to:

File -> Settings -> Build, Execution, Deployment -> Gradle

enter image description here

If above workaround not works then try this:

  1. Open the build.gradle file for your application.

  2. Make sure that the repositories section includes a maven section with the "https://maven.google.com" endpoint. For example:

    allprojects {
         repositories {
             jcenter()
             maven {
                 url "https://maven.google.com"
             }
         }
    }
    
  3. Add the support library to the dependencies section. For example, to add the v4 core-utils library, add the following lines:

    dependencies {
        ...
        compile "com.android.support:support-core-utils:27.1.0"
    }
    

Caution: Using dynamic dependencies (for example, palette-v7:23.0.+) can cause unexpected version updates and regression incompatibilities. We recommend that you explicitly specify a library version (for example, palette-v7:27.1.0).

Manifest Declaration Changes

Specifically, you should update the android:minSdkVersion element of the <uses-sdk> tag in the manifest to the new, lower version number, as shown below:

<uses-sdk
  android:minSdkVersion="14"
  android:targetSdkVersion="23" />

If you are using Gradle build files, the minSdkVersion setting in the build file overrides the manifest settings.

apply plugin: 'com.android.application'

android {
   ...
      defaultConfig {
            minSdkVersion 16
            ...
        }
        ...
    }

Following Android Developer Library Support.

Align text in JLabel to the right

JLabel label = new JLabel("fax", SwingConstants.RIGHT);

How to create a connection string in asp.net c#

string connectionstring="DataSource=severname;InitialCatlog=databasename;Uid=; password=;"
SqlConnection con=new SqlConnection(connectionstring)

How do I add more members to my ENUM-type column in MySQL?

ALTER TABLE
    `table_name`
MODIFY COLUMN
    `column_name2` enum(
        'existing_value1',
        'existing_value2',
        'new_value1',
        'new_value2'
    )
NOT NULL AFTER `column_name1`;

How to wait until WebBrowser is completely loaded in VB.NET?

Hold on...

From my experience, you SHOULD make sure that the DocumCompleted belongs to YOUR URL and not to a frame sub-page, script, image, CSS, etc. And that is regardless of the IsBusy or the ReadyState is finished or not, which both are often inaccurate when page is slightly complex.

Well, that is my own personal experience, on a working program of VB.2013 and IE11. Let me also mention that you should take into account also the compatibility mode IE7 which is ON by default at the webBrowser1.

' Page, sub-frame or resource was totally loaded.
Private Sub webBrowser1_DocumentCompleted(sender As Object, _ 
    e As WebBrowserDocumentCompletedEventArgs) _ 
    Handles webBrowser1.DocumentCompleted

    ' Check if finally the full page was loaded (inc. sub-frames, javascripts, etc)
    If e.Url.ToString = webBrowser1.Url.ToString Then
        ' Only now you are sure!
        fullyLoaded = True
    End If

End Sub

Return a string method in C#

You don't have to have a method for that. You could create a property like this instead:

class SalesPerson
{
    string firstName, lastName;
    public string FirstName { get { return firstName; } set { firstName = value; } }
    public string LastName { get { return lastName; } set { lastName = value; } }
    public string FullName { get { return this.FirstName + " " + this.LastName; } }
}

The class could even be shortened to:

class SalesPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { 
       get { return this.FirstName + " " + this.LastName; } 
    }
}

The property could then be accessed like any other property:

class Program
{
    static void Main(string[] args)
    {
        SalesPerson x = new SalesPerson("John", "Doe");
        Console.WriteLine(x.FullName); // Will print John Doe
    }
}

Get attribute name value of <input>

using value get input name

 $('input[value="1"]').attr('name');

using id get input name

 $('input[class="id"]').attr('name');
   $('#id').attr('name');

using class get input name

 $('input[value="classname"]').attr('name');
   $('.classname').attr('name');  //if classname have unique value

Certificate is trusted by PC but not by Android

I had the same issue and my issue was the device not having the right date and time. Once I fixed that the certificate is being trusted.

Pretty print in MongoDB shell as default

Oh so i guess .pretty() is equal to:

db.collection.find().forEach(printjson);

How to set a hidden value in Razor

While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.

@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)

Responsive Images with CSS

check the images first with php if it is small then the standerd size for logo provide it any other css class and dont change its size

i think you have to take up scripting in between

Differences between ConstraintLayout and RelativeLayout

Officially, ConstraintLayout is much faster

In the N release of Android, the ConstraintLayout class provides similar functionality to RelativeLayout, but at a significantly lower cost.

What are all possible pos tags of NLTK?

To save some folks some time, here is a list I extracted from a small corpus. I do not know if it is complete, but it should have most (if not all) of the help definitions from upenn_tagset...

CC: conjunction, coordinating

& 'n and both but either et for less minus neither nor or plus so
therefore times v. versus vs. whether yet

CD: numeral, cardinal

mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-
seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025
fifteen 271,124 dozen quintillion DM2,000 ...

DT: determiner

all an another any both del each either every half la many much nary
neither no some such that the them these this those

EX: existential there

there

IN: preposition or conjunction, subordinating

astride among uppon whether out inside pro despite on by throughout
below within for towards near behind atop around if like until below
next into if beside ...

JJ: adjective or numeral, ordinal

third ill-mannered pre-war regrettable oiled calamitous first separable
ectoplasmic battery-powered participatory fourth still-to-be-named
multilingual multi-disciplinary ...

JJR: adjective, comparative

bleaker braver breezier briefer brighter brisker broader bumper busier
calmer cheaper choosier cleaner clearer closer colder commoner costlier
cozier creamier crunchier cuter ...

JJS: adjective, superlative

calmest cheapest choicest classiest cleanest clearest closest commonest
corniest costliest crassest creepiest crudest cutest darkest deadliest
dearest deepest densest dinkiest ...

LS: list item marker

A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005
SP-44007 Second Third Three Two * a b c d first five four one six three
two

MD: modal auxiliary

can cannot could couldn't dare may might must need ought shall should
shouldn't will would

NN: noun, common, singular or mass

common-carrier cabbage knuckle-duster Casino afghan shed thermostat
investment slide humour falloff slick wind hyena override subhumanity
machinist ...

NNP: noun, proper, singular

Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos
Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA
Shannon A.K.C. Meltex Liverpool ...

NNS: noun, common, plural

undergraduates scotches bric-a-brac products bodyguards facets coasts
divestitures storehouses designs clubs fragrances averages
subjectivists apprehensions muses factory-jobs ...

PDT: pre-determiner

all both half many quite such sure this

POS: genitive marker

' 's

PRP: pronoun, personal

hers herself him himself hisself it itself me myself one oneself ours
ourselves ownself self she thee theirs them themselves they thou thy us

PRP$: pronoun, possessive

her his mine my our ours their thy your

RB: adverb

occasionally unabatingly maddeningly adventurously professedly
stirringly prominently technologically magisterially predominately
swiftly fiscally pitilessly ...

RBR: adverb, comparative

further gloomier grander graver greater grimmer harder harsher
healthier heavier higher however larger later leaner lengthier less-
perfectly lesser lonelier longer louder lower more ...

RBS: adverb, superlative

best biggest bluntest earliest farthest first furthest hardest
heartiest highest largest least less most nearest second tightest worst

RP: particle

aboard about across along apart around aside at away back before behind
by crop down ever fast for forth from go high i.e. in into just later
low more off on open out over per pie raising start teeth that through
under unto up up-pp upon whole with you

TO: "to" as preposition or infinitive marker

to

UH: interjection

Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen
huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly
man baby diddle hush sonuvabitch ...

VB: verb, base form

ask assemble assess assign assume atone attention avoid bake balkanize
bank begin behold believe bend benefit bevel beware bless boil bomb
boost brace break bring broil brush build ...

VBD: verb, past tense

dipped pleaded swiped regummed soaked tidied convened halted registered
cushioned exacted snubbed strode aimed adopted belied figgered
speculated wore appreciated contemplated ...

VBG: verb, present participle or gerund

telegraphing stirring focusing angering judging stalling lactating
hankerin' alleging veering capping approaching traveling besieging
encrypting interrupting erasing wincing ...

VBN: verb, past participle

multihulled dilapidated aerosolized chaired languished panelized used
experimented flourished imitated reunifed factored condensed sheared
unsettled primed dubbed desired ...

VBP: verb, present tense, not 3rd person singular

predominate wrap resort sue twist spill cure lengthen brush terminate
appear tend stray glisten obtain comprise detest tease attract
emphasize mold postpone sever return wag ...

VBZ: verb, present tense, 3rd person singular

bases reconstructs marks mixes displeases seals carps weaves snatches
slumps stretches authorizes smolders pictures emerges stockpiles
seduces fizzes uses bolsters slaps speaks pleads ...

WDT: WH-determiner

that what whatever which whichever

WP: WH-pronoun

that what whatever whatsoever which who whom whosoever

WRB: Wh-adverb

how however whence whenever where whereby whereever wherein whereof why

Command not found when using sudo

The other solutions I've seen here so far are based on some system definitions, but it's in fact possible to have sudo use the current PATH (with the env command) and/or the rest of the environment (with the -E option) just by invoking it right:

sudo -E env "PATH=$PATH" <command> [arguments]

In fact, one can make an alias out of it:

alias mysudo='sudo -E env "PATH=$PATH"'

(It's also possible to name the alias itself sudo, replacing the original sudo.)

Using Python's os.path, how do I go up one directory?

For a paranoid like me, I'd prefer this one

TEMPLATE_DIRS = (
    __file__.rsplit('/', 2)[0] + '/templates',
)

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

Foreign key referencing a 2 columns primary key in SQL Server

The Content table likely to have multiple duplicate Application values that can't be mapped to Libraries. Is it possible to drop the Application column from the Libraries Primary Key Index and add it as a Unique Key Index instead?

C# DateTime to "YYYYMMDDHHMMSS" format

Specify formatted DateTime as Utc:

Step 1 - Initial date

var initialDtm = DateTime.Now;

Step 2 - Format date as willing ("yyyyMMddHHmmss")

var formattedDtm = DateTime.ParseExact(initialDtm.ToString("yyyyMMddHHmmss"), "yyyyMMddHHmmss", CultureInfo.InvariantCulture);    

Step 3 - Specify kind of date (Utc)

var specifiedDtm = DateTime.SpecifyKind( formattedDtm, DateTimeKind.Utc);

How do I get my C# program to sleep for 50 msec?

Thread.Sleep(50);

The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.

This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.

Thread.Join

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

Access the database as a user administrator (root user maybe). Check the right one user privileges to the database.

mysql >SHOW GRANTS FOR <username>;

Assign full user privileges to the database from localhost

mysql> GRANT ALL PRIVILEGES ON <databasename>.* TO '<username>'@'localhost' IDENTIFIED BY '<password>';
mysql> FLUSH PRIVILEGES;

in case of error in connecting to the database from third-party programs, for example MySQL WORKBENCH, assign privileges to the user to the database from any host MYSQL Grant all privileges to database from any host

mysql> GRANT ALL PRIVILEGES ON <databasename>.* TO '<username>'@'%' IDENTIFIED BY '<password>';
mysql> FLUSH PRIVILEGES;

Which @NotNull Java annotation should I use?

I very much like the Checker Framework, which is an implementation of type annotations (JSR-308) which is used to implement defect checkers like a nullness checker. I haven't really tried any others to offer any comparison, but I've been happy with this implementation.

I'm not affiliated with the group that offers the software, but I am a fan.

Four things I like about this system:

  1. It has a defect checkers for nullness (@Nullable), but also has ones for immutability and interning (and others). I use the first one (nullness) and I'm trying to get into using the second one (immutability/IGJ). I'm trying out the third one, but I'm not certain about using it long term yet. I'm not convinced of the general usefulness of the other checkers yet, but its nice to know that the framework itself is a system for implementing a variety of additional annotations and checkers.

  2. The default setting for nullness checking works well: Non-null except locals (NNEL). Basically this means that by default the checker treats everyhing (instance variables, method parameters, generic types, etc) except local variables as if they have a @NonNull type by default. Per the documentation:

    The NNEL default leads to the smallest number of explicit annotations in your code.

    You can set a different default for a class or for a method if NNEL doesn't work for you.

  3. This framework allows you to use with without creating a dependency on the framework by enclosing your annotations in a comment: e.g. /*@Nullable*/. This is nice because you can annotate and check a library or shared code, but still be able to use that library/shared coded in another project that doesn't use the framework. This is a nice feature. I've grown accustom to using it, even though I tend to enable the Checker Framework on all my projects now.

  4. The framework has a way to annotate APIs you use that aren't already annotated for nullness by using stub files.

Convert an image (selected by path) to base64 string

You can use Server.Map path to give relative path and then you can either create image using base64 conversion or you can just add base64 string to image src.

byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));

string base64ImageRepresentation = Convert.ToBase64String(imageArray);

How can I have two fixed width columns with one flexible column in the center?

Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks.

An initial setting of a flex container is flex-shrink: 1. That's why your columns are shrinking.

It doesn't matter what width you specify (it could be width: 10000px), with flex-shrink the specified width can be ignored and flex items are prevented from overflowing the container.

I'm trying to set up a flexbox with 3 columns where the left and right columns have a fixed width...

You will need to disable shrinking. Here are some options:

.left, .right {
     width: 230px;
     flex-shrink: 0;
 }  

OR

.left, .right {
     flex-basis: 230px;
     flex-shrink: 0;
}

OR, as recommended by the spec:

.left, .right {
    flex: 0 0 230px;    /* don't grow, don't shrink, stay fixed at 230px */
}

7.2. Components of Flexibility

Authors are encouraged to control flexibility using the flex shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.

More details here: What are the differences between flex-basis and width?

An additional thing I need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space.

Try this:

.center { flex: 1; }

This will allow the center column to consume available space, including the space of its siblings when they are removed.

Revised Fiddle

Spring Security redirect to previous page after successful login

What happens after login (to which url the user is redirected) is handled by the AuthenticationSuccessHandler.

This interface (a concrete class implementing it is SavedRequestAwareAuthenticationSuccessHandler) is invoked by the AbstractAuthenticationProcessingFilter or one of its subclasses like (UsernamePasswordAuthenticationFilter) in the method successfulAuthentication.

So in order to have an other redirect in case 3 you have to subclass SavedRequestAwareAuthenticationSuccessHandler and make it to do what you want.


Sometimes (depending on your exact usecase) it is enough to enable the useReferer flag of AbstractAuthenticationTargetUrlRequestHandler which is invoked by SimpleUrlAuthenticationSuccessHandler (super class of SavedRequestAwareAuthenticationSuccessHandler).

<bean id="authenticationFilter"
      class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <property name="filterProcessesUrl" value="/login/j_spring_security_check" />
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler">
        <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
            <property name="useReferer" value="true"/>
        </bean>
    </property>
    <property name="authenticationFailureHandler">
        <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
            <property name="defaultFailureUrl" value="/login?login_error=t" />
        </bean>
    </property>
</bean>

Is there a better way to run a command N times in bash?

A simple function in the bash config file (~/.bashrc often) could work well.

function runx() {
  for ((n=0;n<$1;n++))
    do ${*:2}
  done
}

Call it like this.

$ runx 3 echo 'Hello world'
Hello world
Hello world
Hello world

Rename a table in MySQL

Rename a table in MySQL :

ALTER TABLE current_name RENAME new_name;

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

Python Save to file

You can use this function:

def saveListToFile(listname, pathtosave):
    file1 = open(pathtosave,"w") 
    for i in listname:
        file1.writelines("{}\n".format(i))    
    file1.close() 

# to save:
saveListToFile(list, path)

Numpy: find index of the elements within range

Summary of the answers

For understanding what is the best answer we can do some timing using the different solution. Unfortunately, the question was not well-posed so there are answers to different questions, here I try to point the answer to the same question. Given the array:

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])

The answer should be the indexes of the elements between a certain range, we assume inclusive, in this case, 6 and 10.

answer = (3, 4, 5)

Corresponding to the values 6,9,10.

To test the best answer we can use this code.

import timeit
setup = """
import numpy as np
import numexpr as ne

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
# we define the left and right limit
ll = 6
rl = 10

def sorted_slice(a,l,r):
    start = np.searchsorted(a, l, 'left')
    end = np.searchsorted(a, r, 'right')
    return np.arange(start,end)
"""

functions = ['sorted_slice(a,ll,rl)', # works only for sorted values
'np.where(np.logical_and(a>=ll, a<=rl))[0]',
'np.where((a >= ll) & (a <=rl))[0]',
'np.where((a>=ll)*(a<=rl))[0]',
'np.where(np.vectorize(lambda x: ll <= x <= rl)(a))[0]',
'np.argwhere((a>=ll) & (a<=rl)).T[0]', # we traspose for getting a single row
'np.where(ne.evaluate("(ll <= a) & (a <= rl)"))[0]',]

functions2 = [
   'a[np.logical_and(a>=ll, a<=rl)]',
   'a[(a>=ll) & (a<=rl)]',
   'a[(a>=ll)*(a<=rl)]',
   'a[np.vectorize(lambda x: ll <= x <= rl)(a)]',
   'a[ne.evaluate("(ll <= a) & (a <= rl)")]',
]

Results

The results are reported in the following plot. On the top the fastest solutions. enter image description here If instead of the indexes you want to extract the values you can perform the tests using functions2 but the results are almost the same.

This IP, site or mobile application is not authorized to use this API key

Disable both direction api and geocoding api and re-enable.

it works for only 5-10 seconds and than automatically disabled itself.

it means you have only 5-10 sec to test you assignment.

Single Page Application: advantages and disadvantages

In my development I found two distinct advantages for using an SPA. That is not to say that the following can not be achieved in a traditional web app just that I see incremental benefit without introducing additional disadvantages.

  • Potential for less server request as rendering new content isn’t always or even ever an http server request for a new html page. But I say potential because new content could easily require an Ajax call to pull in data but that data could be incrementally lighter than the itself plus markup providing a net benefit.

  • The ability to maintain “State”. In its simplest terms, set a variable on entry to the app and it will be available to other components throughout the user’s experience without passing it around or setting it to a local storage pattern. Intelligently managing this ability however is key to keep the top level scope uncluttered.

Other than requiring JS (which is not a crazy thing to require of web apps) other noted disadvantages are in my opinion either not specific to SPA or can be mitigated through good habits and development patterns.

how do you pass images (bitmaps) between android activities using bundles?

Activity

To pass a bitmap between Activites

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

And in the Activity class

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

Fragment

To pass a bitmap between Fragments

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

To receive inside the SecondFragment

Bitmap bitmap = getArguments().getParcelable("bitmap");

Transferring large bitmap (Compress bitmap)

If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.

So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this

In the FirstActivity

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

And in the SecondActivity

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

Update some specific field of an entity in android Room

I think you don't need to update only some specific field. Just update whole data.

@Update query

It is a given query basically. No need to make some new query.

@Dao
interface MemoDao {

    @Insert
    suspend fun insert(memo: Memo)

    @Delete
    suspend fun delete(memo: Memo)

    @Update
    suspend fun update(memo: Memo)
}

Memo.class

@Entity
data class Memo (
    @PrimaryKey(autoGenerate = true) val id: Int,
    @ColumnInfo(name = "title") val title: String?,
    @ColumnInfo(name = "content") val content: String?,
    @ColumnInfo(name = "photo") val photo: List<ByteArray>?
)

Only thing you need to know is 'id'. For instance, if you want to update only 'title', you can reuse 'content' and 'photo' from already inserted data. In real code, use like this

val memo = Memo(id, title, content, byteArrayList)
memoViewModel.update(memo)

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

Terminating a script in PowerShell

I realize this is an old post but I find myself coming back to this thread a lot as it is one of the top search results when searching for this topic. However, I always leave more confused then when I came due to the conflicting information. Ultimately I always have to perform my own tests to figure it out. So this time I will post my findings.

TL;DR Most people will want to use Exit to terminate a running scripts. However, if your script is merely declaring functions to later be used in a shell, then you will want to use Return in the definitions of said functions.

Exit vs Return vs Break

  • Exit: This will "exit" the currently running context. If you call this command from a script it will exit the script. If you call this command from the shell it will exit the shell.

    If a function calls the Exit command it will exit what ever context it is running in. So if that function is only called from within a running script it will exit that script. However, if your script merely declares the function so that it can be used from the current shell and you run that function from the shell, it will exit the shell because the shell is the context in which the function contianing the Exit command is running.

    Note: By default if you right click on a script to run it in PowerShell, once the script is done running, PowerShell will close automatically. This has nothing to do with the Exit command or anything else in your script. It is just a default PowerShell behavior for scripts being ran using this specific method of running a script. The same is true for batch files and the Command Line window.

  • Return: This will return to the previous call point. If you call this command from a script (outside any functions) it will return to the shell. If you call this command from the shell it will return to the shell (which is the previous call point for a single command ran from the shell). If you call this command from a function it will return to where ever the function was called from.

    Execution of any commands after the call point that it is returned to will continue from that point. If a script is called from the shell and it contains the Return command outside any functions then when it returns to the shell there are no more commands to run thus making a Return used in this way essentially the same as Exit.

  • Break: This will break out of loops and switch cases. If you call this command while not in a loop or switch case it will break out of the script. If you call Break inside a loop that is nested inside a loop it will only break out of the loop it was called in.

    There is also an interesting feature of Break where you can prefix a loop with a label and then you can break out of that labeled loop even if the Break command is called within several nested groups within that labeled loop.

    While ($true) {
        # Code here will run
    
        :myLabel While ($true) {
            # Code here will run
    
            While ($true) {
                # Code here will run
    
                While ($true) {
                    # Code here will run
                    Break myLabel
                    # Code here will not run
                }
    
                # Code here will not run
            }
    
            # Code here will not run
        }
    
        # Code here will run
    }
    

How to make all controls resize accordingly proportionally when window is maximized?

Just thought i'd share this with anyone who needs more clarity on how to achieve this:

myCanvas is a Canvas control and Parent to all other controllers. This code works to neatly resize to any resolution from 1366 x 768 upward. Tested up to 4k resolution 4096 x 2160

Take note of all the MainWindow property settings (WindowStartupLocation, SizeToContent and WindowState) - important for this to work correctly - WindowState for my user case requirement was Maximized

xaml

<Window x:Name="mainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApp" 
    xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="MyApp.MainWindow" 
     Title="MainWindow"  SizeChanged="MainWindow_SizeChanged"
    Width="1366" Height="768" WindowState="Maximized" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
  
    <Canvas x:Name="myCanvas" HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="1356">
        <Image x:Name="maxresdefault_1_1__jpg" Source="maxresdefault-1[1].jpg" Stretch="Fill" Opacity="0.6" Height="767" Canvas.Left="-6" Width="1366"/>

        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" Height="0" Canvas.Left="-811" Canvas.Top="148" Width="766"/>
        <Separator Margin="0" Background="#FF302D2D" Foreground="#FF111010" HorizontalAlignment="Right" Width="210" Height="0" Canvas.Left="1653" Canvas.Top="102"/>
        <Image x:Name="imgscroll" Source="BcaKKb47i[1].png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" Height="523" Canvas.Left="-3" Canvas.Top="122" Width="580">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="89.093"/>
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>

.cs

 private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        myCanvas.Width = e.NewSize.Width;
        myCanvas.Height = e.NewSize.Height;

        double xChange = 1, yChange = 1;

        if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width / e.PreviousSize.Width);

        if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

        ScaleTransform scale = new ScaleTransform(myCanvas.LayoutTransform.Value.M11 * xChange, myCanvas.LayoutTransform.Value.M22 * yChange);
        myCanvas.LayoutTransform = scale;
        myCanvas.UpdateLayout();
    }

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Running these commands solved my problem (credit to this answer):

import django
django.setup()

However I'm not sure why I need this. Comments would be appreciated.

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

select top(3) min(Name),TotalSalary,ROW_NUMBER() OVER (Order by TotalSalary desc) AS RowNumber FROM tbl_EmployeeProfile group by TotalSalary

Add new column with foreign key constraint in one command

In Oracle :

ALTER TABLE one ADD two_id INTEGER CONSTRAINT Fk_two_id REFERENCES two(id);

Check if EditText is empty.

use TextUtils.isEmpty("Text here"); for single line code

Clearing input in vuejs form

I use this

this.$refs['refFormName'].resetFields();

this work fine for me.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

With Nodejs, if you are using routers, make sure to add cors before the routers. Otherwise, you'll still get the cors error. Like below:

const cors = require('cors');

const userRouter = require('./routers/user');

expressApp = express();
expressApp.use(cors());
expressApp.use(express.json());
expressApp.use(userRouter);

How to generate UML diagrams (especially sequence diagrams) from Java code?

I am one of the authors, so the answer can be biased. It is open-source (Apache 2.0), but the plugin is not free. You don't have to pay (obviously) if you clone and build it locally.

On Intellij IDEA, ZenUML can generate sequence diagram from Java code. enter image description here

Check it out at https://plugins.jetbrains.com/plugin/12437-zenuml-support

Source code: https://github.com/ZenUml/jetbrains-zenuml

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I had a similar issues fresh install and same error surprising. Finally I figured out it was a problem with browser cookies...

  1. Try cleaning your browser cookies and see it helps to resolve this issue, before even trying any configuration changes.

  2. Try using XAMPP Control panel "Admin" button instead of usual http://localhost or http://localhost/phpmyadmin

  3. Try direct link: http://localhost/phpmyadmin/main.php or http://127.0.0.1/phpmyadmin/main.php

  4. Finally try this: http://localhost/phpmyadmin/index.php?db=phpmyadmin&server=1&target=db_structure.php

Somehow if you have old installation and you upgraded to new version it keeps track of your old settings through cookies.

If this solution helped let me know.

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

How to store a list in a column of a database table

Many SQL databases allow a table to contain a subtable as a component. The usual method is to allow the domain of one of the columns to be a table. This is in addition to using some convention like CSV to encode the substructure in ways unknown to the DBMS.

When Ed Codd was developing the relational model in 1969-1970, he specifically defined a normal form that would disallow this kind of nesting of tables. Normal form was later called First Normal Form. He then went on to show that for every database, there is a database in first normal form that expresses the same information.

Why bother with this? Well, databases in first normal form permit keyed access to all data. If you provide a table name, a key value into that table, and a column name, the database will contain at most one cell containing one item of data.

If you allow a cell to contain a list or a table or any other collection, now you can't provide keyed access to the sub items, without completely reworking the idea of a key.

Keyed access to all data is fundamental to the relational model. Without this concept, the model isn't relational. As to why the relational model is a good idea, and what might be the limitations of that good idea, you have to look at the 50 years worth of accumulated experience with the relational model.

TSQL How do you output PRINT in a user defined function?

No, you can not.

You can call a function from a stored procedure and debug a stored procedure (this will step into the function)

Python string prints as [u'String']

Maybe i dont understand , why cant you just get the element.text and then convert it before using it ? for instance (dont know why you would do this but...) find all label elements of the web page and iterate between them until you find one called MyText

        avail = []
        avail = driver.find_elements_by_class_name("label");
        for i in avail:
                if  i.text == "MyText":

Convert the string from i and do whatever you wanted to do ... maybe im missing something in the original message ? or was this what you were looking for ?

How do you round a float to 2 decimal places in JRuby?

sprintf('%.2f', number) is a cryptic, but very powerful way of formatting numbers. The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf can format any number almost any way you like, and lots more.

Full sprintf documentation: http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

Run a JAR file from the command line and specify classpath

You can do these in unix shell:

java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

You can do these in windows powershell:

java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main

How to group time by hour or by 10 minutes

The original answer the author gave works pretty well. Just to extend this idea, you can do something like

group by datediff(minute, 0, [Date])/10

which will allow you to group by a longer period then 60 minutes, say 720, which is half a day etc.

Modal width (increase)

If you use Sass,

according to the documentation you can customize your default values.

In your case, you can easily override the variable named $modal-lg in your _custom.scss file.

Can I delete a git commit but keep the changes?

In some case, I want only to undo the changes on specific files on the first commit to add them to a second commit and have a cleaner git log.

In this case, what I do is the following:

git checkout HEAD~1 <path_to_file_to_put_in_different_commit>
git add -u
git commit --amend --no-edit
git checkout HEAD@{1} <path_to_file_to_put_in_different_commit>
git commit -m "This is the new commit"

Of course, this works well even in the middle of a rebase -i with an edit option on the commit to split.

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

Laravel 5 route not defined, while it is?

when you execute the command

php artisan route:list

You will see all your registered routes in there in table format . Well there you see many columns like Method , URI , Name , Action .. etc.

So basically if you are using route() method that means it will accept only name column values and if you want to use URI column values you should go with url() method of laravel.

In MySQL, can I copy one row to insert into the same table?

This is an additional solution to the answer by "Grim..." There have been some comments on it having a primary key as null. Some comments about it not working. And some comments on solutions. None of the solutions worked for us. We have MariaDB with the InnoDB table.

We could not set the primary key to allow null. Using 0 instead of NULL led to duplicate value error for the primary key. SET SQL_SAFE_UPDATES = 0; Did not work either.

The solution from "Grim..." did work IF we changed our PRIMARY KEY to UNIQUE instead

Unix shell script find out which directory the script file resides?

In Bash, you should get what you need like this:

#!/usr/bin/env bash

BASEDIR=$(dirname "$0")
echo "$BASEDIR"

How to maintain a Unique List in Java?

I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?

If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.

Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.

Unicode character for "X" cancel / close?

× &#215; or &times; (same thing) U+00D7 multiplication sign

× same character with a strong font weight


? &#10799; U+2A2F Gibbs product


? &#10006; U+2716 heavy multiplication sign


There's also an emoji ❌ if you support it. If you don't you just saw a square = &#10060;


I also made this simple code example on Codepen when I was working with a designer who asked me to show her what it would look like when I asked if I could replace your close button with a coded version rather than an image.

<ul>
  <li class="ele">
    <div class="x large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop large"><b></b><b></b><b></b><b></b></div>
    <div class="x t large"><b></b><b></b><b></b><b></b></div>
    <div class="x shift large"><b></b><b></b><b></b><b></b></div>
  </li>
  <li class="ele">
    <div class="x medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop medium"><b></b><b></b><b></b><b></b></div>
    <div class="x t medium"><b></b><b></b><b></b><b></b></div>
    <div class="x shift medium"><b></b><b></b><b></b><b></b></div>

  </li>
  <li class="ele">
    <div class="x small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop small"><b></b><b></b><b></b><b></b></div>
    <div class="x t small"><b></b><b></b><b></b><b></b></div>
    <div class="x shift small"><b></b><b></b><b></b><b></b></div>
    <div class="x small grow"><b></b><b></b><b></b><b></b></div>

  </li>
  <li class="ele">
    <div class="x switch"><b></b><b></b><b></b><b></b></div>
  </li>
</ul>

jQuery click events firing multiple times

Try that way:

<a href="javascript:void(0)" onclick="this.onclick = false; fireThisFunctionOnlyOnce()"> Fire function </a>

How do I use CSS with a ruby on rails application?

I did the following...

  1. place your css file in the app/assets/stylesheets folder.
  2. Add the stylesheet link <%= stylesheet_link_tag "filename" %> in your default layouts file (most likely application.html.erb)

I recommend this over using your public folder. You can also reference the stylesheet inline, such as in your index page.

What is a "thread" (really)?

A thread is an execution context, which is all the information a CPU needs to execute a stream of instructions.

Suppose you're reading a book, and you want to take a break right now, but you want to be able to come back and resume reading from the exact point where you stopped. One way to achieve that is by jotting down the page number, line number, and word number. So your execution context for reading a book is these 3 numbers.

If you have a roommate, and she's using the same technique, she can take the book while you're not using it, and resume reading from where she stopped. Then you can take it back, and resume it from where you were.

Threads work in the same way. A CPU is giving you the illusion that it's doing multiple computations at the same time. It does that by spending a bit of time on each computation. It can do that because it has an execution context for each computation. Just like you can share a book with your friend, many tasks can share a CPU.

On a more technical level, an execution context (therefore a thread) consists of the values of the CPU's registers.

Last: threads are different from processes. A thread is a context of execution, while a process is a bunch of resources associated with a computation. A process can have one or many threads.

Clarification: the resources associated with a process include memory pages (all the threads in a process have the same view of the memory), file descriptors (e.g., open sockets), and security credentials (e.g., the ID of the user who started the process).

Best way to do a split pane in HTML

One totally different approach is to put things in a grid, such as ui-grid or Kendo's grid, and have the columns be resizable. A downside is that users would not be able to resize the rows, though the row size could be set programmatically.

Using OpenSSL what does "unable to write 'random state'" mean?

I know this question is on Linux, but on windows I had the same issue. Turns out you have to start the command prompt in "Run As Administrator" mode for it to work. Otherwise you get the same: unable to write 'random state' error.

adding onclick event to dynamically added button?

This code work good to me and look more simple. Necessary to call a function with specific parameter.

var btn = document.createElement("BUTTON");  //<button> element
var t = document.createTextNode("MyButton"); // Create a text node
btn.appendChild(t);   

btn.onclick = function(){myFunction(myparameter)};  
document.getElementById("myView").appendChild(btn);//to show on myView

HTML Submit-button: Different value / button-text?

Following the @greg0ire suggestion in comments:

<input type="submit" name="add_tag" value="Lägg till tag" />

In your server side, you'll do something like:

if (request.getParameter("add_tag") != null)
    tags.addTag( /*...*/ );

(Since I don't know that language (java?), there may be syntax errors.)

I would prefer the <button> solution, but it doesn't work as expected on IE < 9.

Expanding a parent <div> to the height of its children

Where We’re Starting From

Here’s some boilerplate HTML and CSS. In our example, we have a parent element with two floated child elements.

_x000D_
_x000D_
/* The CSS you're starting with may look similar to this._x000D_
 * This doesn't solve our problem yet, but we'll get there shortly._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
<!-- The HTML you're starting with might look similar to this -->_x000D_
<div class="containing-div">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Solution #1: overflow: auto

A solution that works in all modern browsers and in Internet Explorer back to IE8 is to add overflow: auto to the parent element. This also works in IE7, with scrollbars added.

_x000D_
_x000D_
/* Our Modified CSS._x000D_
 * This is one way we can solve our problem._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
  overflow: auto;_x000D_
  /*This is what we added!*/_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
_x000D_
_x000D_

Solution #2: Float Parent Container

Another solution that works in all modern browsers and back to IE7 is to float the parent container.

This may not always be practical, because floating your parent div may affect other parts of your page layout.

_x000D_
_x000D_
/* Modified CSS #2._x000D_
 * Floating parent div._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  float: left;_x000D_
  /*Added*/_x000D_
  height: auto;_x000D_
  width: 100%;_x000D_
  /*Added*/_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}
_x000D_
_x000D_
_x000D_

Method #3: Add Clearing Div Below Floated Elements

_x000D_
_x000D_
/* _x000D_
 * CSS to Solution #3._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
_x000D_
/*Added*/_x000D_
_x000D_
.clear {_x000D_
  clear: both;_x000D_
}
_x000D_
<!-- Solution 3, Add a clearing div to bottom of parent element -->_x000D_
<div class="containing-div">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Method #4: Add Clearing Div To The Parent Element This solution is pretty bulletproof for older browsers and newer browsers alike.

_x000D_
_x000D_
/* _x000D_
 * CSS to Solution #4._x000D_
 */_x000D_
_x000D_
.containing-div {_x000D_
  background-color: #d2b48c;_x000D_
  display: block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.floating-div {_x000D_
  float: left;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.floating-div ul {_x000D_
  display: inline-block;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
_x000D_
/*Added*/_x000D_
_x000D_
.clearfix {_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.clearfix:after {_x000D_
  clear: both;_x000D_
  content: "";_x000D_
  display: table;_x000D_
}
_x000D_
<!-- Solution 4, make parent element self-clearing -->_x000D_
<div class="containing-div clearfix">_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item One</li>_x000D_
      <li>List Item Two</li>_x000D_
      <li>List Item Three</li>_x000D_
      <li>List Item Four</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
  <div class="floating-div">_x000D_
    <ul>_x000D_
      <li>List Item Five</li>_x000D_
      <li>List Item Six</li>_x000D_
      <li>List Item Seven</li>_x000D_
      <li>List Item Eight</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

from https://www.lockedownseo.com/parent-div-100-height-child-floated-elements/

How to set ChartJS Y axis title?

For Chart.js 2.x refer to andyhasit's answer - https://stackoverflow.com/a/36954319/360067

For Chart.js 1.x, you can tweak the options and extend the chart type to do this, like so

Chart.types.Line.extend({
    name: "LineAlt",
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);

        var ctx = this.chart.ctx;
        ctx.save();
        // text alignment and color
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";
        ctx.fillStyle = this.options.scaleFontColor;
        // position
        var x = this.scale.xScalePaddingLeft * 0.4;
        var y = this.chart.height / 2;
        // change origin
        ctx.translate(x, y);
        // rotate text
        ctx.rotate(-90 * Math.PI / 180);
        ctx.fillText(this.datasets[0].label, 0, 0);
        ctx.restore();
    }
});

calling it like this

var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
    // make enough space on the right side of the graph
    scaleLabel: "          <%=value%>"
});

Notice the space preceding the label value, this gives us space to write the y axis label without messing around with too much of Chart.js internals


Fiddle - http://jsfiddle.net/wyox23ga/


enter image description here

Format numbers in django templates

Regarding Ned Batchelder's solution, here it is with 2 decimal points and a dollar sign. This goes somewhere like my_app/templatetags/my_filters.py

from django import template
from django.contrib.humanize.templatetags.humanize import intcomma

register = template.Library()

def currency(dollars):
    dollars = round(float(dollars), 2)
    return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:])

register.filter('currency', currency)

Then you can

{% load my_filters %}
{{my_dollars | currency}}

Need to install urllib2 for Python 3.5.1

In Python 3, urllib2 was replaced by two in-built modules named urllib.request and urllib.error

Adapted from source


So replace this:

import urllib2

With this:

import urllib.request as urllib2

What is the difference between 'java', 'javaw', and 'javaws'?

From http://publib.boulder.ibm.com/infocenter/javasdk/v6r0/index.jsp?topic=%2Fcom.ibm.java.doc.user.aix32.60%2Fuser%2Fjava.html:

The javaw command is identical to java, except that javaw has no associated console window. Use javaw when you do not want a command prompt window to be displayed. The javaw launcher displays a window with error information if it fails.

And javaws is for Java web start applications, applets, or something like that, I would suspect.

how to bind datatable to datagridview in c#

foreach (DictionaryEntry entry in Hashtable)
{
    datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}

How can I remove the top and right axis in matplotlib?

This is the suggested Matplotlib 3 solution from the official website HERE:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

ax = plt.subplot(111)
ax.plot(x, y)

# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

plt.show()

enter image description here

Installing SciPy with pip

  1. install python-3.4.4
  2. scipy-0.15.1-win32-superpack-python3.4
  3. apply the following commend doc
py -m pip install --upgrade pip
py -m pip install numpy
py -m pip install matplotlib
py -m pip install scipy
py -m pip install scikit-learn

How can I set multiple CSS styles in JavaScript?

<button onclick="hello()">Click!</button>

<p id="demo" style="background: black; color: aliceblue;">
  hello!!!
</p>

<script>
  function hello()
  {
    (document.getElementById("demo").style.cssText =
      "font-size: 40px; background: #f00; text-align: center;")
  }
</script>

SQL Query to fetch data from the last 30 days?

SELECT COUNT(job_id) FROM jobs WHERE posted_date < NOW()-30;

Now() returns the current Date and Time.

Onclick CSS button effect

You should apply the following styles:

#button:active {
    vertical-align: top;
    padding: 8px 13px 6px;
}

This will give you the necessary effect, demo here.

How to reduce a huge excel file

i Change the format of file to *.XLSX this change compress my file and reduce file size of 15%

Is calling destructor manually always a sign of bad design?

I found 3 occasions where I needed to do this:

  • allocating/deallocating objects in memory created by memory-mapped-io or shared memory
  • when implementing a given C interface using C++ (yes this still happens today unfortunately (because I don't have enough clout to change it))
  • when implementing allocator classes

How to check if a service is running on Android?

First of all you shouldn't reach the service by using the ActivityManager. (Discussed here)

Services can run on their own, be bound to an Activity or both. The way to check in an Activity if your Service is running or not is by making an interface (that extends Binder) where you declare methods that both, the Activity and the Service, understand. You can do this by making your own Interface where you declare for example "isServiceRunning()". You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.

You can also use this method to stop your Service or interact with it in another way.

Best way to copy a database (SQL Server 2008)

I run an SP to DROP the table(s) and then use a DTS package to import the most recent production table(s) onto my development box. Then I go home and come back the following morning. It's not elegant; but it works for me.

Running Selenium Webdriver with a proxy in Python

My solution:

def my_proxy(PROXY_HOST,PROXY_PORT):
        fp = webdriver.FirefoxProfile()
        # Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
        print PROXY_PORT
        print PROXY_HOST
        fp.set_preference("network.proxy.type", 1)
        fp.set_preference("network.proxy.http",PROXY_HOST)
        fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
        fp.set_preference("general.useragent.override","whater_useragent")
        fp.update_preferences()
        return webdriver.Firefox(firefox_profile=fp)

Then call in your code:

my_proxy(PROXY_HOST,PROXY_PORT)

I had issues with this code because I was passing a string as a port #:

 PROXY_PORT="31280"

This is important:

int("31280")

You must pass an integer instead of a string or your firefox profile will not be set to a properly port and connection through proxy will not work.

Python: Continuing to next iteration in outer loop

We want to find something and then stop the inner iteration. I use a flag system.

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

How can I check for "undefined" in JavaScript?

    var x;
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    if (typeof y === "undefined") {
        alert ("I am not even declared.")
    };

    /* One more thing to understand: typeof ==='undefined' also checks 
       for if a variable is declared, but no value is assigned. In other 
       words, the variable is declared, but not defined. */

    // Will repeat above logic of x for typeof === 'undefined'
    if (x === undefined) {
        alert ("I am declared, but not defined.")
    };
    /* So typeof === 'undefined' works for both, but x === undefined 
       only works for a variable which is at least declared. */

    /* Say if I try using typeof === undefined (not in quotes) for 
       a variable which is not even declared, we will get run a 
       time error. */

    if (z === undefined) {
        alert ("I am neither declared nor defined.")
    };
    // I got this error for z ReferenceError: z is not defined 

What is the advantage of using REST instead of non-REST HTTP?

I recommend taking a look at Ryan Tomayko's How I Explained REST to My Wife

Third party edit

Excerpt from the waybackmaschine link:

How about an example. You’re a teacher and want to manage students:

  • what classes they’re in,
  • what grades they’re getting,
  • emergency contacts,
  • information about the books you teach out of, etc.

If the systems are web-based, then there’s probably a URL for each of the nouns involved here: student, teacher, class, book, room, etc. ... If there were a machine readable representation for each URL, then it would be trivial to latch new tools onto the system because all of that information would be consumable in a standard way. ... you could build a country-wide system that was able to talk to each of the individual school systems to collect testing scores.

Each of the systems would get information from each other using a simple HTTP GET. If one system needs to add something to another system, it would use an HTTP POST. If a system wants to update something in another system, it uses an HTTP PUT. The only thing left to figure out is what the data should look like.

How can I get a value from a map?

The answer by Steve Jessop explains well, why you can't use std::map::operator[] on a const std::map. Gabe Rainbow's answer suggests a nice alternative. I'd just like to provide some example code on how to use map::at(). So, here is an enhanced example of your function():

void function(const MAP &map, const std::string &findMe) {
    try {
        const std::string& value = map.at(findMe);
        std::cout << "Value of key \"" << findMe.c_str() << "\": " << value.c_str() << std::endl;
        // TODO: Handle the element found.
    }
    catch (const std::out_of_range&) {
        std::cout << "Key \"" << findMe.c_str() << "\" not found" << std::endl;
        // TODO: Deal with the missing element.
    }
}

And here is an example main() function:

int main() {
    MAP valueMap;
    valueMap["string"] = "abc";
    function(valueMap, "string");
    function(valueMap, "strong");
    return 0;
}

Output:

Value of key "string": abc
Key "strong" not found

Code on Ideone

How to format JSON in notepad++

Try with JSToolNpp and follow the snap like this then Plugins | JSTool | JSFormat.

enter image description here

Pandas groupby month and year

Why not keep it simple?!

GB=DF.groupby([(DF.index.year),(DF.index.month)]).sum()

giving you,

print(GB)
        abc  xyz
2013 6   80  250
     8   40   -5
2014 1   25   15
     2   60   80

and then you can plot like asked using,

GB.plot('abc','xyz',kind='scatter')

To find first N prime numbers in python

max = input("enter the maximum limit to check prime number");
if max>1 :
    for i in range (2,max):
        prime=0;
        for j in range (2,i):
            if(i%j==0):
                prime=1;
                break
        if(prime==0 and i!=0):
            print(i,"is prime number");
else:
    print("prime no start from 2");

Aren't Python strings immutable? Then why does a + " " + b work?

l = [1,2,3]
print id(l)
l.append(4)
print id(l) #object l is the same

a = "dog"
print id(a)
a = "cat"
print id(a) #object a is a new object, previous one is deleted

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

Number of days in particular month of particular year?

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/*
 * 44. Return the number of days in a month
 * , where month and year are given as input.
 */
public class ex44 {
    public static void dateReturn(int m,int y)
    {
        int m1=m;
        int y1=y;
        String str=" "+ m1+"-"+y1;
        System.out.println(str);
        SimpleDateFormat sd=new SimpleDateFormat("MM-yyyy");

        try {
            Date d=sd.parse(str);
            System.out.println(d);
            Calendar c=Calendar.getInstance();
            c.setTime(d);
            System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static void main(String[] args) {
dateReturn(2,2012);


    }

}

Any reason not to use '+' to concatenate two strings?

When working with multiple people, it's sometimes difficult to know exactly what's happening. Using a format string instead of concatenation can avoid one particular annoyance that's happened a whole ton of times to us:

Say, a function requires an argument, and you write it expecting to get a string:

In [1]: def foo(zeta):
   ...:     print 'bar: ' + zeta

In [2]: foo('bang')
bar: bang

So, this function may be used pretty often throughout the code. Your coworkers may know exactly what it does, but not necessarily be fully up-to-speed on the internals, and may not know that the function expects a string. And so they may end up with this:

In [3]: foo(23)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

/home/izkata/<ipython console> in foo(zeta)

TypeError: cannot concatenate 'str' and 'int' objects

There would be no problem if you just used a format string:

In [1]: def foo(zeta):
   ...:     print 'bar: %s' % zeta
   ...:     
   ...:     

In [2]: foo('bang')
bar: bang

In [3]: foo(23)
bar: 23

The same is true for all types of objects that define __str__, which may be passed in as well:

In [1]: from datetime import date

In [2]: zeta = date(2012, 4, 15)

In [3]: print 'bar: ' + zeta
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

TypeError: cannot concatenate 'str' and 'datetime.date' objects

In [4]: print 'bar: %s' % zeta
bar: 2012-04-15

So yes: If you can use a format string do it and take advantage of what Python has to offer.

Find which version of package is installed with pip

For Windows you can

  1. open cmd and type python, press enter.

  2. type the import and press enter.

  3. type ._version__ and press enter.

As you can see in screen shot here I am using this method for checking the version of serial module.

Image


Add new value to an existing array in JavaScript

Indeed, you must initialize your array then right after that use array.push() command line.

var array = new Array();
array.push("first value");
array.push("second value");

How to remove "index.php" in codeigniter's path

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /codeigniter/index.php/$0 [PT,L]

after changing RewriteRule .* index.php/$0 [PT,L] with the project folder name "codeigniter".its working for me. Thanks guys for your support.

Passing data into "router-outlet" child components

Following this question, in Angular 7.2 you can pass data from parent to child using the history state. So you can do something like

Send:

this.router.navigate(['action-selection'], { state: { example: 'bar' } });

Retrieve:

constructor(private router: Router) {
  console.log(this.router.getCurrentNavigation().extras.state.example);
}

But be careful to be consistent. For example, suppose you want to display a list on a left side bar and the details of the selected item on the right by using a router-outlet. Something like:


Item 1 (x) | ..............................................

Item 2 (x) | ......Selected Item Details.......

Item 3 (x) | ..............................................

Item 4 (x) | ..............................................


Now, suppose you have already clicked some items. Clicking the browsers back buttons will show the details from the previous item. But what if, meanwhile, you have clicked the (x) and delete from your list that item? Then performing the back click, will show you the details of a deleted item.

MongoDB: Is it possible to make a case-insensitive query?

UPDATE:

The original answer is now obsolete. Mongodb now supports advanced full text searching, with many features.

ORIGINAL ANSWER:

It should be noted that searching with regex's case insensitive /i means that mongodb cannot search by index, so queries against large datasets can take a long time.

Even with small datasets, it's not very efficient. You take a far bigger cpu hit than your query warrants, which could become an issue if you are trying to achieve scale.

As an alternative, you can store an uppercase copy and search against that. For instance, I have a User table that has a username which is mixed case, but the id is an uppercase copy of the username. This ensures case-sensitive duplication is impossible (having both "Foo" and "foo" will not be allowed), and I can search by id = username.toUpperCase() to get a case-insensitive search for username.

If your field is large, such as a message body, duplicating data is probably not a good option. I believe using an extraneous indexer like Apache Lucene is the best option in that case.

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

How to save a plot as image on the disk?

If you want to keep seeing the plot in R, another option is to use dev.copy:

X11 ()
plot (x,y)

dev.copy(jpeg,filename="plot.jpg");
dev.off ();

If you reach a clutter of too many plot windows in R, use graphics.off() to close all of the plot windows.

How do I get the time of day in javascript/Node.js?

If you only want the time string you can use this expression (with a simple RegEx):

new Date().toISOString().match(/(\d{2}:){2}\d{2}/)[0]
// "23:00:59"

Unable to copy ~/.ssh/id_rsa.pub

In case you are trying to use xclip on remote host just add -X to your ssh command

ssh user@host -X

More detailed information can be found here : https://askubuntu.com/a/305681

Running windows shell commands with python

You would use the os module system method.

You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC

For example:

os.system('python') opens up the windows command prompt and runs the python interpreter

os.system('python') example

Passing an array/list into a Python function

You don't need to use the asterisk to accept a list.

Simply give the argument a name in the definition, and pass in a list like

def takes_list(a_list):
    for item in a_list:
         print item

How to always show scrollbar

android:scrollbarFadeDuration="0" sometimes does not work after I exit from the apps and start again. So I add gallery.setScrollbarFadingEnabled(false); to the activity and it works!

Getting the folder name from a path

It's also important to note that while getting a list of directory names in a loop, the DirectoryInfo class gets initialized once thus allowing only first-time call. In order to bypass this limitation, ensure you use variables within your loop to store any individual directory's name.

For example, this sample code loops through a list of directories within any parent directory while adding each found directory-name inside a List of string type:

[C#]

string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();

foreach (var directory in parentDirectory)
{
    // Notice I've created a DirectoryInfo variable.
    DirectoryInfo dirInfo = new DirectoryInfo(directory);

    // And likewise a name variable for storing the name.
    // If this is not added, only the first directory will
    // be captured in the loop; the rest won't.
    string name = dirInfo.Name;

    // Finally we add the directory name to our defined List.
    directories.Add(name);
}

[VB.NET]

Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()

For Each directory In parentDirectory

    ' Notice I've created a DirectoryInfo variable.
    Dim dirInfo As New DirectoryInfo(directory)

    ' And likewise a name variable for storing the name.
    ' If this is not added, only the first directory will
    ' be captured in the loop; the rest won't.
    Dim name As String = dirInfo.Name

    ' Finally we add the directory name to our defined List.
    directories.Add(name)

Next directory

What is the meaning of 'No bundle URL present' in react-native?

This problem may happen when we have multiple versions of node managed by nvm and default version is not intended version to run react-native. (make sure it is Node 8.3 or newer)

react-native run-ios

opens a new terminal and runs the version of node found in the $PATH.

If it finds an older version of node not supported by react native, it may give this error.

Make sure, the $PATH variable is already pointing to intended version of node(make sure it is Node 8.3 or newer) when a new terminal is opened.

That solved the issue for me. Good luck.

Using Predicate in Swift

// change "name" and "value" according to your array data.

// Change "yourDataArrayName" name accroding to your array(NSArray).

    let resultPredicate = NSPredicate(format: "SELF.name contains[c] %@", "value")

    if let sortedDta = yourDataArrayName.filtered(using: resultPredicate) as? NSArray {

 //enter code here.

        print(sortedDta)
    }

Batch script to delete files

Lets say you saved your software onto your desktop.
if you want to remove an entire folder like an uninstaller program you could use this.

cd C:\Users\User\Detsktop\
rd /s /q SOFTWARE

this will delete the entire folder called software and all of its files and subfolders

Make Sure You Delete The Correct Folder Cause This Does Not Have A Yes / No Option

Squash my last X commits together using Git

In the branch you would like to combine the commits on, run:

git rebase -i HEAD~(n number of commits back to review)

example:

git rebase -i HEAD~1

This will open the text editor and you must switch the 'pick' in front of each commit with 'squash' if you would like these commits to be merged together. From documentation:

p, pick = use commit

s, squash = use commit, but meld into previous commit

For example, if you are looking to merge all the commits into one, the 'pick' is the first commit you made and all future ones (placed below the first) should be set to 'squash'. If using vim, use :x in insert mode to save and exit the editor.

Then to continue the rebase:

git rebase --continue

For more on this and other ways to rewrite your commit history see this helpful post

How do I pull from a Git repository through an HTTP proxy?

On Windows, if you don't want to put your password in .gitconfig in the plain text, you can use

It authenticates you against normal or even Windows NTLM proxy and starts localhost-proxy without authentication.

In order to get it run:

  • Install Cntml
  • Configure Cntml according to documentation to pass your proxy authentication
  • Point git to your new localhost proxy:

    [http]
        proxy = http://localhost:3128       # change port as necessary
    

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

How can I call a shell command in my Perl script?

How to run a shell script from a Perl program

1. Using system system($command, @arguments);

For example:

system("sh", "script.sh", "--help" );

system("sh script.sh --help");

System will execute the $command with @arguments and return to your script when finished. You may check $! for certain errors passed to the OS by the external application. Read the documentation for system for the nuances of how various invocations are slightly different.

2. Using exec

This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more.

3. Using backticks or qx//

my $output = `script.sh --option`;

my $output = qx/script.sh --option/;

The backtick operator and it's equivalent qx//, excute the command and options inside the operator and return that commands output to STDOUT when it finishes.

There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more.

How to decrypt an encrypted Apple iTunes iPhone backup?

Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.

You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.

Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.

I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.

Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.

I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.

In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.

Good luck!

Android: adbd cannot run as root in production builds

For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root can run smoothly.

View tabular file such as CSV from command line

I've created tablign for these (and other) purposes. Install with

pip install tablign

and

$ cat test.csv
Header1,Header2,Header3
Pizza,Artichoke dip,Bob's Special of the Day
BLT,Ham on rye with the works,
$ tablign test.csv
Header1 , Header2                   , Header3
Pizza   , Artichoke dip             , Bob's Special of the Day
BLT     , Ham on rye with the works ,

Also works if the data is separated by something else than commas. Most importantly, it preserves the delimiters so you can also use it to style your ASCII tables without sacrificing your [Markdown,CSV,LaTeX] syntax.

Using SQL LIKE and IN together

Use the longer version of IN which is a bunch of OR.

SELECT * FROM tablename 
WHERE column LIKE 'M510%'
OR column LIKE 'M615%'
OR column LIKE 'M515%'
OR column LIKE 'M612%';

How to make custom error pages work in ASP.NET MVC 4

My current setup (on MVC3, but I think it still applies) relies on having an ErrorController, so I use:

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error">
      <error redirect="~/Error/NotFound" statusCode="404" />
    </customErrors>
</system.web>

And the controller contains the following:

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return View("Error");
    }
    public ViewResult NotFound()
    {
        Response.StatusCode = 404;  //you may want to set this to 200
        return View("NotFound");
    }
}

And the views just the way you implement them. I tend to add a bit of logic though, to show the stack trace and error information if the application is in debug mode. So Error.cshtml looks something like this:

@model System.Web.Mvc.HandleErrorInfo
@{
    Layout = "_Layout.cshtml";
    ViewBag.Title = "Error";
}
<div class="list-header clearfix">
    <span>Error</span>
</div>
<div class="list-sfs-holder">
    <div class="alert alert-error">
        An unexpected error has occurred. Please contact the system administrator.
    </div>
    @if (Model != null && HttpContext.Current.IsDebuggingEnabled)
    {
        <div>
            <p>
                <b>Exception:</b> @Model.Exception.Message<br />
                <b>Controller:</b> @Model.ControllerName<br />
                <b>Action:</b> @Model.ActionName
            </p>
            <div style="overflow:scroll">
                <pre>
                    @Model.Exception.StackTrace
                </pre>
            </div>
        </div>
    }
</div>

how to make label visible/invisible?

You should be able to get it to hide/show by setting:

.style.display = 'none';
.style.display = 'inline';

Bind a function to Twitter Bootstrap Modal Close

Bootstrap provide events that you can hook into modal, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event like this

    /* hidden.bs.modal event example */
    $('#myModal').on('hidden.bs.modal', function () {
          window.alert('hidden event fired!');
    })

Check a working fiddle here read more about modal methods and events here in Documentation

Select DISTINCT individual columns in django?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values().

In your case you can do the following to get the names of distinct categories:

q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.

# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"

There are a couple of things to remember here. First, this will return a ValuesQuerySet which behaves differently from a QuerySet. When you access say, the first element of q (above) you'll get a dictionary, NOT an instance of ProductOrder.

Second, it would be a good idea to read the warning note in the docs about using distinct(). The above example will work but all combinations of distinct() and values() may not.

PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:

class ProductOrder(models.Model):
    product  = models.CharField(max_length=20, primary_key=True)
    category = models.CharField(max_length=30)
    rank = models.IntegerField()

Remote JMX connection

I have the same issue and I change any hostname that matches the local host name to 0.0.0.0, it seems to work after I do that.

Simple (non-secure) hash function for JavaScript?

Check out these implementations

Maven dependencies are failing with a 501 error

Update the central repository of Maven and use https instead of http.

<repositories>
    <repository>
        <id>central</id>
        <name>Central Repository</name>
        <url>https://repo.maven.apache.org/maven2</url>
        <layout>default</layout>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

Is it possible to play music during calls so that the partner can hear it ? Android

I think it's not possible. Though I found an app from google play called PHONE MUSIC which claims to : "Thus whenver someone puts you on hold just hit the hovering musical note and start playing music. Or play music while someones on the phone with you. "

Can I scroll a ScrollView programmatically in Android?

Yes, you can.

Let's say you got one Layout and inside that, you got many Views. So if you want to scroll to any View programmatically, you have to write the following code snippet:

For example:

content_main.xml

<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txtView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</ScrollView>

MainActivity.java

ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
Button btn = (Button) findViewById(R.id.ivEventBanner);
TextView txtView = (TextView) findViewById(R.id.ivEditBannerImage);

If you want to scroll to a specific View, let's say txtview, in this case, just write:

scrollView.smoothScrollTo(txtView.getScrollX(),txtView.getScrollY());

And you are done.

Export data from R to Excel

writexl, without Java requirement:

# install.packages("writexl")
library(writexl)
tempfile <- write_xlsx(iris)

Java: Convert String to TimeStamp

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

Date date = formatter.parse(dateString);

Timestamp timestamp = new Timestamp(date.getTime());

System.out.println(timestamp);

What is the difference between Swing and AWT?

Swing:

  1. Swing is part of the java foundation classes.
  2. Swing components are platform-independent.
  3. Swing components are lightweight components because swing sits on the top of awt.

AWT:

  1. AWT is called the abstract window tool.
  2. AWT components are platform-dependent.
  3. AWT components are heavyweight components.

How do I concatenate two arrays in C#?

What you need to remember is that when using LINQ you are utilizing delayed execution. The other methods described here all work perfectly, but they are executed immediately. Furthermore the Concat() function is probably optimized in ways you can't do yourself (calls to internal API's, OS calls etc.). Anyway, unless you really need to try and optimize, you're currently on your path to "the root of all evil" ;)

Use JSTL forEach loop's varStatus as an ID

You can try this. similar result

 <c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount.count}"></div>
 </c:forEach>

Read response headers from API response - Angular 5 + TypeScript

Angular 7 Service:

    this.http.post(environment.urlRest + '/my-operation',body, { headers: headers, observe: 'response'});
    
Component:
    this.myService.myfunction().subscribe(
          (res: HttpResponse) => {
              console.log(res.headers.get('x-token'));
                }  ,
        error =>{
        }) 
    

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

jquery - Check for file extension before uploading

I would like to thank the person who posted the answer, but he has deleted the post. We can do it like this.

$("#yourElem").uploadify({
   'uploader': ...,
   'script': ...
    'fileExt' : '*.jpg;*.gif;', //add allowed extensions
    .....,
    'onSelect': function(e, q, f) {
        var validExtensions = ['jpg','gif']; //array of valid extensions
        var fileName = f.name;
        var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
        if ($.inArray(fileNameExt, validExtensions) == -1){
           alert("Invalid file type");
           $("#yourElem").uploadifyCancel(q);
           return false;
        }
    }
});

Thanks for the answer, it really worked...

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

How can I concatenate a string within a loop in JSTL/JSP?

define a String variable using the JSP tags

<%!
String test = new String();
%>

then refer to that variable in your loop as

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>

Android emulator not able to access the internet

Simply open the AVD Manager and wipe the data of that emulator works for me.

How to copy a collection from one database to another in MongoDB

Actually, there is a command to move a collection from one database to another. It's just not called "move" or "copy".

To copy a collection, you can clone it on the same database, then move the cloned collection.

To clone:

> use db1
switched to db db1

> db.source_collection.find().forEach(
      function(x){
          db.collection_copy.insert(x)
      }
  );

To move:

> use admin
switched to db admin

> db.runCommand(
      {
          renameCollection: 'db1.source_collection',
          to              : 'db2.target_collection'
      }
  );

The other answers are better for copying the collection, but this is especially useful if you're looking to move it.