Programs & Examples On #Java.util.logging

Java package which provides the classes and interfaces of the Java 2 platform's core logging facilities.

Why are the Level.FINE logging messages not showing?

I found my actual problem and it was not mentioned in any answer: some of my unit-tests were causing logging initialization code to be run multiple times within the same test suite, messing up the logging on the later tests.

How can I disable the default console handler, while using the java logging API?

Do a reset of the configuration and set the root level to OFF

LogManager.getLogManager().reset();
Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(java.util.logging.Level.OFF);

Good examples using java.util.logging

There are many examples and also of different types for logging. Take a look at the java.util.logging package.

Example code:

import java.util.logging.Logger;

public class Main {

  private static Logger LOGGER = Logger.getLogger("InfoLogging");

  public static void main(String[] args) {
    LOGGER.info("Logging an INFO-level message");
  }
}

Without hard-coding the class name:

import java.util.logging.Logger;

public class Main {
  private static final Logger LOGGER = Logger.getLogger(
    Thread.currentThread().getStackTrace()[0].getClassName() );

  public static void main(String[] args) {
    LOGGER.info("Logging an INFO-level message");
  }
}

Why can't Python parse this JSON data?

If you're using Python3, you can try changing your (connection.json file) JSON to:

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

Then using the following code:

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>> test1

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

here is your answer

String userName = "xxxx";
    String password = "xxxx";
    String url = "jdbc:sqlserver:xxx.xxx.xxx.xxx;databaseName=asdfzxcvqwer;integratedSecurity=true";

    try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            connection = DriverManager.getConnection(url, userName, password); 

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

What are the differences between type() and isinstance()?

According to python documentation here is a statement:

8.15. types — Names for built-in types

Starting in Python 2.2, built-in factory functions such as int() and str() are also names for the corresponding types.

So isinstance() should be preferred over type().

Complex CSS selector for parent of active child

According to Wikipedia:

Selectors are unable to ascend

CSS offers no way to select a parent or ancestor of element that satisfies certain criteria. A more advanced selector scheme (such as XPath) would enable more sophisticated stylesheets. However, the major reasons for the CSS Working Group rejecting proposals for parent selectors are related to browser performance and incremental rendering issues.

And for anyone searching SO in future, this might also be referred to as an ancestor selector.

Update:

The Selectors Level 4 Spec allows you to select which part of the select is the subject:

The subject of the selector can be explicitly identified by prepending a dollar sign ($) to one of the compound selectors in a selector. Although the element structure that the selector represents is the same with or without the dollar sign, indicating the subject in this way can change which compound selector represents the subject in that structure.

Example 1:

For example, the following selector represents a list item LI unique child of an ordered list OL:

OL > LI:only-child

However the following one represents an ordered list OL having a unique child, that child being a LI:

$OL > LI:only-child

The structures represented by these two selectors are the same, but the subjects of the selectors are not.

Although this isn't available (currently, November 2011) in any browser or as a selector in jQuery.

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,

BEGIN

    .. Declare statements ..

    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
          .. set any flags etc  eg. SET @flag = 0; ..
          ROLLBACK;
    END;

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;
    .. eg. SET @flag = 1; ..

END

AngularJS ui router passing data between states without URL

We can use params, new feature of the UI-Router:

API Reference / ui.router.state / $stateProvider

params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.

See the part: "...or defines additional non-url parameters..."

So the state def would be:

$stateProvider
  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
    params: { hiddenOne: null, }
  })

Few examples form the doc mentioned above:

// define a parameter's default value
params: {
  param1: { value: "defaultValue" }
}
// shorthand default values
params: {
  param1: "defaultValue",
  param2: "param2Default"
}

// param will be array []
params: {
  param1: { array: true }
}

// handling the default value in url:
params: {
  param1: {
    value: "defaultId",
    squash: true
} }
// squash "defaultValue" to "~"
params: {
  param1: {
    value: "defaultValue",
    squash: "~"
  } }

EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info

Here is an example of a state definition:

 $stateProvider
  .state('home', {
      url: "/home",
      params : { veryLongParamHome: null, },
      ...
  })
  .state('parent', {
      url: "/parent",
      params : { veryLongParamParent: null, },
      ...
  })
  .state('parent.child', { 
      url: "/child",
      params : { veryLongParamChild: null, },
      ...
  })

This could be a call using ui-sref:

<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
  })">home</a>

<a ui-sref="parent({ 
    veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
  })">parent</a>

<a ui-sref="parent.child({
    veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',  
    veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
  })">parent.child</a>

Check the example here

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

This is if you see Java classes in red and get this error, "Cannot resolve symbol".

If you're importing projects into IntelliJ and none of the above solutions worked for you then give this a try. This is what worked for me when everything else failed.

Go to to your project folder and rename/delete the .idea folder which has the idea settings for your project. This would have been created from your old IntelliJ version. Once you have renamed/deleted the .idea folder, import your project into IntelliJ. You should not see any errors for your Java classes now. Hope this helped.

jinja2.exceptions.TemplateNotFound error

You put your template in the wrong place. From the Flask docs:

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates

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

The 2nd option is the one you want.

In your web.config, make sure these keys exist:

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>

JavaScript: How to get parent element by selector?

var base_element = document.getElementById('__EXAMPLE_ELEMENT__');
for( var found_parent=base_element, i=100; found_parent.parentNode && !(found_parent=found_parent.parentNode).classList.contains('__CLASS_NAME__') && i>0; i-- );
console.log( found_parent );

How to convert currentTimeMillis to a date in Java?

The easiest way to do this is to use the Joda DateTime class and specify both the timestamp in milliseconds and the DateTimeZone you want.

I strongly recommend avoiding the built-in Java Date and Calendar classes; they're terrible.

Loop code for each file in a directory

scandir:

$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or glob may be even better for your needs:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}

How can I remove a specific item from an array?

I made a function:

function pop(valuetoremove, myarray) {
    var indexofmyvalue = myarray.indexOf(valuetoremove);
    myarray.splice(indexofmyvalue, 1);
}

And used it like this:

pop(valuetoremove, myarray);

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Using 2.0 and 4.0 assemblies together isn't quite straight forward.

The ORDER of the supported framework declarations in app.config actually have an effect on the exception of mixed mode being thrown. If you flip the declaration order you will get mixed mode error. This is the purpose of this answer.

So if you get the error in a Windows Forms app, , try this, mostly Windows Forms apps.

  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/>
    <supportedRuntime version="v2.0.50727"></supportedRuntime>
  </startup>

Or if the project is not Windows Form. In a Web project add this to web.config file.

  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    <supportedRuntime version="v2.0.50727"></supportedRuntime>
  </startup>

How to convert a Django QuerySet to a list

Try this values_list('column_name', flat=True).

answers = Answer.objects.filter(id__in=[answer.id for answer in answer_set.answers.all()]).values_list('column_name', flat=True)

It will return you a list with specified column values

How to pretty print XML from Java?

Hmmm... faced something like this and it is a known bug ... just add this OutputProperty ..

transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "8");

Hope this helps ...

Generate C# class from XML

Use below syntax to create schema class from XSD file.

C:\xsd C:\Test\test-Schema.xsd /classes /language:cs /out:C:\Test\

How to select all and copy in vim?

There are a few important informations missing from your question:

  • output of $ vim --version?
  • OS?
  • CLI or GUI?
  • local or remote?
  • do you use tmux? screen?

If your Vim was built with clipboard support, you are supposed to use the clipboard register like this, in normal mode:

gg"+yG

If your Vim doesn't have clipboard support, you can manage to copy text from Vim to your OS clipboard via other programs. This pretty much depends on your OS but you didn't say what it is so we can't really help.

However, if your Vim is crippled, the best thing to do is to install a proper build with clipboard support but I can't tell you how either because I don't know what OS you use.

edit

On debian based systems, the following command will install a proper Vim with clipboard, ruby, python… support.

$ sudo apt-get install vim-gnome

reading from app.config file

Just for the future reference, you just need to add System.Configuration to your references library:

enter image description here

Adding values to specific DataTable cells

You mean you want to add a new row and only put data in a certain column? Try the following:

var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);

As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value instead of whatever data type you imagine it would be.

Using Server.MapPath in external C# Classes in ASP.NET

The ServerUtility class is available as an instance in your HttpContext. If you're in an environment where you know it'll be executed inside the ASP.Net pipeline, you can use

HttpContext.Current.Server.MapPath()

You'll have to import System.Web though.

How to remove duplicate white spaces in string using Java?

You can also try using String Tokeniser, for any space, tab, newline, and all. A simple way is,

String s = "Your Text Here";        
StringTokenizer st = new StringTokenizer( s, " " );
while(st.hasMoreTokens())
{
    System.out.print(st.nextToken());
}

Get last 30 day records from today date in SQL Server

You can use DateDiff for this. The where clause in your query would look like:

where DATEDIFF(day,pdate,GETDATE()) < 31

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Your selector is a little off, it's missing the trailing ]

var mySelect = $('select[name=' + name + ']')

you may also need to put quotes around the name, like so:

var mySelect = $('select[name="' + name + '"]')

What is the most "pythonic" way to iterate over a list in chunks?

I'm a fan of

chunk_size= 4
for i in range(0, len(ints), chunk_size):
    chunk = ints[i:i+chunk_size]
    # process chunk of size <= chunk_size

Returning JSON object as response in Spring Boot

you can also use a hashmap for this

@GetMapping
public HashMap<String, Object> get() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("results", somePOJO);
    return map;
}

Assert an object is a specific type

You can use the assertThat method and the Matchers that comes with JUnit.

Take a look at this link that describes a little bit about the JUnit Matchers.

Example:

public class BaseClass {
}

public class SubClass extends BaseClass {
}

Test:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author maba, 2012-09-13
 */
public class InstanceOfTest {

    @Test
    public void testInstanceOf() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }
}

How do I Set Background image in Flutter?

We can use Container and mark its height as infinity

body: Container(
      height: double.infinity,
      width: double.infinity,
      child: FittedBox(
        fit: BoxFit.cover,
        child: Image.network(
          'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
        ),
      ),
    ));

Output:

enter image description here

Spring MVC + JSON = 406 Not Acceptable

Use below dependency in your pom

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>

How to write a stored procedure using phpmyadmin and how to use it through php?

Since a stored procedure is created, altered and dropped using queries you actually CAN manage them using phpMyAdmin.

To create a stored procedure, you can use the following (change as necessary) :

CREATE PROCEDURE sp_test()
BEGIN
  SELECT 'Number of records: ', count(*) from test;
END//

And make sure you set the "Delimiter" field on the SQL tab to //.

Once you created the stored procedure it will appear in the Routines fieldset below your tables (in the Structure tab), and you can easily change/drop it.

To use the stored procedure from PHP you have to execute a CALL query, just like you would do in plain SQL.

Getting unique items from a list

In .Net 2.0 I`m pretty sure about this solution:

public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
     List<T> uniques = new List<T>();
     foreach (T item in source)
     {
         if (!uniques.Contains(item)) uniques.Add(item);
     }
     return uniques;
}

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

gray = cv2.cvtColor(cv2.UMat(imgUMat), cv2.COLOR_RGB2GRAY)

UMat is a part of the Transparent API (TAPI) than help to write one code for the CPU and OpenCL implementations.

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

Define the selected option with the old input in Laravel / Blade

Laravel 6 or above: just use the old() function for instance @if (old('cat')==$cat->id), it will do the rest of the work for you.

How its works: select tag store the selected option value into its name attribute in bellow case if you select any option it will store into cat. At the first time when page loaded there is nothing inside cat, when user chose a option the value of that selected option is stored into cat so when user were redirected old() function pull the previous value from cat.

 {!!Form::open(['action'=>'CategoryController@storecat', 'method'=>'POST']) !!}
        <div class="form-group">
            <select name="cat" id="cat" class="form-control input-lg">
                <option value="">Select App</option>
                @foreach ($cats as $cat)
                    @if (old('cat')==$cat->id)
                        <option value={{$cat->id}} selected>{{ $cat->title }}</option>
                    @else
                        <option value={{$cat->id}} >{{ $cat->title }}</option>
                    @endif
                @endforeach
            </select>
        </div>

        <div class="from-group">
            {{Form::label('name','Category name:')}}
            {{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
        </div>
    <br>
    {!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
    {!!Form::close()!!}

Deleting all files in a directory with Python

I realize this is old; however, here would be how to do so using just the os module...

def purgedir(parent):
    for root, dirs, files in os.walk(parent):                                      
        for item in files:
            # Delete subordinate files                                                 
            filespec = os.path.join(root, item)
            if filespec.endswith('.bak'):
                os.unlink(filespec)
        for item in dirs:
            # Recursively perform this operation for subordinate directories   
            purgedir(os.path.join(root, item))

jQuery.animate() with css class only, without explicit styles

The jQueryUI provides a extension to animate function that allows you to animate css class.

edit: Example here

There are also methods to add/remove/toggle class which you might also be interested in.

Get the data received in a Flask request

To post JSON with jQuery in JavaScript, use JSON.stringify to dump the data, and set the content type to application/json.

var value_data = [1, 2, 3, 4];

$.ajax({
    type: 'POST',
    url: '/process',
    data: JSON.stringify(value_data),
    contentType: 'application/json',
    success: function (response_data) {
        alert("success");
    }   
});

Parse it in Flask with request.get_json().

data = request.get_json()

Cannot open backup device. Operating System error 5

The SQL Server service account does not have permissions to write to the folder C:\Users\Kimpoy\Desktop\Backup\

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

How can I use NSError in my iPhone App?

I would like to add some more suggestions based on my most recent implementation. I've looked at some code from Apple and I think my code behaves in much the same way.

The posts above already explain how to create NSError objects and return them, so I won't bother with that part. I'll just try to suggest a good way to integrate errors (codes, messages) in your own app.


I recommend creating 1 header that will be an overview of all the errors of your domain (i.e. app, library, etc..). My current header looks like this:

FSError.h

FOUNDATION_EXPORT NSString *const FSMyAppErrorDomain;

enum {
    FSUserNotLoggedInError = 1000,
    FSUserLogoutFailedError,
    FSProfileParsingFailedError,
    FSProfileBadLoginError,
    FSFNIDParsingFailedError,
};

FSError.m

#import "FSError.h" 

NSString *const FSMyAppErrorDomain = @"com.felis.myapp";

Now when using the above values for errors, Apple will create some basic standard error message for your app. An error could be created like the following:

+ (FSProfileInfo *)profileInfoWithData:(NSData *)data error:(NSError **)error
{
    FSProfileInfo *profileInfo = [[FSProfileInfo alloc] init];
    if (profileInfo)
    {
        /* ... lots of parsing code here ... */

        if (profileInfo.username == nil)
        {
            *error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSProfileParsingFailedError userInfo:nil];            
            return nil;
        }
    }
    return profileInfo;
}

The standard Apple-generated error message (error.localizedDescription) for the above code will look like the following:

Error Domain=com.felis.myapp Code=1002 "The operation couldn’t be completed. (com.felis.myapp error 1002.)"

The above is already quite helpful for a developer, since the message displays the domain where the error occured and the corresponding error code. End users will have no clue what error code 1002 means though, so now we need to implement some nice messages for each code.

For the error messages we have to keep localisation in mind (even if we don't implement localized messages right away). I've used the following approach in my current project:


1) create a strings file that will contain the errors. Strings files are easily localizable. The file could look like the following:

FSError.strings

"1000" = "User not logged in.";
"1001" = "Logout failed.";
"1002" = "Parser failed.";
"1003" = "Incorrect username or password.";
"1004" = "Failed to parse FNID."

2) Add macros to convert integer codes to localized error messages. I've used 2 macros in my Constants+Macros.h file. I always include this file in the prefix header (MyApp-Prefix.pch) for convenience.

Constants+Macros.h

// error handling ...

#define FS_ERROR_KEY(code)                    [NSString stringWithFormat:@"%d", code]
#define FS_ERROR_LOCALIZED_DESCRIPTION(code)  NSLocalizedStringFromTable(FS_ERROR_KEY(code), @"FSError", nil)

3) Now it's easy to show a user friendly error message based on an error code. An example:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
            message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code) 
            delegate:nil 
            cancelButtonTitle:@"OK" 
            otherButtonTitles:nil];
[alert show];

Codeigniter $this->input->post() empty while $_POST is working correctly

Try This, change

$config['base_url'] = 'http://mywebsite.cl/';

to

$config['base_url'] = 'http://www.mywebsite.cl/';

Some provider auto add www , https , etc to your url, most of the times, this causes this issue

Inline JavaScript onclick function

This isn't really recommended, but you can do it all inline like so:

<a href="#" onClick="function test(){ /* Do something */  } test(); return false;"></a>

But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick.

How to create the most compact mapping n ? isprime(n) up to a limit N?

You could try something like this.

def main():
    try:
        user_in = int(input("Enter a number to determine whether the number is prime or not: "))
    except ValueError:
        print()
        print("You must enter a number!")
        print()
        return
    list_range = list(range(2,user_in+1))
    divisor_list = []
    for number in list_range:
        if user_in%number==0:
            divisor_list.append(number)
    if len(divisor_list) < 2:
        print(user_in, "is a prime number!")
        return
    else:
        print(user_in, "is not a prime number!")
        return
main()

ImportError: No module named pip

On Mac using brew is a better option as apt-get is not available. Command:

brew install python

In case you have both python2 & python3 installed on machine

python2.7 -m ensurepip --default-pip

simply should solve the issue.

If instead you are missing pip from python 3 then simply change python2.7 to python3 in the command above.

Convert date to datetime in Python

Today being 2016, I think the cleanest solution is provided by pandas Timestamp:

from datetime import date
import pandas as pd
d = date.today()
pd.Timestamp(d)

Timestamp is the pandas equivalent of datetime and is interchangable with it in most cases. Check:

from datetime import datetime
isinstance(pd.Timestamp(d), datetime)

But in case you really want a vanilla datetime, you can still do:

pd.Timestamp(d).to_datetime()

Timestamps are a lot more powerful than datetimes, amongst others when dealing with timezones. Actually, Timestamps are so powerful that it's a pity they are so poorly documented...

simple vba code gives me run time error 91 object variable or with block not set

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

How to download/checkout a project from Google Code in Windows?

Thanks Mr. Tom Chantler adding that to get the exe http://downloadsvn.codeplex.com/ to pull the SVN source

just note that suppose you're downloading the below project: you have to enter exactly the following to donwload it in the exe URL:

http://myproject.googlecode.com/svn/trunk/

developer not taking care of appending the h t t p : / / if it does not exist. Hope it saves somebody's time.

Enable vertical scrolling on textarea

Here's your CSS

element{
  width: 200px;
  height: 300px;
  overflow-y: auto;
}

Enzyme - How to access and set <input> value?

here is my code..

const input = MobileNumberComponent.find('input')
// when
input.props().onChange({target: {
   id: 'mobile-no',
   value: '1234567900'
}});
MobileNumberComponent.update()
const Footer = (loginComponent.find('Footer'))
expect(Footer.find('Buttons').props().disabled).equals(false)

I have update my DOM with componentname.update() And then checking submit button validation(disable/enable) with length 10 digit.

How to Compare two Arrays are Equal using Javascript?

A less robust approach, but it works.

a = [2, 4, 5].toString();
b = [2, 4, 5].toString();

console.log(a===b);

Check that a variable is a number in UNIX shell

In either ksh93 or bash with the extglob option enabled:

if [[ $var == +([0-9]) ]]; then ...

How to set selected value from Combobox?

try this

combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

Stop and Start a service via batch or cmd file?

Syntax always gets me.... so...

Here is explicitly how to add a line to a batch file that will kill a remote service (on another machine) if you are an admin on both machines, run the .bat as an administrator, and the machines are on the same domain. The machine name follows the UNC format \myserver

sc \\ip.ip.ip.ip stop p4_1

In this case... p4_1 was both the Service Name and the Display Name, when you view the Properties for the service in Service Manager. You must use the Service Name.

For your Service Ops junkies... be sure to append your reason code and comment! i.e. '4' which equals 'Planned' and comment 'Stopping server for maintenance'

sc \\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance

Split string into strings by length?

And for dudes who prefer it to be a bit more readable:

def itersplit_into_x_chunks(string,x=10): # we assume here that x is an int and > 0
    size = len(string)
    chunksize = size//x
    for pos in range(0, size, chunksize):
        yield string[pos:pos+chunksize]

output:

>>> list(itersplit_into_x_chunks('qwertyui',x=4))
['qw', 'er', 'ty', 'ui']

Difference between JSON.stringify and JSON.parse

JSON.parse() is for "parsing" something that was received as JSON.
JSON.stringify() is to create a JSON string out of an object/array.

Laravel 5.2 not reading env file

I ran into this same problem on my local, and I have tried all the answers here but to no avail. Only this worked for me, php artisan config:clear and restart server. Works like a charm!

How to resize an Image C#

Resize and save an image to fit under width and height like a canvas keeping image proportional

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace Infra.Files
{
    public static class GenerateThumb
    {
        /// <summary>
        /// Resize and save an image to fit under width and height like a canvas keeping things proportional
        /// </summary>
        /// <param name="originalImagePath"></param>
        /// <param name="thumbImagePath"></param>
        /// <param name="newWidth"></param>
        /// <param name="newHeight"></param>
        public static void GenerateThumbImage(string originalImagePath, string thumbImagePath, int newWidth, int newHeight)
        {
            Bitmap srcBmp = new Bitmap(originalImagePath);
            float ratio = 1;
            float minSize = Math.Min(newHeight, newHeight);

            if (srcBmp.Width > srcBmp.Height)
            {
                ratio = minSize / (float)srcBmp.Width;
            }
            else
            {
                ratio = minSize / (float)srcBmp.Height;
            }

            SizeF newSize = new SizeF(srcBmp.Width * ratio, srcBmp.Height * ratio);
            Bitmap target = new Bitmap((int)newSize.Width, (int)newSize.Height);

            using (Graphics graphics = Graphics.FromImage(target))
            {
                graphics.CompositingQuality = CompositingQuality.HighSpeed;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    target.Save(thumbImagePath);
                }
            }
        }
    }
}

ASP.NET Web Api: The requested resource does not support http method 'GET'

Have the same Setup as OP. One controller with many actions... less "messy" :-)

In my case i forgot the "[HttpGet]" when adding a new action.

[HttpGet]
public IEnumerable<string> TestApiCall()
{
    return new string[] { "aa", "bb" };
}

Line break in SSRS expression

Use the vbcrlf for new line in SSSR. e.g.

= First(Fields!SAPName.Value, "DataSet1") & vbcrlf & First(Fields!SAPStreet.Value, "DataSet1") & vbcrlf & First(Fields!SAPCityPostal.Value, "DataSet1") & vbcrlf & First(Fields!SAPCountry.Value, "DataSet1") 

Text not wrapping in p tag

The solutions is in fact

p{
    white-space:normal;
}

You can change the break behaviors by modifying, word-break property

p{
    word-break: break-all; // will break at end of line 
}

break-all: Will break the string at the very end, breaking at the last word word-break: is more of pretty brake, will break nicely for example at ? point normal: same as word-break

Replacing Numpy elements if condition is met

The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):

import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)

which will produce:

a: [[1 4 0 1]
 [1 3 2 4]
 [1 0 2 1]
 [3 1 0 0]
 [1 4 0 1]]

b: [[0 1 0 0]
 [0 1 0 1]
 [0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]]

Preferred method to store PHP arrays (json_encode vs serialize)

You might also be interested in https://github.com/phadej/igbinary - which provides a different serialization 'engine' for PHP.

My random/arbitrary 'performance' figures, using PHP 5.3.5 on a 64bit platform show :

JSON :

  • JSON encoded in 2.180496931076 seconds
  • JSON decoded in 9.8368630409241 seconds
  • serialized "String" size : 13993

Native PHP :

  • PHP serialized in 2.9125759601593 seconds
  • PHP unserialized in 6.4348418712616 seconds
  • serialized "String" size : 20769

Igbinary :

  • WIN igbinary serialized in 1.6099879741669 seconds
  • WIN igbinrary unserialized in 4.7737920284271 seconds
  • WIN serialized "String" Size : 4467

So, it's quicker to igbinary_serialize() and igbinary_unserialize() and uses less disk space.

I used the fillArray(0, 3) code as above, but made the array keys longer strings.

igbinary can store the same data types as PHP's native serialize can (So no problem with objects etc) and you can tell PHP5.3 to use it for session handling if you so wish.

See also http://ilia.ws/files/zendcon_2010_hidden_features.pdf - specifically slides 14/15/16

How do I turn a python datetime into a string, with readable format date?

Using f-strings, in Python 3.6+.

from datetime import datetime

date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'

Python, Matplotlib, subplot: How to set the axis range?

Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes or AxesSubplot object. The functions of interest are set_autoscale_on, set_autoscalex_on, and set_autoscaley_on.

In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on property to False. Here is a modified version of the FFT subplot snippet from your code:

fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

ActionLink htmlAttributes

@Html.ActionLink("display name", "action", "Contorller"
    new { id = 1 },Html Attribute=new {Attribute1="value"})

How to create an infinite loop in Windows batch file?

Unlimited loop in one-line command for use in cmd windows:

FOR /L %N IN () DO @echo Oops

enter image description here

Getting the Facebook like/share count for a given URL

UPDATE: This solution is no longer valid. FQLs are deprecated since August 7th, 2016.


https://api.facebook.com/method/fql.query?query=select%20%20like_count%20from%20link_stat%20where%20url=%22http://www.techlila.com%22

Also http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.techlila.com will show you all the data like 'Share Count', 'Like Count' and 'Comment Count' and total of all these.

Change the URL (i.e. http://www.techlila.com) as per your need.

This is the correct URL, I'm getting right results.

EDIT (May 2017): as of v2.9 you can make a graph API call where ID is the URL and select the 'engagement' field, below is a link with the example from the graph explorer.

https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%3A%2F%2Fcomunidade.edp.pt%26fields%3Dengagement&version=v2.9

List of Timezone IDs for use with FindTimeZoneById() in C#?

var timeZoneInfos = TimeZoneInfo.GetSystemTimeZones();

The above gives you a list of timezones, which includes the ids.

Selecting with complex criteria from pandas.DataFrame

Sure! Setup:

>>> import pandas as pd
>>> from random import randint
>>> df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
                   'B': [randint(1, 9)*10 for x in range(10)],
                   'C': [randint(1, 9)*100 for x in range(10)]})
>>> df
   A   B    C
0  9  40  300
1  9  70  700
2  5  70  900
3  8  80  900
4  7  50  200
5  9  30  900
6  2  80  700
7  2  80  400
8  5  80  300
9  7  70  800

We can apply column operations and get boolean Series objects:

>>> df["B"] > 50
0    False
1     True
2     True
3     True
4    False
5    False
6     True
7     True
8     True
9     True
Name: B
>>> (df["B"] > 50) & (df["C"] == 900)
0    False
1    False
2     True
3     True
4    False
5    False
6    False
7    False
8    False
9    False

[Update, to switch to new-style .loc]:

And then we can use these to index into the object. For read access, you can chain indices:

>>> df["A"][(df["B"] > 50) & (df["C"] == 900)]
2    5
3    8
Name: A, dtype: int64

but you can get yourself into trouble because of the difference between a view and a copy doing this for write access. You can use .loc instead:

>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"]
2    5
3    8
Name: A, dtype: int64
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"].values
array([5, 8], dtype=int64)
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"] *= 1000
>>> df
      A   B    C
0     9  40  300
1     9  70  700
2  5000  70  900
3  8000  80  900
4     7  50  200
5     9  30  900
6     2  80  700
7     2  80  400
8     5  80  300
9     7  70  800

Note that I accidentally typed == 900 and not != 900, or ~(df["C"] == 900), but I'm too lazy to fix it. Exercise for the reader. :^)

Watch multiple $scope attributes

how about:

scope.$watch(function() { 
   return { 
      a: thing-one, 
      b: thing-two, 
      c: red-fish, 
      d: blue-fish 
   }; 
}, listener...);

Rounding a variable to two decimal places C#

You can round the result and use string.Format to set the precision like this:

decimal pay = 200.5555m;
pay = Math.Round(pay + bonus, 2);
string payAsString = string.Format("{0:0.00}", pay);

How to run the sftp command with a password from Bash script?

I was recently asked to switch over from ftp to sftp, in order to secure the file transmission between servers. We are using Tectia SSH package, which has an option --password to pass the password on the command line.

example : sftp --password="password" "userid"@"servername"

Batch example :

(
  echo "
  ascii
  cd pub
  lcd dir_name
  put filename
  close
  quit
    "
) | sftp --password="password" "userid"@"servername"

I thought I should share this information, since I was looking at various websites, before running the help command (sftp -h), and was i surprised to see the password option.

How can I add an image file into json object?

public class UploadToServer extends Activity {

TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;

String upLoadServerUri = null;

/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "Quotes.jpg";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_to_server);

    uploadButton = (Button) findViewById(R.id.uploadButton);
    messageText = (TextView) findViewById(R.id.messageText);

    messageText.setText("Uploading file path :- '/mnt/sdcard/"
            + uploadFileName + "'");

    /************* Php script path ****************/
    upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php";

    uploadButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(UploadToServer.this, "",
                    "Uploading file...", true);

            new Thread(new Runnable() {
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            messageText.setText("uploading started.....");
                        }
                    });

                    uploadFile(uploadFilePath + "" + uploadFileName);

                }
            }).start();
        }
    });
}

public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection connection = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + uploadFilePath + ""
                + uploadFileName);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :"
                        + uploadFilePath + "" + uploadFileName);
            }
        });

        return 0;

    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true); // Allow Inputs
            connection.setDoOutput(true); // Allow Outputs
            connection.setUseCaches(false); // Don't use a Cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(connection.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            // dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
            // + fileName + "\"" + lineEnd);
            dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                    + URLEncoder.encode(fileName, "UTF-8") + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {

                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                + " http://www.androidexample.com/media/uploads/"
                                + uploadFileName;

                        messageText.setText(msg);
                        Toast.makeText(UploadToServer.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadToServer.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(UploadToServer.this,
                            "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

PHP FILE

<?php
$target_path  = "./Upload/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
 echo "There was an error uploading the file, please try again!";
}
?>

Safest way to run BAT file from Powershell script

Try this, your dot source was a little off. Edit, adding lastexitcode bits for OP.

$A = Start-Process -FilePath .\my-app\my-fle.bat -Wait -passthru;$a.ExitCode

add -WindowStyle Hidden for invisible batch.

How to create an empty R vector to add new items

You can create an empty vector like so

vec <- numeric(0)

And then add elements using c()

vec <- c(vec, 1:5)

However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements)

How to print / echo environment variables?

The syntax

variable=value command

is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:

a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'

The result will be 5 for the first echo and 3 for the second.

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

"Couldn't read dependencies" error with npm

I resolved that problem just moving my project from E: to C:. I think it happened becouse nodejs and npm was installed in my C: and the project was in my E:

Understanding PIVOT function in T-SQL

To set Compatibility error

use this before using pivot function

ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100  

curl posting with header application/x-www-form-urlencoded

 $curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL => "http://example.com",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "value1=111&value2=222",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"
            ),
        ));
 $response = curl_exec($curl);
 $err = curl_error($curl);

 curl_close($curl);

 if (!$err)
 {
      var_dump($response);
 }

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

EC2 Instance Cloning

The easier way is through the web management console:

  1. go to the instance
  2. select the instance and click on instance action
  3. create image

Once you have an image you can launch another cloned instance, data and all. :)

What is the difference between HTTP status code 200 (cache) vs status code 304?

This threw me for a long time too. The first thing I'd verify is that you're not reloading the page by clicking the refresh button, that will always issue a conditional request for resources and will return 304s for many of the page elements. Instead go up to the url bar select the page and hit enter as if you had just typed in the same URL again, that will give you a better indicator of what's being cached properly. This article does a great job explaining the difference between conditional and unconditional requests and how the refresh button affects them: http://blogs.msdn.com/b/ieinternals/archive/2010/07/08/technical-information-about-conditional-http-requests-and-the-refresh-button.aspx

Removing an element from an Array (Java)

You could use commons lang's ArrayUtils.

array = ArrayUtils.removeElement(array, element)

commons.apache.org library:Javadocs

How often should you use git-gc?

Note that the downside of garbage-collecting your repository is that, well, the garbage gets collected. As we all know as computer users, files we consider garbage right now might turn out to be very valuable three days in the future. The fact that git keeps most of its debris around has saved my bacon several times – by browsing all the dangling commits, I have recovered much work that I had accidentally canned.

So don’t be too much of a neat freak in your private clones. There’s little need for it.

OTOH, the value of data recoverability is questionable for repos used mainly as remotes, eg. the place all the devs push to and/or pulled from. There, it might be sensible to kick off a GC run and a repacking frequently.

How to create streams from string in Node.Js?

Another solution is passing the read function to the constructor of Readable (cf doc stream readeable options)

var s = new Readable({read(size) {
    this.push("your string here")
    this.push(null)
  }});

you can after use s.pipe for exemple

How do I install the babel-polyfill library?

For Babel version 7, if your are using @babel/preset-env, to include polyfill all you have to do is add a flag 'useBuiltIns' with the value of 'usage' in your babel configuration. There is no need to require or import polyfill at the entry point of your App.

With this flag specified, babel@7 will optimize and only include the polyfills you needs.

To use this flag, after installation:

npm install --save-dev  @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill

Simply add the flag:

useBuiltIns: "usage" 

to your babel configuration file called "babel.config.js" (also new to Babel@7), under the "@babel/env" section:

// file: babel.config.js

module.exports = () => {
   const presets = [
      [
         "@babel/env", 
         { 
             targets: { /* your targeted browser */ },
             useBuiltIns: "usage"  // <-----------------*** add this
         }
      ]
   ];

   return { presets };
};

Reference:


Update Aug 2019:

With the release of Babel 7.4.0 (March 19, 2019) @babel/polyfill is deprecated. Instead of installing @babe/polyfill, you will install core-js:

npm install --save core-js@3

A new entry corejs is added to your babel.config.js

// file: babel.config.js

module.exports = () => {
   const presets = [
      [
         "@babel/env", 
         { 
             targets: { /* your targeted browser */ },
             useBuiltIns: "usage",
             corejs: 3  // <----- specify version of corejs used
         }
      ]
   ];

   return { presets };
};

see example: https://github.com/ApolloTang/stackoverflow-eg--babel-v7.4.0-polyfill-w-core-v3

Reference:

Java: How to insert CLOB into oracle database

The easiest way is to simply use the

stmt.setString(position, xml);

methods (for "small" strings which can be easily kept in Java memory), or

try {
  java.sql.Clob clob = 
    oracle.sql.CLOB.createTemporary(
      connection, false, oracle.sql.CLOB.DURATION_SESSION);

  clob.setString(1, xml);
  stmt.setClob(position, clob);
  stmt.execute();
}

// Important!
finally {
  clob.free();
}

Python Web Crawlers and "getting" html source code

Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).

I recommend you using the stdlib module urllib2, it will allow you to comfortably get web resources. Example:

import urllib2

response = urllib2.urlopen("http://google.de")
page_source = response.read()

For parsing the code, have a look at BeautifulSoup.

BTW: what exactly do you want to do:

Just for background, I need to download a page and replace any img with ones I have

Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests is a very nice high-level library which is easier to use than urllib2.

jQuery prevent change for select

_x000D_
_x000D_
$('#my_select').bind('mousedown', function (event) {_x000D_
         event.preventDefault();_x000D_
         event.stopImmediatePropagation();_x000D_
     });
_x000D_
_x000D_
_x000D_

How do I run a VBScript in 32-bit mode on a 64-bit machine?

We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"

Get cookie by name

It seems to me you could split the cookie key-value pairs into an array and base your search on that:

var obligations = getCookieData("obligations");

Which runs the following:

function getCookieData( name ) {
    var pairs = document.cookie.split("; "),
        count = pairs.length, parts; 
    while ( count-- ) {
        parts = pairs[count].split("=");
        if ( parts[0] === name )
            return parts[1];
    }
    return false;
}

Fiddle: http://jsfiddle.net/qFmPc/

Or possibly even the following:

function getCookieData( name ) {
    var patrn = new RegExp( "^" + name + "=(.*?);" ),
        patr2 = new RegExp( " " + name + "=(.*?);" );
    if ( match = (document.cookie.match(patrn) || document.cookie.match(patr2)) )
        return match[1];
    return false;
}

MongoDB relationships: embed or reference?

In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

What is the use of printStackTrace() method in Java?

printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.

The following is an another example of print stack of the Exception in Java.

public class Demo {
   public static void main(String[] args) {
      try {
         ExceptionFunc();
      } catch(Throwable e) {
         e.printStackTrace();
      }
   }
   public static void ExceptionFunc() throws Throwable {
      Throwable t = new Throwable("This is new Exception in Java...");

      StackTraceElement[] trace = new StackTraceElement[] {
         new StackTraceElement("ClassName","methodName","fileName",5)
      };
      t.setStackTrace(trace);
      throw t;
   }
}

java.lang.Throwable: This is new Exception in Java... at ClassName.methodName(fileName:5)

How to hide underbar in EditText

You can set the EditText to have a custom transparent drawable or just use

android:background="@android:color/transparent"

or

android:background="@null"

or Programmatically

editText.setBackgroundResource(android.R.color.transparent);

How can I export tables to Excel from a webpage

Far and away, the cleanest, easiest export from tables to Excel is Jquery DataTables Table Tools plugin. You get a grid that sorts, filters, orders, and pages your data, and with just a few extra lines of code and two small files included, you get export to Excel, PDF, CSV, to clipboard and to the printer.

This is all the code that's required:

  $(document).ready( function () {
    $('#example').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "sSwfPath": "/swf/copy_cvs_xls_pdf.swf"
        }
    } );
} );

So, quick to deploy, no browser limitations, no server-side language required, and most of all very EASY to understand. It's a win-win. The one thing it does have limits on, though, is strict formatting of columns.

If formatting and colors are absolute dealbreakers, the only 100% reliable, cross browser method I've found is to use a server-side language to process proper Excel files from your code. My solution of choice is PHPExcel It is the only one I've found so far that positively handles export with formatting to a MODERN version of Excel from any browser when you give it nothing but HTML. Let me clarify though, it's definitely not as easy as the first solution, and also is a bit of a resource hog. However, on the plus side it also can output direct to PDF as well. And, once you get it configured, it just works, every time.

UPDATE - September 15, 2016: TableTools has been discontinued in favor of a new plugin called "buttons" These tools perform the same functions as the old TableTools extension, but are FAR easier to install and they make use of HTML5 downloads for modern browsers, with the capability to fallback to the original Flash download for browsers that don't support the HTML5 standard. As you can see from the many comments since I posted this response in 2011, the main weakness of TableTools has been addressed. I still can't recommend DataTables enough for handling large amounts of data simply, both for the developer and the user.

React Js conditionally applying class attributes

In case you will need only one optional class name:

<div className={"btn-group pull-right " + (this.props.showBulkActions ? "show" : "")}>

How to use Elasticsearch with MongoDB?

Since mongo-connector now appears dead, my company decided to build a tool for using Mongo change streams to output to Elasticsearch.

Our initial results look promising. You can check it out at https://github.com/electionsexperts/mongo-stream. We're still early in development, and would welcome suggestions or contributions.

Different ways of adding to Dictionary

Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.

I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.

The dict[key] = value represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.

ffprobe or avprobe not found. Please install one

brew install ffmpeg will install what you need and all the dependencies if you are on a Mac.

LINQ's Distinct() on a particular property

When we faced such a task in our project we defined a small API to compose comparators.

So, the use case was like this:

var wordComparer = KeyEqualityComparer.Null<Word>().
    ThenBy(item => item.Text).
    ThenBy(item => item.LangID);
...
source.Select(...).Distinct(wordComparer);

And API itself looks like this:

using System;
using System.Collections;
using System.Collections.Generic;

public static class KeyEqualityComparer
{
    public static IEqualityComparer<T> Null<T>()
    {
        return null;
    }

    public static IEqualityComparer<T> EqualityComparerBy<T, K>(
        this IEnumerable<T> source,
        Func<T, K> keyFunc)
    {
        return new KeyEqualityComparer<T, K>(keyFunc);
    }

    public static KeyEqualityComparer<T, K> ThenBy<T, K>(
        this IEqualityComparer<T> equalityComparer,
        Func<T, K> keyFunc)
    {
        return new KeyEqualityComparer<T, K>(keyFunc, equalityComparer);
    }
}

public struct KeyEqualityComparer<T, K>: IEqualityComparer<T>
{
    public KeyEqualityComparer(
        Func<T, K> keyFunc,
        IEqualityComparer<T> equalityComparer = null)
    {
        KeyFunc = keyFunc;
        EqualityComparer = equalityComparer;
    }

    public bool Equals(T x, T y)
    {
        return ((EqualityComparer == null) || EqualityComparer.Equals(x, y)) &&
                EqualityComparer<K>.Default.Equals(KeyFunc(x), KeyFunc(y));
    }

    public int GetHashCode(T obj)
    {
        var hash = EqualityComparer<K>.Default.GetHashCode(KeyFunc(obj));

        if (EqualityComparer != null)
        {
            var hash2 = EqualityComparer.GetHashCode(obj);

            hash ^= (hash2 << 5) + hash2;
        }

        return hash;
    }

    public readonly Func<T, K> KeyFunc;
    public readonly IEqualityComparer<T> EqualityComparer;
}

More details is on our site: IEqualityComparer in LINQ.

jQuery/JavaScript to replace broken images

I believe this is what you're after: jQuery.Preload

Here's the example code from the demo, you specify the loading and not found images and you're all set:

jQuery('#images img').preload({
  placeholder:'placeholder.jpg',
  notFound:'notfound.jpg'
});

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

This can be accomplished using only CSS. To change the carousel to a fade transition instead of slide, use one of the following snippets (LESS or standard CSS).

LESS

// Fade transition for carousel items
.carousel {
  .item {
    left: 0 !important;
    .transition(opacity .4s); //adjust timing here
  }
  .carousel-control {
    background-image: none; // remove background gradients on controls
  }
  // Fade controls with items
  .next.left,
  .prev.right {
    opacity: 1;
    z-index: 1;
  }
  .active.left,
  .active.right {
    opacity: 0;
    z-index: 2;
  }
}

Plain CSS:

/* Fade transition for carousel items */
.carousel .item {
    left: 0 !important;
      -webkit-transition: opacity .4s; /*adjust timing here */
         -moz-transition: opacity .4s;
           -o-transition: opacity .4s;
              transition: opacity .4s;
}
.carousel-control {
    background-image: none !important; /* remove background gradients on controls */
}
/* Fade controls with items */
.next.left,
.prev.right {
    opacity: 1;
    z-index: 1;
}
.active.left,
.active.right {
    opacity: 0;
    z-index: 2;
}

How to show soft-keyboard when edittext is focused

call requestFocus() method on editText in onCrete() method of activity() and call clearFocus() method on the same editText when click done in keypad.

How to use a table type in a SELECT FROM statement?

You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.

If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:

-- dummy ITEM table as we don't know what the real ones looks like
create table item(
    item_num number,
    currency varchar2(9)
)
/   

insert into item values(1,'GBP');
insert into item values(2,'AUD');
insert into item values(3,'GBP');
insert into item values(4,'AUD');
insert into item values(5,'CDN');

create package so_5165580 as
    type exch_row is record(
        exch_rt_eur number,
        exch_rt_usd number);
    type exch_tbl is table of exch_row index by varchar2(9);
    exch_rt exch_tbl;
    procedure show_items;
end so_5165580;
/

create package body so_5165580 as
    procedure populate_rates is
        rate exch_row;
    begin
        rate.exch_rt_eur := 0.614394;
        rate.exch_rt_usd := 0.8494;
        exch_rt('GBP') := rate;
        rate.exch_rt_eur := 0.9817;
        rate.exch_rt_usd := 1.3572;
        exch_rt('AUD') := rate;
    end;

    procedure show_items is
        cursor c0 is
            select i.*
            from item i;
    begin
        for r0 in c0 loop
            if exch_rt.exists(r0.currency) then
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' EUR ' || exch_rt(r0.currency).exch_rt_eur
                    || ' USD ' || exch_rt(r0.currency).exch_rt_usd);
            else
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' ** no rates defined **');
            end if;
        end loop;
    end;
begin
    populate_rates;
end so_5165580;
/

So inside your loop, wherever you would have expected to use r0.exch_rt_eur you instead use exch_rt(r0.currency).exch_rt_eur, and the same for USD. Testing from an anonymous block:

begin
    so_5165580.show_items;
end;
/

Item 1 Currency GBP EUR .614394 USD .8494
Item 2 Currency AUD EUR .9817 USD 1.3572
Item 3 Currency GBP EUR .614394 USD .8494
Item 4 Currency AUD EUR .9817 USD 1.3572
Item 5 Currency CDN ** no rates defined **

Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert statement. Assuming EXCH holds exchange rates of other currencies against the Euro, including USD with currency_key=1:

insert into detail_items
with rt as (select c.currency_cd as currency_cd,
        e.exch_rt as exch_rt_eur,
        (e.exch_rt / usd.exch_rt) as exch_rt_usd
    from exch e,
        currency c,
        (select exch_rt from exch where currency_key = 1) usd
    where c.currency_key = e.currency_key)
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

With items valued at 19.99 GBP and 25.00 AUD, you get detail_items:

DOC DOC_CURRENCY NET_VALUE         NET_VALUE_IN_USD  NET_VALUE_IN_EURO
--- ------------ ----------------- ----------------- -----------------
1   GBP          19.99             32.53611          23.53426
2   AUD          25                25.46041          18.41621

If you want the currency stuff to be more re-usable you could create a view:

create view rt as
select c.currency_cd as currency_cd,
    e.exch_rt as exch_rt_eur,
    (e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
    currency c,
    (select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key;

And then insert using values from that:

insert into detail_items
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

Store an array in HashMap

Your life will be much easier if you can save a List as the value instead of an array in that Map.

What is the naming convention in Python for variable and function names?

further to what @JohnTESlade has answered. Google's python style guide has some pretty neat recommendations,

Names to Avoid

  • single character names except for counters or iterators
  • dashes (-) in any package/module name
  • \__double_leading_and_trailing_underscore__ names (reserved by Python)

Naming Convention

  • "Internal" means internal to a module or protected or private within a class.
  • Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from). Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).
  • Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module.
  • Use CapWords for class names, but lower_with_under.py for module names. Although there are many existing modules named CapWords.py, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I write import StringIO or from StringIO import StringIO?")

Guidelines derived from Guido's Recommendations enter image description here

Java: Reading integers from a file into an array

It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?

You could probably fix the code like this

String s = in.readLine();
int i = 0;

while (s != null) {
    // Skip empty lines.
    s = s.trim();
    if (s.length() == 0) {
        continue;
    }

    tall[i] = Integer.parseInt(s); // This is line 19.
    System.out.println(tall[i]);
    s = in.readLine();
    i++;
}

in.close();

Create Excel file in Java

You can use Apache POI for creating native binary xls files.

Or you can use JExcelApi which is another, and somewhat light-weight as far as I can remember, Java library for Excel.

HTML button calling an MVC Controller and Action method

You can use Url.Action to specify generate the url to a controller action, so you could use either of the following:

<form method="post" action="<%: Url.Action("About", "Home") %>">
   <input type="submit" value="Click me to go to /Home/About" />
</form>

or:

<form action="#">
  <input type="submit" onclick="parent.location='<%: Url.Action("About", "Home") %>';return false;" value="Click me to go to /Home/About" />
  <input type="submit" onclick="parent.location='<%: Url.Action("Register", "Account") %>';return false;" value="Click me to go to /Account/Register" />
</form>

How can I dynamically set the position of view in Android?

For anything below Honeycomb (API Level 11) you'll have to use setLayoutParams(...).

If you can limit your support to Honeycomb and up you can use the setX(...), setY(...), setLeft(...), setTop(...), etc.

How to remove all subviews of a view in Swift?

I wrote this extension:

extension UIView {
    func lf_removeAllSubviews() {
        for view in self.subviews {
            view.removeFromSuperview()
        }
    }
}

So that you can use self.view.lf_removeAllSubviews in a UIViewController. I'll put this in the swift version of my https://github.com/superarts/LFramework later, when I have more experience in swift (1 day exp so far, and yes, for API I gave up underscore).

Usage of \b and \r in C

As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.

I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc. enter image description here

Also, I am very curious what is the compiler that you were using. :)

How to install gdb (debugger) in Mac OSX El Capitan?

Once you get the macports version of gdb installed you will need to disable SIP in order to make the proper edits to /System/Library/LaunchDaemons/com.apple.taskgated.plist. To disable SIP, you need to restart in recovery mode and execute the following command:

csrutil disable

Then restart. Then you will need to edit the bottom part of com.apple.taskgated.plist like this:

<array>
        <string>/usr/libexec/taskgated</string>
        <string>-sp</string>
</array>

Then you will have to restart to have the changes take effect. Then you should reenable SIP. The gdb command for the macports install is actually ggdb. You will need to code sign ggdb following the instructions here:

https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html

The only way I have been able to get the code signing to work is by running ggdb with sudo. Good luck!

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

What is the newline character in the C language: \r or \n?

'\r' = carriage return and '\n' = line feed.

In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.

git push >> fatal: no configured push destination

I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.

git add .
git commit -m "some comments"
git push --set-upstream origin master

nodejs send html file to client

Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.

What is the best way to add a value to an array in state

Both of the options you provided are the same. Both of them will still point to the same object in memory and have the same array values. You should treat the state object as immutable as you said, however you need to re-create the array so its pointing to a new object, set the new item, then reset the state. Example:

onChange(event){
    var newArray = this.state.arr.slice();    
    newArray.push("new value");   
    this.setState({arr:newArray})
}

HTML -- two tables side by side

<div style="float: left;margin-right:10px">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>
<div style="float: left">
  <table>
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

Which command in VBA can count the number of characters in a string variable?

Len(word)

Although that's not what your question title asks =)

Using OR & AND in COUNTIFS

One solution is doing the sum:

=SUM(COUNTIFS(A1:A196,{"yes","no"},B1:B196,"agree"))

or know its not the countifs but the sumproduct will do it in one line:

=SUMPRODUCT(((A1:A196={"yes","no"})*(j1:j196="agree")))

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

After seeing

You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

I ran

pip install -U pip

and hit this error

PermissionError: [WinError 5]

I tried again and got

pip install -U pip
ERROR: To modify pip, please run the following command:
c:\python36-32\python.exe -m pip install -U pip

After running that exact command, it worked.

For those promoting the use of virtual environments as a solution to this error, pip and virtualenv must be updated in your main install. Simply put, a virtual environment offers no solution to this problem.

Intersection and union of ArrayLists in Java

One-liners since Java 8

import static java.util.stream.Stream.concat;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

Union if there are no duplicates:

  return concat(a.stream(), b.stream()).collect(toList());

Union and distinct:

  return concat(a.stream(), b.stream()).distinct().collect(toList());

Union and distinct if Collection/Set return type:

  return concat(a.stream(), b.stream()).collect(toSet());

Intersect if no duplicates:

  return a.stream().filter(b::contains).collect(toList());

If collection b is huge and not O(1), then pre-optimize filter performance by adding 1 line before return. Copy to HasSet (import java.util.Set;):

... b = Set.copyOf(b);

Intersect and distinct:

  return a.stream().distinct().filter(b::contains).collect(toList());

How do I order my SQLITE database in descending order, for an android app?

About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html

If you implement this, you will call you data base very efficient.

public class LoadEntitiesActionImp implements LoaderManager.LoaderCallbacks<Cursor> {

   public interface OnLoadEntities {
       void onSuccessLoadEntities(List<Entities> entitiesList);
   }

    private OnLoadEntities onLoadEntities;

    private final Context context;

    private final LoaderManager loaderManager;

    public LoadEntitiesActionImp(Context context, LoaderManager loaderManager) {
        this.context = context;
        this.loaderManager = loaderManager;
    }

    public void setCallback(OnLoadEntities onLoadEntities) {
        this.onLoadEntities = onLoadEntities;
    }

    public void loadEntities() {
        loaderManager.initLoader(LOADER_ID, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(context, YOUR_URI, null, YOUR_SELECTION, YOUR_ARGUMENTS_FOR_SELECTION, YOUR_SORT_ORDER);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

OpenCV - Apply mask to a color image

Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).

This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.

apply mask and get a customized background

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np

# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))

# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)  # mask is only 
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)

# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

Note: It is better to use the opencv methods because they are optimized.

constant pointer vs pointer on a constant value

You may use cdecl utility or its online versions, like https://cdecl.org/

For example:

void (* x)(int (*[])()); is a declare x as pointer to function (array of pointer to function returning int) returning void

Change image in HTML page every few seconds

Best way to swap images with javascript with left vertical clickable thumbnails

SCRIPT FILE: function swapImages() {

    window.onload = function () {
        var img = document.getElementById("img_wrap");
        var imgall = img.getElementsByTagName("img");
        var firstimg = imgall[0]; //first image
        for (var a = 0; a <= imgall.length; a++) {
            setInterval(function () {
                var rand = Math.floor(Math.random() * imgall.length);
                firstimg.src = imgall[rand].src;
            }, 3000);



            imgall[1].onmouseover = function () {
                 //alert("what");
                clearInterval();
                firstimg.src = imgall[1].src;


            }
            imgall[2].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[2].src;
            }
            imgall[3].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[3].src;
            }
            imgall[4].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[4].src;
            }
            imgall[5].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[5].src;
            }
        }

    }


}

Initializing entire 2D array with one value

Note that GCC has an extension to the designated initializer notation which is very useful for the context. It is also allowed by clang without comment (in part because it tries to be compatible with GCC).

The extension notation allows you to use ... to designate a range of elements to be initialized with the following value. For example:

#include <stdio.h>

enum { ROW = 5, COLUMN = 10 };

int array[ROW][COLUMN] = { [0 ... ROW-1] = { [0 ... COLUMN-1] = 1 } };

int main(void)
{
    for (int i = 0; i < ROW; i++)
    {
        for (int j = 0; j < COLUMN; j++)
            printf("%2d", array[i][j]);
        putchar('\n');
    }
    return 0;
}

The output is, unsurprisingly:

 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1

Note that Fortran 66 (Fortran IV) had repeat counts for initializers for arrays; it's always struck me as odd that C didn't get them when designated initializers were added to the language. And Pascal uses the 0..9 notation to designate the range from 0 to 9 inclusive, but C doesn't use .. as a token, so it is not surprising that was not used.

Note that the spaces around the ... notation are essentially mandatory; if they're attached to numbers, then the number is interpreted as a floating point number. For example, 0...9 would be tokenized as 0., ., .9, and floating point numbers aren't allowed as array subscripts. With the named constants, ...ROW-1 would not cause trouble, but it is better to get into the safe habits.


Addenda:

I note in passing that GCC 7.3.0 rejects:

int array[ROW][COLUMN] = { [0 ... ROW-1] = { [0 ... COLUMN-1] = { 1 } } };

where there's an extra set of braces around the scalar initializer 1 (error: braces around scalar initializer [-Werror]). I'm not sure that's correct given that you can normally specify braces around a scalar in int a = { 1 };, which is explicitly allowed by the standard. I'm not certain it's incorrect, either.

I also wonder if a better notation would be [0]...[9] — that is unambiguous, cannot be confused with any other valid syntax, and avoids confusion with floating point numbers.

int array[ROW][COLUMN] = { [0]...[4] = { [0]...[9] = 1 } };

Maybe the standards committee would consider that?

Display a decimal in scientific notation

This worked best for me:

import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10

JavaScript moving element in the DOM

var swap = function () {
    var divs = document.getElementsByTagName('div');
    var div1 = divs[0];
    var div2 = divs[1];
    var div3 = divs[2];

    div3.parentNode.insertBefore(div1, div3);
    div1.parentNode.insertBefore(div3, div2);
};

This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.

What standards peculiarities does it rely on?

insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.

Play an audio file using jQuery when a button is clicked

I here have a nice and versatile solution with a fallback:

<script type="text/javascript">
    var audiotypes={
        "mp3": "audio/mpeg",
        "mp4": "audio/mp4",
        "ogg": "audio/ogg",
        "wav": "audio/wav"
    }

    function ss_soundbits(sound){
        var audio_element = document.createElement('audio')
        if (audio_element.canPlayType){
            for (var i=0; i<arguments.length; i++){
                var source_element = document.createElement('source')
                source_element.setAttribute('src', arguments[i])
                if (arguments[i].match(/\.(\w+)$/i))
                    source_element.setAttribute('type', audiotypes[RegExp.$1])
                audio_element.appendChild(source_element)
            }
            audio_element.load()
            audio_element.playclip=function(){
                audio_element.pause()
                audio_element.currentTime=0
                audio_element.play()
            }
            return audio_element
        }
    }
</script>

After that you can initialize as many audio as you like:

<script type="text/javascript" >
    var clicksound  = ss_soundbits('your/path/to/click.ogg', "your/path/to/click.mp3");
    var plopsound  = ss_soundbits('your/path/to/plopp.ogg', "your/path/to/plopp.mp3");
</script>

Now you can reach the initialized audio element whereever you like with simple event calls like

onclick="clicksound.playclip()"

onmouseover="plopsound.playclip()"

How to make an "alias" for a long path?

Put the following line in your myscript

set myFold = '~/Files/Scripts/Main'

In the terminal use

source myscript
cd $myFold

Get a json via Http Request in NodeJS

Just tell request that you are using json:true and forget about header and parse

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'GET',
    json:true
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

and the same for post

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'POST',
    json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

How to get a Docker container's IP address from the host

I wrote the following Bash script to get a table of IP addresses from all containers running under docker-compose.

function docker_container_names() {
    docker ps -a --format "{{.Names}}" | xargs
}

# Get the IP address of a particular container
dip() {
    local network
    network='YOUR-NETWORK-HERE'
    docker inspect --format "{{ .NetworkSettings.Networks.$network.IPAddress }}" "$@"
}

dipall() {
    for container_name in $(docker_container_names);
    do
        local container_ip=$(dip $container_name)
        if [[ -n "$container_ip" ]]; then
            echo $(dip $container_name) " $container_name"
        fi
    done | sort -t . -k 3,3n -k 4,4n
}

You should change the variable network to your own network name.

How to compare strings in an "if" statement?

You can't compare array of characters using == operator. You have to use string compare functions. Take a look at Strings (c-faq).

The standard library's strcmp function compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."

javascript cell number validation

Verify this code : It works on change of phone number field in ms crm 2016 form .

function validatePhoneNumber() {

    var mob = Xrm.Page.getAttribute("gen_phone").getValue();
    var length = mob.length;
    if (length < 10 || length > 10) {
        alert("Please Enter 10 Digit Number:");
        Xrm.Page.getAttribute("gen_phone").setValue(null);
        return true;
    }
    if (mob > 31 && (mob < 48 || mob > 57)) {} else {
        alert("Please Enter 10 Digit Number:");
        Xrm.Page.getAttribute("gen_phone").setValue(null);
        return true;
    }
}

Get fragment (value after hash '#') from a URL in php

I found this trick if you insist want the value with PHP. split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP

How to disable button in React.js

I have had a similar problem, turns out we don't need hooks to do these, we can make an conditional render and it will still work fine.

<Button
    type="submit"
    disabled={
        name === "" || email === "" || password === "" ? true : false
    }
    fullWidth
    variant="contained"
    color="primary"
    className={classes.submit}>
    SignUP
</Button>

html <input type="text" /> onchange event not working

try onpropertychange. it only works for IE.

Python: Finding differences between elements of a list

Ok. I think I found the proper solution:

v = [x[0]-x[1] for x in zip(t[1:],t[:-1])]

How to implement a ConfigurationSection with a ConfigurationElementCollection

The previous answer is correct but I'll give you all the code as well.

Your app.config should look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
   </configSections>
   <ServicesSection>
      <Services>
         <add Port="6996" ReportType="File" />
         <add Port="7001" ReportType="Other" />
      </Services>
   </ServicesSection>
</configuration>

Your ServiceConfig and ServiceCollection classes remain unchanged.

You need a new class:

public class ServiceConfigurationSection : ConfigurationSection
{
   [ConfigurationProperty("Services", IsDefaultCollection = false)]
   [ConfigurationCollection(typeof(ServiceCollection),
       AddItemName = "add",
       ClearItemsName = "clear",
       RemoveItemName = "remove")]
   public ServiceCollection Services
   {
      get
      {
         return (ServiceCollection)base["Services"];
      }
   }
}

And that should do the trick. To consume it you can use:

ServiceConfigurationSection serviceConfigSection =
   ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;

ServiceConfig serviceConfig = serviceConfigSection.Services[0];

How to access the last value in a vector?

The xts package provides a last function:

library(xts)
a <- 1:100
last(a)
[1] 100

What is the best way to conditionally apply attributes in AngularJS?

You can prefix attributes with ng-attr to eval an Angular expression. When the result of the expressions undefined this removes the value from the attribute.

<a ng-attr-href="{{value || undefined}}">Hello World</a>

Will produce (when value is false)

<a ng-attr-href="{{value || undefined}}" href>Hello World</a>

So don't use false because that will produce the word "false" as the value.

<a ng-attr-href="{{value || false}}" href="false">Hello World</a>

When using this trick in a directive. The attributes for the directive will be false if they are missing a value.

For example, the above would be false.

function post($scope, $el, $attr) {
      var url = $attr['href'] || false;
      alert(url === false);
}

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

How to select a single column with Entity Framework?

If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.

var name = dbContext.MyTable.Select(x => new { x.UserId, x.Name }).FirstOrDefault(x => x.UserId == 1)?.Name;

Above query will be converted to this:

Select Top (1) UserId, Name from MyTable where UserId = 1;

For multiple items you can simply chain Select after Where:

var names = dbContext.MyTable.Where(x => x.UserId > 10).Select(x => x.Name);

Use anonymous object inside Select if you need more than one properties.

What is ViewModel in MVC?

View model is same as your datamodel but you can add 2 or more data model classes in it. According to that you have to change your controller to take 2 models at once

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

function getProductionGroupItems($itemId){
     $this->db->select("*");
     $this->db->where("id",$itemId);
     $this->db->or_where("parent_item_id",$itemId);

    /*********** order by *********** */
     $this->db->order_by("id", "asc");

     $q=$this->db->get("recipe_products");
     if($q->num_rows()>0){
         foreach($q->result() as $row){
             $data[]=$row;
         }
         return $data;
     }
    return false;
}

How to combine multiple conditions to subset a data-frame using "OR"?

Just for the sake of completeness, we can use the operators [ and [[:

set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

library(sqldf)
sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

Java ArrayList how to add elements at the beginning

List has the method add(int, E), so you can use:

list.add(0, yourObject);

Afterwards you can delete the last element with:

if(list.size() > 10)
    list.remove(list.size() - 1);

However, you might want to rethink your requirements or use a different data structure, like a Queue

EDIT

Maybe have a look at Apache's CircularFifoQueue:

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

Just initialize it with you maximum size:

CircularFifoQueue queue = new CircularFifoQueue(10);

Pandas percentage of total with groupby

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999)
                         for _ in range(12)]})

grouped = df.groupby(['state', 'office_id'])
100*grouped.sum()/df[["state","sales"]].groupby('state').sum()

Returns:

sales
state   office_id   
AZ  2   54.587910
    4   33.009225
    6   12.402865
CA  1   32.046582
    3   44.937684
    5   23.015735
CO  1   21.099989
    3   31.848658
    5   47.051353
WA  2   43.882790
    4   10.265275
    6   45.851935

Using BigDecimal to work with currencies

I would be radical. No BigDecimal.

Here is a great article https://lemnik.wordpress.com/2011/03/25/bigdecimal-and-your-money/

Ideas from here.

import java.math.BigDecimal;

public class Main {

    public static void main(String[] args) {
        testConstructors();
        testEqualsAndCompare();
        testArithmetic();
    }

    private static void testEqualsAndCompare() {
        final BigDecimal zero = new BigDecimal("0.0");
        final BigDecimal zerozero = new BigDecimal("0.00");

        boolean zerosAreEqual = zero.equals(zerozero);
        boolean zerosAreEqual2 = zerozero.equals(zero);

        System.out.println("zerosAreEqual: " + zerosAreEqual + " " + zerosAreEqual2);

        int zerosCompare = zero.compareTo(zerozero);
        int zerosCompare2 = zerozero.compareTo(zero);
        System.out.println("zerosCompare: " + zerosCompare + " " + zerosCompare2);
    }

    private static void testArithmetic() {
        try {
            BigDecimal value = new BigDecimal(1);
            value = value.divide(new BigDecimal(3));
            System.out.println(value);
        } catch (ArithmeticException e) {
            System.out.println("Failed to devide. " + e.getMessage());
        }
    }

    private static void testConstructors() {
        double doubleValue = 35.7;
        BigDecimal fromDouble = new BigDecimal(doubleValue);
        BigDecimal fromString = new BigDecimal("35.7");

        boolean decimalsEqual = fromDouble.equals(fromString);
        boolean decimalsEqual2 = fromString.equals(fromDouble);

        System.out.println("From double: " + fromDouble);
        System.out.println("decimalsEqual: " + decimalsEqual + " " + decimalsEqual2);
    }
}

It prints

From double: 35.7000000000000028421709430404007434844970703125
decimalsEqual: false false
zerosAreEqual: false false
zerosCompare: 0 0
Failed to devide. Non-terminating decimal expansion; no exact representable decimal result.

How about storing BigDecimal into a database? Hell, it also stores as a double value??? At least, if I use mongoDb without any advanced configuration it will store BigDecimal.TEN as 1E1.

Possible solutions?

I came with one - use String to store BigDecimal in Java as a String into the database. You have validation, for example @NotNull, @Min(10), etc... Then you can use a trigger on update or save to check if current string is a number you need. There are no triggers for mongo though. Is there a built-in way for Mongodb trigger function calls?

There is one drawback I am having fun around - BigDecimal as String in Swagger defenition

I need to generate swagger, so our front-end team understands that I pass them a number presented as a String. DateTime for example presented as a String.

There is another cool solution I read in the article above... Use long to store precise numbers.

A standard long value can store the current value of the Unites States national debt (as cents, not dollars) 6477 times without any overflow. Whats more: it’s an integer type, not a floating point. This makes it easier and accurate to work with, and a guaranteed behavior.


Update

https://stackoverflow.com/a/27978223/4587961

Maybe in the future MongoDb will add support for BigDecimal. https://jira.mongodb.org/browse/SERVER-1393 3.3.8 seems to have this done.

It is an example of the second approach. Use scaling. http://www.technology-ebay.de/the-teams/mobile-de/blog/mapping-bigdecimals-with-morphia-for-mongodb.html

Setting a JPA timestamp column to be generated by the database?

I realize this is a bit late, but I've had success with annotating a timestamp column with

@Column(name="timestamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")

This should also work with CURRENT_DATE and CURRENT_TIME. I'm using JPA/Hibernate with Oracle, so YMMV.

Create a data.frame with m columns and 2 rows

For completeness:

Along the lines of Chase's answer, I usually use as.data.frame to coerce the matrix to a data.frame:

m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))

EDIT: speed test data.frame vs. as.data.frame

system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  8.005   0.108   8.165 

system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  3.759   0.048   3.802 

Yes, it appears to be faster (by about 2 times).

How to express a NOT IN query with ActiveRecord/Rails?

Here is a more complex "not in" query, using a subquery in rails 4 using squeel. Of course very slow compared to the equivalent sql, but hey, it works.

    scope :translations_not_in_english, ->(calmapp_version_id, language_iso_code){
      join_to_cavs_tls_arr(calmapp_version_id).
      joins_to_tl_arr.
      where{ tl1.iso_code == 'en' }.
      where{ cavtl1.calmapp_version_id == my{calmapp_version_id}}.
      where{ dot_key_code << (Translation.
        join_to_cavs_tls_arr(calmapp_version_id).
        joins_to_tl_arr.    
        where{ tl1.iso_code == my{language_iso_code} }.
        select{ "dot_key_code" }.all)}
    }

The first 2 methods in the scope are other scopes which declare the aliases cavtl1 and tl1. << is the not in operator in squeel.

Hope this helps someone.

Call parent method from child class c#

One way to do this would be to pass the instance of ParentClass to the ChildClass on construction

public ChildClass
{
    private ParentClass parent;

    public ChildClass(ParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Make sure to pass the reference to this when constructing ChildClass inside parent:

if(loadData){

     ChildClass childClass = new ChildClass(this); // here

     childClass.LoadData(this.Datatable);

}

Caveat: This is probably not the best way to organise your classes, but it directly answers your question.

EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass. This is possible with the introduction of an interface, eg:

public interface IParentClass
{
    void UpdateProgressBar();
    int CurrentRow{get; set;}
}

Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:

public ChildClass
{
    private IParentClass parent;

    public ChildClass(IParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Now anything that implements IParentClass can construct an instance of ChildClass and pass this to its constructor.

Spring @ContextConfiguration how to put the right location for the xml

We Use:

@ContextConfiguration(locations="file:WebContent/WEB-INF/spitterMVC-servlet.xml")

the project is a eclipse dynamic web project, then the path is:

{project name}/WebContent/WEB-INF/spitterMVC-servlet.xml

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

Convert UTC/GMT time to local time

This code block uses universal time to convert current DateTime object then converts it back to local DateTime. Works perfect for me I hope it helps!

CreatedDate.ToUniversalTime().ToLocalTime();

How to use java.String.format in Scala?

You can use this;

String.format("%1$s %2$s %2$s %3$s", "a", "b", "c");

Output:

a b b c

String comparison - Android

Actually every code runs well here, but your probleme probably come from your gender variable. Did you try to do a simple System.out.println(gender); before the comparaison ?

How to find the process id of a running Java process on Windows? And how to kill the process alone?

This is specific to Windows. I was facing the same issue where I have to kill one specific java program using taskkill. When I run the java program, tasklist was showing the same program with Image name set as java.exe. But killing it using taskkill /F java.exe will stop all other java applications other than intended one which is not required.

So I run the same java program using:

start "MyProgramName" java java-program..

Here start command will open a new window and run the java program with window's title set to MyProgramName.

Now to kill this java-program use the following taskkill command:

taskkill /fi "MyProgramName"

Your Java program will be killed only. Rest will be unaffected.

remove space between paragraph and unordered list

I ended up using a definition list with an unordered list inside it. It solves the issue of the unwanted space above the list without needing to change every paragraph tag.

<dl><dt>Text</dt>
<dd><ul><li>First item</li>
<li>Second item</li></ul></dd></dl>

Is there a way to break a list into columns?

If you are looking for a solution that works in IE as well, you could float the list elements to the left. However, this will result in a list that snakes around, like this:

item 1 | item 2 | item 3
item 4 | item 5

Instead of neat columns, like:

item 1 | item 4
item 2 | 
item 3 | 

The code to do that would be:

ul li {
  width:10em;
  float:left;
}

You could add a border-bottom to the lis to make the flow of the items from left to right more apparent.

How to calculate the sum of the datatable column in asp.net?

Try this

int sum = 0;
foreach (DataRow dr in dt.Rows)
{
     dynamic value = dr[index].ToString();
     if (!string.IsNullOrEmpty(value))
     { 
         sum += Convert.ToInt32(value);
     }
}

Make hibernate ignore class variables that are not mapped

JPA will use all properties of the class, unless you specifically mark them with @Transient:

@Transient
private String agencyName;

The @Column annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length attribute of @Column is only used when auto-generating table definitions, it has no effect on the runtime.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

If you are trying to activate iCloud syncing, you will need to enable iCloud for the AppID that is used to create the development provisioning profile (which Xcode does automatically). You'll also need to enable this for distribution profiles as well.

The tricky part is that when you refresh profiles in Xcode, this does not trigger a renewal of the profiles; they are simply re-downloaded. So in your iOS Provisioning Portal under Provisioning/Development, you'll need to check the profile that is labeled (Managed by Xcode) and delete it (Remove Selected button). Do this for ALL profiles, development & distribution, that you need to regenerate.

Now, in Xcode in the Organizer, delete provisioning profiles that you are about to replace.

Now to get new ones. If you develop for more than one team and only want to refresh a particular one, select the appropriate Team in the left pane under TEAMS, otherwise select Provisioning Profiles under LIBRARY, then select Refresh.

Finally, remove any old provisioning profiles on your device that could conflict with the new ones since profiles are never deleted automatically; newer profiles are simply added to the list.

Fastest method of screen capturing on Windows

DXGI Desktop Capture

Project that captures the desktop image with DXGI duplication. Saves the captured image to the file in different image formats (*.bmp; *.jpg; *.tif).

This sample is written in C++. You also need some experience with DirectX (D3D11, D2D1).

What the Application Can Do

  • If you have more than one desktop monitor, you can choose.
  • Resize the captured desktop image.
  • Choose different scaling modes.
  • You can show or hide the mouse icon in the output image.
  • You can rotate the image for the output picture, or leave it as default.

How do I save a stream to a file in C#?

Why not use a FileStream object?

public void SaveStreamToFile(string fileFullPath, Stream stream)
{
    if (stream.Length == 0) return;

    // Create a FileStream object to write a stream to a file
    using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
    {
        // Fill the bytes[] array with the stream data
        byte[] bytesInStream = new byte[stream.Length];
        stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

        // Use FileStream object to write to the specified file
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
     }
}

How to change spinner text size and text color?

Another variation of Ashraf's solution would be to make sure you're taking into account screen sizes. You'll need to get the spinner in onCreate and set the listener after you set the adapter:

//set your adapter with default or custom spinner cell, then://
serverSpinner.setOnItemSelectedListener(spinnerSelector);
serverSpinner.setSelection(defaultServer);

Then you can start changing the text size of the view that's showing before the spinner is clicked:

private AdapterView.OnItemSelectedListener spinnerSelector = new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
        boolean largeTablet = getResources().getBoolean(R.bool.isLargeTablet);
        if (tabletSize) { ((TextView)parent.getChildAt(0)).setTextSize(16); }
        else if (largeTablet) { ((TextView)parent.getChildAt(0)).setTextSize(18); }
        else { ((TextView)parent.getChildAt(0)).setTextSize(12); }
    }
    public void onNothingSelected(AdapterView<?> parent) {

    }
};

All you need to do is create layout specific folders like this:

values-sw360dp

values-sw600dp

values-sw800dp

an then add an xml file named "bool.xml" into each of those folders:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="isTablet">false</bool>
    <bool name="isLargeTablet">false</bool>
</resources>

Could not find method compile() for arguments Gradle

Wrong gradle file. The right one is build.gradle in your 'app' folder.

Adding elements to a C# array

If you really won't (or can't) use a generic collection instead of your array, Array.Resize is c#'s version of redim preserve:

var  oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

keyCode values for numeric keypad?

For the people that want a CTRL+C, CTRL-V solution, here you go:

    /**
     * Retrieves the number that was pressed on the keyboard.
     *
     * @param {Event} event The keypress event containing the keyCode.
     * @returns {number|null} a number between 0-9 that was pressed. Returns null if there was no numeric key pressed.
     */
    function getNumberFromKeyEvent(event) {
        if (event.keyCode >= 96 && event.keyCode <= 105) {
            return event.keyCode - 96;
        } else if (event.keyCode >= 48 && event.keyCode <= 57) {
            return event.keyCode - 48;
        }
        return null;
    }

It uses the logic of the first answer.

Test if element is present using Selenium WebDriver?

Giving my snippet of code. So, the below method checks if a random web element 'Create New Application' button exists on a page or not. Note that I have used the wait period as 0 seconds.

public boolean isCreateNewApplicationButtonVisible(){
    WebDriverWait zeroWait = new WebDriverWait(driver, 0);
    ExpectedCondition<WebElement> c = ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@value='Create New Application']"));
    try {
        zeroWait.until(c);
        logger.debug("Create New Application button is visible");
        return true;
    } catch (TimeoutException e) {
        logger.debug("Create New Application button is not visible");
        return false;
    }
}

HTML / CSS How to add image icon to input type="button"?

If you're using spritesheets this becomes impossible and the element must be wrapped.

.btn{
    display: inline-block;
    background: blue;
    position: relative;
    border-radius: 5px;
}
.input, .btn:after{
    color: #fff;
}
.btn:after{
    position: absolute;
    content: '@';
    right: 0;
    width: 1.3em;
    height: 1em;
}
.input{
    background: transparent;
    color: #fff;
    border: 0;
    padding-right: 20px;
    cursor: pointer;
    position: relative;
    padding: 5px 20px 5px 5px;
    z-index: 1;
}

Check out this fiddle: http://jsfiddle.net/AJNnZ/

Placing/Overlapping(z-index) a view above another view in android

If you are adding the View programmatically, you can use yourLayout.addView(view, 1);

where 1 is the index.

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

How to get the last character of a string in a shell?

Try:

"${str:$((${#str}-1)):1}"

For e.g.:

someone@mypc:~$ str="A random string*"; echo "$str"
A random string*
someone@mypc:~$ echo "${str:$((${#str}-1)):1}"
*
someone@mypc:~$ echo "${str:$((${#str}-2)):1}"
g

Verify ImageMagick installation

Try this one-shot solution that should figure out where ImageMagick is, if you have access to it...

This found all versions on my Godaddy hosting.

Upload this file to your server and call it ImageMagick.php or something then run it. You will get all the info you need... hopefully...

Good luck.

<?
/*
// This file will run a test on your server to determine the location and versions of ImageMagick. 
//It will look in the most commonly found locations. The last two are where most popular hosts (including "Godaddy") install ImageMagick.
//
// Upload this script to your server and run it for a breakdown of where ImageMagick is.
//
*/
echo '<h2>Test for versions and locations of ImageMagick</h2>';
echo '<b>Path: </b> convert<br>';

function alist ($array) {  //This function prints a text array as an html list.
    $alist = "<ul>";
    for ($i = 0; $i < sizeof($array); $i++) {
        $alist .= "<li>$array[$i]";
    }
    $alist .= "</ul>";
    return $alist;
}

exec("convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"
echo '<br>';
echo '<b>This should test for ImageMagick version 5.x</b><br>';
echo '<b>Path: </b> /usr/bin/convert<br>';

exec("/usr/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version"

echo '<br>';
echo '<b>This should test for ImageMagick version 6.x</b><br>';
echo '<b>Path: </b> /usr/local/bin/convert<br>';

exec("/usr/local/bin/convert -version", $out, $rcode); //Try to get ImageMagick "convert" program version number.
echo "Version return code is $rcode <br>"; //Print the return code: 0 if OK, nonzero if error.
echo alist($out); //Print the output of "convert -version";

?>

Swap two items in List<T>

Check the answer from Marc from C#: Good/best implementation of Swap method.

public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
}

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;
}

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

Can I try/catch a warning?

Normaly you should never use @ unless this is the only solution. In that specific case the function dns_check_record should be use first to know if the record exists.

HTML input arrays

Follow it...

<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3];  // Displaying Selected array Value
foreach ($a as $v) {
    print_r($v); //print all array element.
}
?>

Best way to incorporate Volley (or other library) into Android Studio project

add

compile 'com.mcxiaoke.volley:library:1.0.19'
        compile project('volley')

in the dependencies, under build.gradle file of your app

DO NOT DISTURB THE build.gradle FILE OF YOUR LIBRARY. IT'S YOUR APP'S GRADLE FILE ONLY YOU NEED TO ALTER

PHP/MySQL insert row then get 'id'

Try this... it worked for me!

$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
    if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    $msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    $msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

:last-child not working as expected?

The last-child selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.

The other part of the compound selector (which is attached before the :last-child) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.

_x000D_
_x000D_
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
  background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
  color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <p>Child w/o class</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


To answer your question, the below would style the last child li element with background color as red.

li:last-child{
    background-color: red;
}

But the following selector would not work for your markup because the last-child does not have the class='complete' even though it is an li.

li.complete:last-child{
    background-color: green;
}

It would have worked if (and only if) the last li in your markup also had class='complete'.


To address your query in the comments:

@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.

The selector .complete:first-of-type works in the fiddle because it (that is, the element with class='complete') is still the first element of type li within the parent. Try to add <li>0</li> as the first element under the ul and you will find that first-of-type also flops. This is because the first-of-type and last-of-type selectors select the first/last element of each type under the parent.

Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

cannot connect to pc-name\SQLEXPRESS

Follow these steps then you solve your problem 100%.

  1. When you get this error then close everything(Microsoft SQL Server Managment):

error

  1. Then open command prompt by pressing (window + r) keys and type services.msc and click OK or press Enter key.

  2. And search **SQL Server (SQLEXPRESS) as I show in the image.

enter image description here

  1. Now see left upper side and click start.

  2. If you open Microsoft SQL Server Management then you not get any type error.

Enjoy!!!

C# version of java's synchronized keyword?

static object Lock = new object();

lock (Lock) 
{
// do stuff
}

How do I convert a PDF document to a preview image in PHP?

You need ImageMagick and GhostScript

<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>

The [0] means page 1.

Returning null in a method whose signature says return int?

int is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed.

Nulls are assigned only to reference types, it means the reference doesn't point to anything. Primitives are not reference types, they are values, so they are never set to null.

Using the object wrapper java.lang.Integer as the return value means you are passing back an Object and the object reference can be null.

Populate unique values into a VBA array from Excel

OK I did it finally:

Sub CountUniqueRecords()
Dim Array() as variant, UniqueArray() as variant, UniqueNo as Integer,      
Dim i as integer, j as integer, k as integer

Redim UnquiArray(1)

k= Upbound(array)

For i = 1 To k
For j = 1 To UniqueNo + 1
  If Array(i) = UniqueArray(j) Then GoTo Nx
Next j
  UniqueNo = UniqueNo + 1
  ReDim Preserve UniqueArray(UniqueNo + 1)
  UniqueArray(UniqueNo) = Array(i)
Nx:
Next i

MsgBox UniqueNo

End Sub

How to display line numbers in 'less' (GNU)

You could filter the file through cat -n before piping to less:

cat -n file.txt | less

Or, if your version of less supports it, the -N option:

less -N file.txt

IIS Manager in Windows 10

Thanks to @SLaks comment above I was able to turn on IIS and bring the manager back.

Press the Windows Key and type Windows Features, select the first entry Turn Windows Features On or Off.

Make sure the box next to IIS is checked.

enter image description here

If it is not checked, check it. This might take a few minutes, but this will install everything you need to use IIS.

When it is done, IIS should have returned to Control Panel > Administrative Tools

enter image description here