Programs & Examples On #Autocreate

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

Can I have H2 autocreate a schema in an in-memory database?

Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:

String url = "jdbc:h2:mem:test;" + 
             "INIT=CREATE SCHEMA IF NOT EXISTS TEST"
String url = "jdbc:h2:mem:test;" + 
             "INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" + 
                  "SET SCHEMA TEST";
String url = "jdbc:h2:mem;" + 
             "INIT=RUNSCRIPT FROM '~/create.sql'\\;" + 
                  "RUNSCRIPT FROM '~/populate.sql'";

Please note the double backslash (\\) is only required within Java. The backslash(es) before ; within the INIT is required.

In PHP, how can I add an object element to an array?

Just do:

$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;

You need to create the object first (the new line) and then push it onto the end of the array (the [] line).

You can also do this:

$myArray[] = (object) ['name' => 'My name'];

However I would argue that's not as readable, even if it is more succinct.

Programmatically Add CenterX/CenterY Constraints

In Swift 5 it looks like this:

label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true

How do I add a tool tip to a span element?

Here's the simple, built-in way:

<span title="My tip">text</span>

That gives you plain text tooltips. If you want rich tooltips, with formatted HTML in them, you'll need to use a library to do that. Fortunately there are loads of those.

Angularjs prevent form submission when input validation fails

Your forms are automatically put into $scope as an object. It can be accessed via $scope[formName]

Below is an example that will work with your original setup and without having to pass the form itself as a parameter in ng-submit.

var controller = function($scope) {

    $scope.login = {
        submit: function() {
            if($scope.loginform.$invalid) return false;

        }
    }

};

Working example: http://plnkr.co/edit/BEWnrP?p=preview

Call a Javascript function every 5 seconds continuously

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

How do I prompt a user for confirmation in bash script?

echo are you sure?
read x
if [ "$x" = "yes" ]
then
  # do the dangerous stuff
fi

How do I upload a file with the JS fetch API?

I've done it like this:

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})

How to create a DB for MongoDB container on start up?

In case someone is looking for how to configure MongoDB with authentication using docker-compose, here is a sample configuration using environment variables:

version: "3.3"

services:

  db:
      image: mongo
      environment:
        - MONGO_INITDB_ROOT_USERNAME=admin
        - MONGO_INITDB_ROOT_PASSWORD=<YOUR_PASSWORD>
      ports:
        - "27017:27017"

When running docker-compose up your mongo instance is run automatically with auth enabled. You will have a admin database with the given password.

Pass element ID to Javascript function

In jsFiddle by default the code you type into the script block is wrapped in a function executed on window.onload:

<script type='text/javascript'>//<![CDATA[ 
    window.onload = function () {
        function myFunc(id){
            alert(id);     
        }
    }
//]]>  
</script>

Because of this, your function myFunc is not in the global scope so is not available to your html buttons. By changing the option to No-wrap in <head> as Sergio suggests your code isn't wrapped:

<script type='text/javascript'>//<![CDATA[ 
    function myFunc(id){
       alert(id);     
    }
//]]>  
</script>

and so the function is in the global scope and available to your html buttons.

SQL Server Restore Error - Access is Denied

I ended up making new folders for Data and Logs and it worked properly, must have been a folder/file permission issue.

How do you join on the same table, twice, in mysql?

you'd use another join, something along these lines:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 
    rvw.*

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from

EDIT:

All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

For more info about aliasing in SQL, read here.

Android Button setOnClickListener Design

I think you can usually do what you need in a loop, which is much better than many onClick methods if it can be done.

Check out this answer for a demonstration of how to use a loop for a similar problem. How you construct your loop will depend on the needs of your onClick functions and how similar they are to one another. The end result is much less repetitive code that is easier to maintain.

How to call python script on excel vba?

This code will works:

 your_path= ActiveWorkbook.Path & "\your_python_file.py" 
 Shell "RunDll32.Exe Url.Dll,FileProtocolHandler " & your_path, vbNormalFocus 

ActiveWorkbook.Path return the current directory of the workbook. The shell command open the file through the shell of Windows.

Check if a folder exist in a directory and create them using C#

using System.IO;
...

Directory.CreateDirectory(@"C:\MP_Upload");

Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.

(This also means that all directories along the path are created if needed: CreateDirectory(@"C:\a\b\c\d") suffices, even if C:\a does not exist yet.)


Let me add a word of caution about your choice of directory, though: Creating a folder directly below the system partition root C:\ is frowned upon. Consider letting the user choose a folder or creating a folder in %APPDATA% or %LOCALAPPDATA% instead (use Environment.GetFolderPath for that). The MSDN page of the Environment.SpecialFolder enumeration contains a list of special operating system folders and their purposes.

JavaScript dictionary with names

Try:

var myMappings = {
    "Name":     "10%",
    "Phone":    "10%",
    "Address":  "50%",
    "Zip":      "10%",
    "Comments": "20%"
}

// Access is like this
myMappings["Name"] // Returns "10%"
myMappings.Name // The same thing as above

// To loop through...
for(var title in myMappings) {
    // Do whatever with myMappings[title]
}

java.lang.IllegalStateException: Fragment not attached to Activity

This issue occurs whenever you call a context which is unavailable or null when you call it. This can be a situation when you are calling main activity thread's context on a background thread or background thread's context on main activity thread.

For instance , I updated my shared preference string like following.

editor.putString("penname",penNameEditeText.getText().toString());
editor.commit();
finish();

And called finish() right after it. Now what it does is that as commit runs on main thread and stops any other Async commits if coming until it finishes. So its context is alive until the write is completed. Hence previous context is live , causing the error to occur.

So make sure to have your code rechecked if there is some code having this context issue.

SQL Query - Change date format in query to DD/MM/YYYY

SELECT CONVERT(varchar(11),Getdate(),105)

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

Hibernate is ignorant of time zone stuff in Dates (because there isn't any), but it's actually the JDBC layer that's causing problems. ResultSet.getTimestamp and PreparedStatement.setTimestamp both say in their docs that they transform dates to/from the current JVM timezone by default when reading and writing from/to the database.

I came up with a solution to this in Hibernate 3.5 by subclassing org.hibernate.type.TimestampType that forces these JDBC methods to use UTC instead of the local time zone:

public class UtcTimestampType extends TimestampType {

    private static final long serialVersionUID = 8088663383676984635L;

    private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

    @Override
    public Object get(ResultSet rs, String name) throws SQLException {
        return rs.getTimestamp(name, Calendar.getInstance(UTC));
    }

    @Override
    public void set(PreparedStatement st, Object value, int index) throws SQLException {
        Timestamp ts;
        if(value instanceof Timestamp) {
            ts = (Timestamp) value;
        } else {
            ts = new Timestamp(((java.util.Date) value).getTime());
        }
        st.setTimestamp(index, ts, Calendar.getInstance(UTC));
    }
}

The same thing should be done to fix TimeType and DateType if you use those types. The downside is you'll have to manually specify that these types are to be used instead of the defaults on every Date field in your POJOs (and also breaks pure JPA compatibility), unless someone knows of a more general override method.

UPDATE: Hibernate 3.6 has changed the types API. In 3.6, I wrote a class UtcTimestampTypeDescriptor to implement this.

public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
    public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();

    private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

    public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicBinder<X>( javaTypeDescriptor, this ) {
            @Override
            protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
                st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
            }
        };
    }

    public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicExtractor<X>( javaTypeDescriptor, this ) {
            @Override
            protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
                return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
            }
        };
    }
}

Now when the app starts, if you set TimestampTypeDescriptor.INSTANCE to an instance of UtcTimestampTypeDescriptor, all timestamps will be stored and treated as being in UTC without having to change the annotations on POJOs. [I haven't tested this yet]

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

For one, you can wrap it up in a function:

function manytimes {
    n=0
    times=$1
    shift
    while [[ $n -lt $times ]]; do
        $@
        n=$((n+1))
    done
}

Call it like:

$ manytimes 3 echo "test" | tr 'e' 'E'
tEst
tEst
tEst

How to insert a new key value pair in array in php?

foreach($test_package_data as $key=>$data ) {

   $category_detail_arr = $test_package_data[$key]['category_detail'];

   foreach( $category_detail_arr as $i=>$value ) {
     $test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
   }

}

Abort a git cherry-pick?

Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.

--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.

--abort Cancel the operation and return to the pre-sequence state.

use help to see the original doc with more details, $ git help cherry-pick

I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.

How to pass optional arguments to a method in C++?

Use default parameters

template <typename T>
void func(T a, T b = T()) {

   std::cout << a << b;

}

int main()
{
    func(1,4); // a = 1, b = 4
    func(1);   // a = 1, b = 0

    std::string x = "Hello";
    std::string y = "World";

    func(x,y);  // a = "Hello", b ="World"
    func(x);    // a = "Hello", b = "" 

}

Note : The following are ill-formed

template <typename T>
void func(T a = T(), T b )

template <typename T>
void func(T a, T b = a )

Run Stored Procedure in SQL Developer?

Can't believe, this won't execute in SQL Developer:

var r refcursor;
exec PCK.SOME_SP(:r,
 '02619857');

print r;

BUT this will:

var r refcursor;
exec TAPI_OVLASCENJA.ARH_SELECT_NAKON_PRESTANKA_REG(:r, '02619857');

print r;

Obviously everything has to be in one line..

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

On particular table

_x000D_
_x000D_
<table style="border-collapse: separate; border-spacing: 10px;" >_x000D_
    <tr>_x000D_
      <td>Hi</td>_x000D_
      <td>Hello</td>_x000D_
    <tr/>_x000D_
    <tr>_x000D_
      <td>Hola</td>_x000D_
      <td>Oi!</td>_x000D_
    <tr/>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Matplotlib-Animation "No MovieWriters Available"

I'm running Ubuntu 20 and I had a similar problem

Installed ffmpeg

pip install ffmpeg

then

sudo apt install ffmpeg

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

I've implemented cross-browser compatible page to test browser's refresh behavior (here is the source code) and get results similar to @some, but for modern browsers:

enter image description here

How to use multiple conditions (With AND) in IIF expressions in ssrs

Here is an example that should give you some idea..

=IIF(First(Fields!Gender.Value,"vw_BrgyClearanceNew")="Female" and 
(First(Fields!CivilStatus.Value,"vw_BrgyClearanceNew")="Married"),false,true)

I think you have to identify the datasource name or the table name where your data is coming from.

setting system property

System.setProperty("gate.home", "/some/directory");

For more information, see:

How to 'grep' a continuous stream?

I use the tail -f <file> | grep <pattern> all the time.

It will wait till grep flushes, not till it finishes (I'm using Ubuntu).

How can I list the scheduled jobs running in my database?

I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)

see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

How to run multiple SQL commands in a single SQL connection?

using (var connection = new SqlConnection("Enter Your Connection String"))
    {
        connection.Open();
    
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "Enter the First Command Here";
            command.ExecuteNonQuery();
    
            command.CommandText = "Enter Second Comand Here";
            command.ExecuteNonQuery();

    //Similarly You can Add Multiple
        }
    }

Incompatible implicit declaration of built-in function ‘malloc’

The stdlib.h file contains the header information or prototype of the malloc, calloc, realloc and free functions.

So to avoid this warning in ANSI C, you should include the stdlib header file.

From io.Reader to string in Go

var b bytes.Buffer
b.ReadFrom(r)

// b.String()

.NET Console Application Exit Event

The application is a server which simply runs until the system shuts down or it receives a Ctrl+C or the console window is closed.

Due to the extraordinary nature of the application, it is not feasible to "gracefully" exit. (It may be that I could code another application which would send a "server shutdown" message but that would be overkill for one application and still insufficient for certain circumstances like when the server (Actual OS) is actually shutting down.)

Because of these circumstances I added a "ConsoleCtrlHandler" where I stop my threads and clean up my COM objects etc...


Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As Boolean

Public Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As Boolean

Public Enum CtrlTypes
  CTRL_C_EVENT = 0
  CTRL_BREAK_EVENT
  CTRL_CLOSE_EVENT
  CTRL_LOGOFF_EVENT = 5
  CTRL_SHUTDOWN_EVENT
End Enum

Public Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean
.
.clean up code here
.
End Function

Public Sub Main()
.
.
.
SetConsoleCtrlHandler(New HandlerRoutine(AddressOf ControlHandler), True)
.
.
End Sub

This setup seems to work out perfectly. Here is a link to some C# code for the same thing.

What's in an Eclipse .classpath/.project file?

.project

When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.

.classpath

Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

It sounds like you hit the "Insert" key .. in most applications this results in a fat (solid rectangle) cursor being displayed, as your screenshot suggests. This indicates that you are in overwrite mode rather than the default insert mode.

Just hit the "insert" key on your keyboard once more... it's usually near the 'delete' (not backspace), scroll lock and 'Print Screen' (often above the cursor keys in a full size keyboard.) This will switch back to insert mode and turn your cursor into a vertical line rather than a rectangle.

how to pass list as parameter in function

You need to do it like this,

void Yourfunction(List<DateTime> dates )
{

}

How to close activity and go back to previous activity in android

This closes the entire application:

this.finish();

Vertically aligning CSS :before and :after content

I think a cleaner approach is to inherit the vertical alignment:

In html:

<div class="shortcut"><a href="#">Download</a></div>

And in css:

.shortcut {
    vertical-align: middle;
}
.shortcut > a:after {
    vertical-align: inherit;
{

This way the icon will align properly in any resolution/font-size combination. Great for use with icon fonts.

How to send parameters from a notification-click to an activity?

Please use as PendingIntent while showing notification than it will be resolved.

PendingIntent intent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Add PendingIntent.FLAG_UPDATE_CURRENT as last field.

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

In your css add folllowing

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
    display: none !important;
 }

And then in you code you can add ng-cloak directive. For example,

<div ng-cloak>
   Welcome {{data.name}}
</div>

Thats it!

Jenkins: Cannot define variable in pipeline stage

I think error is not coming from the specified line but from the first 3 lines. Try this instead :

node {
   stage("first") {
     def foo = "foo"
     sh "echo ${foo}"
   }
}

I think you had some extra lines that are not valid...

From declaractive pipeline model documentation, it seems that you have to use an environment declaration block to declare your variables, e.g.:

pipeline {
   environment {
     FOO = "foo"
   }

   agent none
   stages {
       stage("first") {
           sh "echo ${FOO}"
       }
   }
}

Trying to retrieve first 5 characters from string in bash error?

Works here:

$ TESTSTRINGONE="MOTEST"
$ NEWTESTSTRING=${TESTSTRINGONE:0:5}
$ echo ${NEWTESTSTRING}
MOTES

What shell are you using?

How to set null to a GUID property

Since "Guid" is not nullable, use "Guid.Empty" as default value.

Regex: match word that ends with "Id"

Regex ids = new Regex(@"\w*Id\b", RegexOptions.None);

\b means "word break" and \w means any word character. So \w*Id\b means "{stuff}Id". By not including RegexOptions.IgnoreCase, it will be case sensitive.

Make a UIButton programmatically in Swift

Swift "Button factory" extension for UIButton (and while we're at it) also for UILabel like so:

extension UILabel
{
// A simple UILabel factory function
// returns instance of itself configured with the given parameters

// use example (in a UIView or any other class that inherits from UIView):

//   addSubview(   UILabel().make(     x: 0, y: 0, w: 100, h: 30,
//                                   txt: "Hello World!",
//                                 align: .center,
//                                   fnt: aUIFont,
//                              fntColor: UIColor.red)                 )
//

func make(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat,
          txt: String,
          align: NSTextAlignment,
          fnt: UIFont,
          fntColor: UIColor)-> UILabel
{
    frame = CGRect(x: x, y: y, width: w, height: h)
    adjustsFontSizeToFitWidth = true
    textAlignment = align
    text = txt
    textColor = fntColor
    font = fnt
    return self
}
// Of course, you can make more advanced factory functions etc.
// Also one could subclass UILabel, but this seems to be a     convenient case for an extension.
}


extension UIButton
{
// UIButton factory returns instance of UIButton
//usage example:

// addSubview(UIButton().make(x: btnx, y:100, w: btnw, h: btnh,
// title: "play", backColor: .red,
// target: self,
// touchDown: #selector(play), touchUp: #selector(stopPlay)))


func make(   x: CGFloat,y: CGFloat,
             w: CGFloat,h: CGFloat,
                  title: String, backColor: UIColor,
                  target: UIView,
                  touchDown:  Selector,
                  touchUp:    Selector ) -> UIButton
{
    frame = CGRect(x: x, y: y, width: w, height: h)
    backgroundColor = backColor
    setTitle(title, for: .normal)
    addTarget(target, action: touchDown, for: .touchDown)
    addTarget(target, action: touchUp  , for: .touchUpInside)
    addTarget(target, action: touchUp  , for: .touchUpOutside)

    return self
}
}

Tested in Swift in Xcode Version 9.2 (9C40b) Swift 4.x

Please initialize the log4j system properly. While running web service

You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator

public class FooImpl implements Foo {

    private static final Logger LOGGER = Logger.getLogger(FooBar.class);

    public Object createObject() {
        BasicConfigurator.configure();
        LOGGER.info("something");
        return new Object();
    }
}

So under the table, configure do:

  configure() {
    Logger root = Logger.getRootLogger();
    root.addAppender(new ConsoleAppender(
           new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
  }

Java: How to access methods from another class

You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.

1) Give Alphas a Beta in the constructor. In class Alpha write:

public class Alpha {
   private Beta beta;
   public Alpha(Beta beta) {
     this.beta = beta; 
   }

and call cAlpha = new Alpha(cBeta) from main()

2) give Alphas a mutator that gives them a beta. In class Alpha write:

public class Alpha {
   private Beta beta;
   public void setBeta (Beta newBeta) {
     this.beta = beta;
   }

and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or

3) have a beta as an argument to doSomethingAlpha. in class Alpha write:

public void DoSomethingAlpha(Beta cBeta) {
      cbeta.DoSomethingBeta()
}

Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!

MySQL "WITH" clause

   WITH authorRating as (select aname, rating from book)
   SELECT aname, AVG(quantity)
   FROM authorRating
   GROUP BY aname

Difference between Spring MVC and Struts MVC

Spring provides a very clean division between controllers, JavaBean models, and views.

How can I lock a file using java (if possible)

Below is a sample snippet code to lock a file until it's process is done by JVM.

 public static void main(String[] args) throws InterruptedException {
    File file = new File(FILE_FULL_PATH_NAME);
    RandomAccessFile in = null;
    try {
        in = new RandomAccessFile(file, "rw");
        FileLock lock = in.getChannel().lock();
        try {

            while (in.read() != -1) {
                System.out.println(in.readLine());
            }
        } finally {
            lock.release();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

How to remove stop words using nltk or python

To exclude all type of stop-words including nltk stop-words, you could do something like this:

from stop_words import get_stop_words
from nltk.corpus import stopwords

stop_words = list(get_stop_words('en'))         #About 900 stopwords
nltk_words = list(stopwords.words('english')) #About 150 stopwords
stop_words.extend(nltk_words)

output = [w for w in word_list if not w in stop_words]

openpyxl - adjust column width size

This is my version referring @Virako 's code snippet

def adjust_column_width_from_col(ws, min_row, min_col, max_col):

        column_widths = []

        for i, col in \
                enumerate(
                    ws.iter_cols(min_col=min_col, max_col=max_col, min_row=min_row)
                ):

            for cell in col:
                value = cell.value
                if value is not None:

                    if isinstance(value, str) is False:
                        value = str(value)

                    try:
                        column_widths[i] = max(column_widths[i], len(value))
                    except IndexError:
                        column_widths.append(len(value))

        for i, width in enumerate(column_widths):

            col_name = get_column_letter(min_col + i)
            value = column_widths[i] + 2
            ws.column_dimensions[col_name].width = value

And how to use is as follows,

adjust_column_width_from_col(ws, 1,1, ws.max_column)

no module named urllib.parse (How should I install it?)

pip install -U websocket 

I just use this to fix my problem

Populate dropdown select with array using jQuery

The array declaration has incorrect syntax. Try the following, instead:

var numbers = [ 1, 2, 3, 4, 5]

The loop part seems right

$.each(numbers, function(val, text) {
            $('#items').append( $('<option></option>').val(val).html(text) )
            }); // there was also a ) missing here

As @Reigel did seems to add a bit more performance (it is not noticeable on such small arrays)

How can I make a TextBox be a "password box" and display stars when using MVVM?

You can make your TextBox as customed PasswordBox by simply adding the following value to FontFamily property of your TextBox control.

<TextBox
    Text="{Binding Password}"
    FontFamily="ms-appx:///Assets/PassDot.ttf#PassDot"
    FontSize="35"/>

In my case this works perfectly. This will show dot in place of the actual text (not star(*) though).

How to implement an STL-style iterator and avoid common pitfalls?

And now a keys iterator for range-based for loop.

template<typename C>
class keys_it
{
    typename C::const_iterator it_;
public:
    using key_type        = typename C::key_type;
    using pointer         = typename C::key_type*;
    using difference_type = std::ptrdiff_t;

    keys_it(const typename C::const_iterator & it) : it_(it) {}

    keys_it         operator++(int               ) /* postfix */ { return it_++         ; }
    keys_it&        operator++(                  ) /*  prefix */ { ++it_; return *this  ; }
    const key_type& operator* (                  ) const         { return it_->first    ; }
    const key_type& operator->(                  ) const         { return it_->first    ; }
    keys_it         operator+ (difference_type v ) const         { return it_ + v       ; }
    bool            operator==(const keys_it& rhs) const         { return it_ == rhs.it_; }
    bool            operator!=(const keys_it& rhs) const         { return it_ != rhs.it_; }
};

template<typename C>
class keys_impl
{
    const C & c;
public:
    keys_impl(const C & container) : c(container) {}
    const keys_it<C> begin() const { return keys_it<C>(std::begin(c)); }
    const keys_it<C> end  () const { return keys_it<C>(std::end  (c)); }
};

template<typename C>
keys_impl<C> keys(const C & container) { return keys_impl<C>(container); }

Usage:

std::map<std::string,int> my_map;
// fill my_map
for (const std::string & k : keys(my_map))
{
    // do things
}

That's what i was looking for. But nobody had it, it seems.

You get my OCD code alignment as a bonus.

As an exercise, write your own for values(my_map)

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

How should I tackle --secure-file-priv in MySQL?

I'm working on MySQL5.7.11 on Debian, the command that worked for me to see the directory is:

mysql> SELECT @@global.secure_file_priv;

How to Return partial view of another controller by controller?

The control searches for a view in the following order:

  • First in shared folder
  • Then in the folder matching the current controller (in your case it's Views/DEF)

As you do not have xxx.cshtml in those locations, it returns a "view not found" error.

Solution: You can use the complete path of your view:

Like

 PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

Should have subtitle controller already set Mediaplayer error Android

To remove message on logcat, i add a subtitle to track. On windows, right click on track -> Property -> Details -> insert a text on subtitle. Done :)

How to change sa password in SQL Server 2008 express?

I didn't know the existing sa password so this is what I did:

  1. Open Services in Control Panel

  2. Find the "SQL Server (SQLEXPRESS)" entry and select properties

  3. Stop the service

  4. Enter "-m" at the beginning of the "Start parameters" fields. If there are other parameters there already add a semi-colon after -m;

  5. Start the service

  6. Open a Command Prompt

Enter the command:

osql -S YourPcName\SQLEXPRESS -E

(change YourPcName to whatever your PC is called).

  1. At the prompt type the following commands:
alter login sa enable
go
sp_password NULL,'new_password','sa'
go
quit
  1. Stop the "SQL Server (SQLEXPRESS)" service

  2. Remove the "-m" from the Start parameters field

  3. Start the service

this.getClass().getClassLoader().getResource("...") and NullPointerException

tul,

  • When you use .getClass().getResource(fileName) it considers the location of the fileName is the same location of the of the calling class.
  • When you use .getClass().getClassLoader().getResource(fileName) it considers the location of the fileName is the root - in other words bin folder.

Source :

package Sound;
public class ResourceTest {
    public static void main(String[] args) {
        String fileName = "Kalimba.mp3";
        System.out.println(fileName);
        System.out.println(new ResourceTest().getClass().getResource(fileName));
        System.out.println(new ResourceTest().getClass().getClassLoader().getResource(fileName));
    }
}

Output :

Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Sound/Kalimba.mp3
file:/C:/Users/User/Workspaces/MyEclipse%208.5/JMplayer/bin/Kalimba.mp3

How to get < span > value?

You can use querySelectorAll to get all span elements and then use new ES2015 (ES6) spread operator convert StaticNodeList that querySelectorAll returns to array of spans, and then use map operator to get list of items.

See example bellow

_x000D_
_x000D_
([...document.querySelectorAll('#test span')]).map(x => console.log(x.innerHTML))
_x000D_
<div id="test">_x000D_
    <span>1</span>_x000D_
    <span>2</span>_x000D_
    <span>3</span>_x000D_
    <span>4</span>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Update statement using with clause

If anyone comes here after me, this is the answer that worked for me.

NOTE: please make to read the comments before using this, this not complete. The best advice for update queries I can give is to switch to SqlServer ;)

update mytable t
set z = (
  with comp as (
    select b.*, 42 as computed 
    from mytable t 
    where bs_id = 1
  )
  select c.computed
  from  comp c
  where c.id = t.id
)

Good luck,

GJ

Bind service to activity in Android

"If you start an android Service with startService(..) that Service will remain running until you explicitly invoke stopService(..). There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the Service's IBinder). Usually the IBinder returned is for a complex interface that has been written in AIDL.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the Service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy()."

Turn Pandas Multi-Index into column

I ran into Karl's issue as well. I just found myself renaming the aggregated column then resetting the index.

df = pd.DataFrame(df.groupby(['arms', 'success'])['success'].sum()).rename(columns={'success':'sum'})

enter image description here

df = df.reset_index()

enter image description here

How to avoid 'cannot read property of undefined' errors?

If I am understanding your question correctly, you want the safest way to determine if an object contains a property.

The easiest way is to use the in operator.

window.a = "aString";
//window should have 'a' property
//lets test if it exists
if ("a" in window){
    //true
 }

if ("b" in window){
     //false
 }

Of course you can nest this as deep as you want

if ("a" in window.b.c) { }

Not sure if this helps.

Using bootstrap with bower

I finally ended using the following : bower install --save http://twitter.github.com/bootstrap/assets/bootstrap.zip

Seems cleaner to me since it doesn't clone the whole repo, it only unzip the required assests.

The downside of that is that it breaks the bower philosophy since a bower update will not update bootstrap.

But I think it's still cleaner than using bower install bootstrap and then building bootstrap in your workflow.

It's a matter of choice I guess.

Update : seems they now version a dist folder (see: https://github.com/twbs/bootstrap/pull/6342), so just use bower install bootstrap and point to the assets in the dist folder

How to enumerate an enum with String type?

Updated to Swift 2.2+

func iterateEnum<T: Hashable>(_: T.Type) -> AnyGenerator<T> {
    var i = 0
    return AnyGenerator {
        let next = withUnsafePointer(&i) {
            UnsafePointer<T>($0).memory
        }
        if next.hashValue == i {
            i += 1
            return next
        } else {
            return nil
        }
    }
}

It's updated code to Swift 2.2 form @Kametrixom's answer

For Swift 3.0+ (many thanks to @Philip)

func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
    var i = 0
    return AnyIterator {
        let next = withUnsafePointer(&i) {
            UnsafePointer<T>($0).pointee
        }
        if next.hashValue == i {
            i += 1
            return next
        } else {
            return nil
        }
    }
}

SQL DELETE with JOIN another table for WHERE condition

Due to the locking implementation issues, MySQL does not allow referencing the affected table with DELETE or UPDATE.

You need to make a JOIN here instead:

DELETE  gc.*
FROM    guide_category AS gc 
LEFT JOIN
        guide AS g 
ON      g.id_guide = gc.id_guide
WHERE   g.title IS NULL

or just use a NOT IN:

DELETE  
FROM    guide_category AS gc 
WHERE   id_guide NOT IN
        (
        SELECT  id_guide
        FROM    guide
        )

Handling multiple IDs in jQuery

Yes, #id selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.

However, for your example, since <script> comes before the elements, you need a document.ready handler, so it waits until the elements are in the DOM to go looking for them, like this:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

Why not use Double or Float to represent currency?

Most answers have highlighted the reasons why one should not use doubles for money and currency calculations. And I totally agree with them.

It doesn't mean though that doubles can never be used for that purpose.

I have worked on a number of projects with very low gc requirements, and having BigDecimal objects was a big contributor to that overhead.

It's the lack of understanding about double representation and lack of experience in handling the accuracy and precision that brings about this wise suggestion.

You can make it work if you are able to handle the precision and accuracy requirements of your project, which has to be done based on what range of double values is one dealing with.

You can refer to guava's FuzzyCompare method to get more idea. The parameter tolerance is the key. We dealt with this problem for a securities trading application and we did an exhaustive research on what tolerances to use for different numerical values in different ranges.

Also, there might be situations when you're tempted to use Double wrappers as a map key with hash map being the implementation. It is very risky because Double.equals and hash code for example values "0.5" & "0.6 - 0.1" will cause a big mess.

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

how to update spyder on anaconda

Go to Anaconda Naviagator, find spyder,click settings in the top right corner of the spyder app.click update tab

Bootstrap 4 align navbar items to the right

On Bootsrap 4.0.0-beta.2, none of the answers listed here worked for me. Finally, the Bootstrap site gave me the solution, not via its doc but via its page source code...

Getbootstrap.com align their right navbar-nav to the right with the help of the following class: ml-md-auto.

Install a module using pip for specific python version

I faced a similar problem with another package called Twisted. I wanted to install it for Python 2.7, but it only got installed for Python 2.6 (system's default version).

Making a simple change worked for me.

When adding Python 2.7's path to your $PATH variable, append it to the front like this: PATH=/usr/local/bin:$PATH, so that the system uses that version.

If you face more problems, you can follow this blog post which helped me - https://github.com/h2oai/h2o-2/wiki/installing-python-2.7-on-centos-6.3.-follow-this-sequence-exactly-for-centos-machine-only

Add a UIView above all, even the navigation bar

Add you view as the subview of NavigationController.

[self.navigationController.navigationBar addSubview: overlayView)]

You can also add it over the window:

UIView *view = /* Your custom view */;
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[window addSubview:view];

Hope this helps.. :)

What does "#pragma comment" mean?

Pragma directives specify operating system or machine specific (x86 or x64 etc) compiler options. There are several options available. Details can be found in https://msdn.microsoft.com/en-us/library/d9x1s805.aspx

#pragma comment( comment-type [,"commentstring"] ) has this format.

Refer https://msdn.microsoft.com/en-us/library/7f0aews7.aspx for details about different comment-type.

#pragma comment(lib, "kernel32") #pragma comment(lib, "user32")

The above lines of code includes the library names (or path) that need to be searched by the linker. These details are included as part of the library-search record in the object file.

So, in this case kernel.lib and user32.lib are searched by the linker and included in the final executable.

How to load data to hive from HDFS without removing the source file?

from your question I assume that you already have your data in hdfs. So you don't need to LOAD DATA, which moves the files to the default hive location /user/hive/warehouse. You can simply define the table using the externalkeyword, which leaves the files in place, but creates the table definition in the hive metastore. See here: Create Table DDL eg.:

create external table table_name (
  id int,
  myfields string
)
location '/my/location/in/hdfs';

Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:

row format delimited fields terminated by ','

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).

If you cannot find it this way, try the menu: View/Properties Window.

Or try the F4 key.

OperationalError, no such column. Django

Anyone coming here:

Remove all migrations Remove db.sqlite file

redo migrations

Customize the Authorization HTTP header

In the case of CROSS ORIGIN request read this:

I faced this situation and at first I chose to use the Authorization Header and later removed it after facing the following issue.

Authorization Header is considered a custom header. So if a cross-domain request is made with the Autorization Header set, the browser first sends a preflight request. A preflight request is an HTTP request by the OPTIONS method, this request strips all the parameters from the request. Your server needs to respond with Access-Control-Allow-Headers Header having the value of your custom header (Authorization header).

So for each request the client (browser) sends, an additional HTTP request(OPTIONS) was being sent by the browser. This deteriorated the performance of my API. You should check if adding this degrades your performance. As a workaround I am sending tokens in http parameters, which I know is not the best way of doing it but I couldn't compromise with the performance.

How to show text on image when hovering?

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  width: 50%;_x000D_
}_x000D_
_x000D_
.image {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.overlay {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  opacity: 0;_x000D_
  transition: .5s ease;_x000D_
  background-color: #008CBA;_x000D_
}_x000D_
_x000D_
.container:hover .overlay {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.text {_x000D_
  color: white;_x000D_
  font-size: 20px;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  -ms-transform: translate(-50%, -50%);_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <img src="http://lorempixel.com/500/500/" alt="Avatar" class="image">_x000D_
  <div class="overlay">_x000D_
    <div class="text">Hello World</div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference Link W3schools with multiple styles

Pass a variable to a PHP script running from the command line

There are four main alternatives. Both have their quirks, but Method 4 has many advantages from my view.


./script is a shell script starting by #!/usr/bin/php


Method 1: $argv

./script hello wo8844rld
// $argv[0] = "script", $argv[1] = "hello", $argv[2] = "wo8844rld"

?? Using $argv, the parameter order is critical.


Method 2: getopt()

./script -p7 -e3
// getopt("p::")["p"] = "7", getopt("e::")["e"] = "3"

It's hard to use in conjunction of $argv, because:

?? The parsing of options will end at the first non-option found, anything that follows is discarded.

?? Only 26 parameters as the alphabet.


Method 3: Bash Global variable

P9="xptdr" ./script
// getenv("P9") = "xptdr"
// $_SERVER["P9"] = "xptdr"

Those variables can be used by other programs running in the same shell.

They are blown when the shell is closed, but not when the PHP program is terminated. We can set them permanent in file ~/.bashrc!


Method 4: STDIN pipe and stream_get_contents()

Some piping examples:


Feed a string:

./script <<< "hello wo8844rld"
// stream_get_contents(STDIN) = "hello wo8844rld"

Feed a string using bash echo:

echo "hello wo8844rld" | ./script
// explode(" ",stream_get_contents(STDIN)) ...

Feed a file content:

./script < ~/folder/Special_params.txt
// explode("\n",stream_get_contents(STDIN)) ...

Feed an array of values:

./script <<< '["array entry","lol"]'
// var_dump( json_decode(trim(stream_get_contents(STDIN))) );

Feed JSON content from a file:

echo params.json | ./script
// json_decode(stream_get_contents(STDIN)) ...

It might work similarly to fread() or fgets(), by reading the STDIN.


Bash-Scripting Guide

Difference between private, public, and protected inheritance

Accessors    | Base Class | Derived Class | World
—————————————+————————————+———————————————+———————
public       |      y     |       y       |   y
—————————————+————————————+———————————————+———————
protected    |      y     |       y       |   n
—————————————+————————————+———————————————+———————
private      |            |               |    
  or         |      y     |       n       |   n
no accessor  |            |               |

y: accessible
n: not accessible

Based on this example for java... I think a little table worth a thousand words :)

Inserting line breaks into PDF

Another option is to use TCPDF::Ln(). It adds a line to the PDF with the option to set the height.

If the newlines are within your content already then MultiCell() is probably the way to go, as others have mentioned, but I find I like using:

$pdf->Cell(0, 0, 'Line 1', 0, 0, 'C');
$pdf->Ln();
$pdf->Cell(0, 0, 'Line 2', 0, 0, 'C');

It confuses me that Cell() and MultiCell() take in different arguments so I tend to stick to using Cell() only. Also it reads like a newline character for the PDF the same as \n reads like a newline character in text or <br> in HTML.

Set maxlength in Html Textarea

If you are using HTML 5, you need to specify that in your DOCTYPE declaration.

For a valid HTML 5 document, it should start with:

<!DOCTYPE html>

Before HTML 5, the textarea element did not have a maxlength attribute.

You can see this in the DTD/spec:

<!ELEMENT TEXTAREA - - (#PCDATA)       -- multi-line text field -->
<!ATTLIST TEXTAREA
  %attrs;                              -- %coreattrs, %i18n, %events --
  name        CDATA          #IMPLIED
  rows        NUMBER         #REQUIRED
  cols        NUMBER         #REQUIRED
  disabled    (disabled)     #IMPLIED  -- unavailable in this context --
  readonly    (readonly)     #IMPLIED
  tabindex    NUMBER         #IMPLIED  -- position in tabbing order --
  accesskey   %Character;    #IMPLIED  -- accessibility key character --
  onfocus     %Script;       #IMPLIED  -- the element got the focus --
  onblur      %Script;       #IMPLIED  -- the element lost the focus --
  onselect    %Script;       #IMPLIED  -- some text was selected --
  onchange    %Script;       #IMPLIED  -- the element value was changed --
  %reserved;                           -- reserved for possible future use --
  >

In order to limit the number of characters typed into a textarea, you will need to use javascript with the onChange event. You can then count the number of characters and disallow further typing.

Here is an in-depth discussion on text input and how to use server and client side scripting to limit the size.

Here is another sample.

Npm Error - No matching version found for

The version you have specified, or one of your dependencies has specified is not published to npmjs.com

Executing npm view ionic-native (see docs) the following output is returned for package versions:

versions:
   [ '1.0.7',
     '1.0.8',
     '1.0.9',
     '1.0.10',
     '1.0.11',
     '1.0.12',
     '1.1.0',
     '1.1.1',
     '1.2.0',
     '1.2.1',
     '1.2.2',
     '1.2.3',
     '1.2.4',
     '1.3.0',
     '1.3.1',
     '1.3.2',
     '1.3.3',
     '1.3.4',
     '1.3.5',
     '1.3.6',
     '1.3.7',
     '1.3.8',
     '1.3.9',
     '1.3.10',
     '1.3.11',
     '1.3.12',
     '1.3.13',
     '1.3.14',
     '1.3.15',
     '1.3.16',
     '1.3.17',
     '1.3.18',
     '1.3.19',
     '1.3.20',
     '1.3.21',
     '1.3.22',
     '1.3.23',
     '1.3.24',
     '1.3.25',
     '1.3.26',
     '1.3.27',
     '2.0.0',
     '2.0.1',
     '2.0.2',
     '2.0.3',
     '2.1.2',
     '2.1.3',
     '2.1.4',
     '2.1.5',
     '2.1.6',
     '2.1.7',
     '2.1.8',
     '2.1.9',
     '2.2.0',
     '2.2.1',
     '2.2.2',
     '2.2.3',
     '2.2.4',
     '2.2.5',
     '2.2.6',
     '2.2.7',
     '2.2.8',
     '2.2.9',
     '2.2.10',
     '2.2.11',
     '2.2.12',
     '2.2.13',
     '2.2.14',
     '2.2.15',
     '2.2.16',
     '2.2.17',
     '2.3.0',
     '2.3.1',
     '2.3.2',
     '2.4.0',
     '2.4.1',
     '2.5.0',
     '2.5.1',
     '2.6.0',
     '2.7.0',
     '2.8.0',
     '2.8.1',
     '2.9.0' ],

As you can see no version higher than 2.9.0 has been published to the npm repository. Strangely they have versions higher than this on GitHub. I would suggest opening an issue with the maintainers on this.

For now you can manually install the package via the tarball URL of the required release:

npm install https://github.com/ionic-team/ionic-native/tarball/v3.5.0

Getting the 'external' IP address in Java

All this are still up and working smoothly! (as of 23 Sep 2019)

Piece of advice: Do not direcly depend only on one of them; try to use one but have a contigency plan considering others! The more you use, the better!

Good luck!

How to check if a process id (PID) exists

You have two ways:

Lets start by looking for a specific application in my laptop:

[root@pinky:~]# ps fax | grep mozilla
 3358 ?        S      0:00  \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2    S+     0:00              \_ grep mozilla

All examples now will look for PID 3358.

First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:

[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358

So your code will be:

if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
    kill $PID 
fi

Second way: Just look for something in the /proc/$PID directory. I am using "exe" in this example, but you can use anything else.

[root@pinky:~]# ls -l /proc/3358/exe 
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash

So your code will be:

if [ -f /proc/$PID/exe ]; then
    kill $PID 
fi

BTW: whats wrong with kill -9 $PID || true ?


EDIT:

After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.

Debugging WebSocket in Google Chrome

As for a tool I started using, I suggest firecamp Its like Postman, but it also supports websockets and socket.io.

How to load assemblies in PowerShell?

You could use LoadWithPartialName. However, that is deprecated as they said.

You can indeed go along with Add-Type, and in addition to the other answers, if you don't want to specify the full path of the .dll file, you could just simply do:

Add-Type -AssemblyName "Microsoft.SqlServer.Management.SMO"

To me this returned an error, because I do not have SQL Server installed (I guess), however, with this same idea I was able to load the Windows Forms assembly:

Add-Type -AssemblyName "System.Windows.Forms"

You can find out the precise assembly name belonging to the particular class on the MSDN site:

Example of finding out assembly name belonging to a particular class

D3.js: How to get the computed width and height for an arbitrary element?

.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I have some useful comments. Because I had similar problem with location of figures. I used package "wrapfig" that allows to make figures wrapped by text. Something like

...
\usepackage{wrapfig}
\usepackage{graphicx}
...
\begin{wrapfigure}{r}{53pt}
\includegraphics[width=53pt]{cone.pdf}
\end{wrapfigure}

In options {r} means to put figure from right side. {l} can be use for left side.

linux script to kill java process

if there are multiple java processes and you wish to kill them with one command try the below command

kill -9 $(ps -ef | pgrep -f "java")

replace "java" with any process string identifier , to kill anything else.

Polymorphism vs Overriding vs Overloading

Both overriding and overloading are used to achieve polymorphism.

You could have a method in a class that is overridden in one or more subclasses. The method does different things depending on which class was used to instantiate an object.

    abstract class Beverage {
       boolean isAcceptableTemperature();
    }

    class Coffee extends Beverage {
       boolean isAcceptableTemperature() { 
           return temperature > 70;
       }
    }

    class Wine extends Beverage {
       boolean isAcceptableTemperature() { 
           return temperature < 10;
       }
    }

You could also have a method that is overloaded with two or more sets of arguments. The method does different things based on the type(s) of argument(s) passed.

    class Server {
        public void pour (Coffee liquid) {
            new Cup().fillToTopWith(liquid);
        }

        public void pour (Wine liquid) {
            new WineGlass().fillHalfwayWith(liquid);
        }

        public void pour (Lemonade liquid, boolean ice) {
            Glass glass = new Glass();
            if (ice) {
                glass.fillToTopWith(new Ice());
            }
            glass.fillToTopWith(liquid);
        }
    }

Why em instead of px?

You probably want to use em for font sizes until IE6 is gone (from your site). Px will be alright when page zooming (as opposed to text zooming) becomes the standard behaviour.

Traingamer already provided the neccessary links.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

<script>
jQuery(document).ready(function() {
    jQuery("tr").click(function(){
       alert("Click! "+ jQuery(this).find('td').html());
    });
});
</script>

Share variables between files in Node.js?

I'm unable to find an scenario where a global var is the best option, of course you can have one, but take a look at these examples and you may find a better way to accomplish the same:

Scenario 1: Put the stuff in config files

You need some value that it's the same across the application, but it changes depending on the environment (production, dev or test), the mailer type as example, you'd need:

// File: config/environments/production.json
{
    "mailerType": "SMTP",
    "mailerConfig": {
      "service": "Gmail",
      ....
}

and

// File: config/environments/test.json
{
    "mailerType": "Stub",
    "mailerConfig": {
      "error": false
    }
}

(make a similar config for dev too)

To decide which config will be loaded make a main config file (this will be used all over the application)

// File: config/config.js
var _ = require('underscore');

module.exports = _.extend(
    require(__dirname + '/../config/environments/' + process.env.NODE_ENV + '.json') || {});

And now you can get the data like this:

// File: server.js
...
var config = require('./config/config');
...
mailer.setTransport(nodemailer.createTransport(config.mailerType, config.mailerConfig));

Scenario 2: Use a constants file

// File: constants.js
module.exports = {
  appName: 'My neat app',
  currentAPIVersion: 3
};

And use it this way

// File: config/routes.js

var constants = require('../constants');

module.exports = function(app, passport, auth) {
  var apiroot = '/api/v' + constants.currentAPIVersion;
...
  app.post(apiroot + '/users', users.create);
...

Scenario 3: Use a helper function to get/set the data

Not a big fan of this one, but at least you can track the use of the 'name' (citing the OP's example) and put validations in place.

// File: helpers/nameHelper.js

var _name = 'I shall not be null'

exports.getName = function() {
  return _name;
};

exports.setName = function(name) {
  //validate the name...
  _name = name;
};

And use it

// File: controllers/users.js

var nameHelper = require('../helpers/nameHelper.js');

exports.create = function(req, res, next) {
  var user = new User();
  user.name = req.body.name || nameHelper.getName();
  ...

There could be a use case when there is no other solution than having a global var, but usually you can share the data in your app using one of these scenarios, if you are starting to use node.js (as I was sometime ago) try to organize the way you handle the data over there because it can get messy really quick.

Purge or recreate a Ruby on Rails database

I use:

  • rails db:drop to delete the databases.
  • rails db:create to create the databases based on config/database.yml

The previous commands may be replaced with rails db:reset.

Don't forget to run rails db:migrate to run the migrations.

How to make the script wait/sleep in a simple way in unity

here is more simple way without StartCoroutine:

float t = 0f;
float waittime = 1f;

and inside Update/FixedUpdate:

if (t < 0){
    t += Time.deltaTIme / waittime;
    yield return t;
}

Java - Create a new String instance with specified length and filled with specific character. Best solution?

Mi solution :

  pw = "1321";
    if (pw.length() < 16){
      for(int x = pw.length() ; x < 16 ; x++){
        pw  += "*";
      }
    }

The output :

1321************

Get human readable version of file size?

This will do what you need in almost any situation, is customizable with optional arguments, and as you can see, is pretty much self-documenting:

from math import log
def pretty_size(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']):
    pow,n=min(int(log(max(n*b**pow,1),b)),len(pre)-1),n*b**pow
    return "%%.%if %%s%%s"%abs(pow%(-pow-1))%(n/b**float(pow),pre[pow],u)

Example output:

>>> pretty_size(42)
'42 B'

>>> pretty_size(2015)
'2.0 KiB'

>>> pretty_size(987654321)
'941.9 MiB'

>>> pretty_size(9876543210)
'9.2 GiB'

>>> pretty_size(0.5,pow=1)
'512 B'

>>> pretty_size(0)
'0 B'

Advanced customizations:

>>> pretty_size(987654321,b=1000,u='bytes',pre=['','kilo','mega','giga'])
'987.7 megabytes'

>>> pretty_size(9876543210,b=1000,u='bytes',pre=['','kilo','mega','giga'])
'9.9 gigabytes'

This code is both Python 2 and Python 3 compatible. PEP8 compliance is an exercise for the reader. Remember, it's the output that's pretty.

Update:

If you need thousands commas, just apply the obvious extension:

def prettier_size(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']):
    r,f=min(int(log(max(n*b**pow,1),b)),len(pre)-1),'{:,.%if} %s%s'
    return (f%(abs(r%(-r-1)),pre[r],u)).format(n*b**pow/b**float(r))

For example:

>>> pretty_units(987654321098765432109876543210)
'816,968.5 YiB'

Notepad++ - How can I replace blank lines

You can record a macro that removes the first blank line, and positions the cursor correctly for the second line. Then you can repeat executing that macro.

Directly export a query to CSV using SQL Developer

You can use the spool command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool can change the file that's being written to, so you can have several queries writing to different files just by putting spool commands between them:

spool "\path\to\spool1.txt"

select /*csv*/ * from employees;

spool "\path\to\spool2.txt"

select /*csv*/ * from locations;

spool off;

You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set command, though some of those do not translate to SQL Developer.

Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.

A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Once I found what format it was looking for in the connection string, it worked just fine like this with Oracle.ManagedDataAccess. Without having to mess around with anything separately.

DATA SOURCE=DSDSDS:1521/ORCL;

jquery validate check at least one checkbox

 if ($('input:checkbox').filter(':checked').length < 1){
        alert("Check at least one!");
 return false;
 }

MySQL joins and COUNT(*) from another table

Maybe I am off the mark here and not understanding the OP but why are you joining tables?

If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.

SELECT group_id, COUNT(*) as membercount 
FROM members 
GROUP BY group_id 
HAVING membercount > 4

This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.

If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.

Eclipse and Windows newlines

There is a handy bash utility - dos2unix - which is a DOS/MAC to UNIX text file format converter, that if not already installed on your distro, should be able to be easily installed via a package manager. dos2unix man page

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

I'm using flow with vscode but had the same problem. I solved it with these steps:

  1. Install the extension Flow Language Support

  2. Disable the built-in TypeScript extension:

    1. Go to Extensions tab
    2. Search for @builtin TypeScript and JavaScript Language Features
    3. Click on Disable

How to increment datetime by custom months in python without using library

This implementation might have some value for someone who is working with billing.

If you are working with billing, you probably want to get "the same date next month (if possible)" as opposed to "add 1/12 of one year".

What is so confusing about this is you actually need take into account two values if you are doing this continuously. Otherwise for any dates past the 27th, you'll keep losing a few days until you end up at the 27th after leap year.

The values you need to account for:

  • The value you want to add a month to
  • The day you started with

This way if you get bumped from the 31st down to the 30th when you add one month, you'll get bumped back up to the 31st for the next month that has that day.

This is how I did it:

def closest_date_next_month(year, month, day):
    month = month + 1
    if month == 13:
        month = 1
        year  = year + 1


    condition = True
    while condition:
        try:
            return datetime.datetime(year, month, day)
        except ValueError:
            day = day-1
        condition = day > 26

    raise Exception('Problem getting date next month')

paid_until = closest_date_next_month(
                 last_paid_until.year, 
                 last_paid_until.month, 
                 original_purchase_date.day)  # The trick is here, I'm using the original date, that I started adding from, not the last one

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?

var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone', 
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike 
v7.6 release 92', 'Pike v7.8 release 517'];

// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
    // Execute code
}
// If NOT on Apple device
else {
    // Execute code
}

Centering text in a table in Twitter Bootstrap

In Bootstrap 3 (3.0.3) adding the "text-center" class to a td element works out of the box.

I.e., the following centers some text in a table cell:

<td class="text-center">some text</td>

Extract a substring according to a pattern

Here is another simple answer

gsub("^.*:","", string)

Difference between partition key, composite key and clustering key in Cassandra?

The primary key in Cassandra usually consists of two parts - Partition key and Clustering columns.

primary_key((partition_key), clustering_col )

Partition key - The first part of the primary key. The main aim of a partition key is to identify the node which stores the particular row.

CREATE TABLE phone_book ( phone_num int, name text, age int, city text, PRIMARY KEY ((phone_num, name), age);

Here, (phone_num, name) is the partition key. While inserting the data, the hash value of the partition key is generated and this value decides which node the row should go into.

Consider a 4 node cluster, each node has a range of hash values it can store. (Write) INSERT INTO phone_book VALUES (7826573732, ‘Joey’, 25, ‘New York’);

Now, the hash value of the partition key is calculated by Cassandra partitioner. say, hash value(7826573732, ‘Joey’) ? 12 , now, this row will be inserted in Node C.

(Read) SELECT * FROM phone_book WHERE phone_num=7826573732 and name=’Joey’;

Now, again the hash value of the partition key (7826573732,’Joey’) is calculated, which is 12 in our case which resides in Node C, from which the read is done.

  1. Clustering columns - Second part of the primary key. The main purpose of having clustering columns is to store the data in a sorted order. By default, the order is ascending.

There can be more than one partition key and clustering columns in a primary key depending on the query you are solving.

primary_key((pk1, pk2), col 1,col2)

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

Playing mp3 song on python

See also playsound

pip install playsound

import playsound
playsound.playsound('/path/to/filename.mp3', True)

Joining Spark dataframes on the key

Alias Approach using scala (this is example given for older version of spark for spark 2.x see my other answer) :

You can use case class to prepare sample dataset ... which is optional for ex: you can get DataFrame from hiveContext.sql as well..

import org.apache.spark.sql.functions.col

case class Person(name: String, age: Int, personid : Int)

case class Profile(name: String, personid  : Int , profileDescription: String)

    val df1 = sqlContext.createDataFrame(
   Person("Bindu",20,  2) 
:: Person("Raphel",25, 5) 
:: Person("Ram",40, 9):: Nil)


val df2 = sqlContext.createDataFrame(
Profile("Spark",2,  "SparkSQLMaster") 
:: Profile("Spark",5, "SparkGuru") 
:: Profile("Spark",9, "DevHunter"):: Nil
)

// you can do alias to refer column name with aliases to  increase readablity

val df_asPerson = df1.as("dfperson")
val df_asProfile = df2.as("dfprofile")


val joined_df = df_asPerson.join(
    df_asProfile
, col("dfperson.personid") === col("dfprofile.personid")
, "inner")


joined_df.select(
  col("dfperson.name")
, col("dfperson.age")
, col("dfprofile.name")
, col("dfprofile.profileDescription"))
.show

sample Temp table approach which I don't like personally...

The reason to use the registerTempTable( tableName ) method for a DataFrame, is so that in addition to being able to use the Spark-provided methods of a DataFrame, you can also issue SQL queries via the sqlContext.sql( sqlQuery ) method, that use that DataFrame as an SQL table. The tableName parameter specifies the table name to use for that DataFrame in the SQL queries.

df_asPerson.registerTempTable("dfperson");
df_asProfile.registerTempTable("dfprofile")

sqlContext.sql("""SELECT dfperson.name, dfperson.age, dfprofile.profileDescription
                  FROM  dfperson JOIN  dfprofile
                  ON dfperson.personid == dfprofile.personid""")

If you want to know more about joins pls see this nice post : beyond-traditional-join-with-apache-spark

enter image description here

Note : 1) As mentioned by @RaphaelRoth ,

val resultDf = PersonDf.join(ProfileDf,Seq("personId")) is good approach since it doesnt have duplicate columns from both sides if you are using inner join with same table.
2) Spark 2.x example updated in another answer with full set of join operations supported by spark 2.x with examples + result

TIP :

Also, important thing in joins : broadcast function can help to give hint please see my answer

What is the best open XML parser for C++?

I am a C++ newbie and after trying a couple different suggestions on this page I must say I like pugixml the most. It has easy to understand documentation and a high level API which was all I was looking for.

What is the idiomatic Go equivalent of C's ternary operator?

Foreword: Without arguing that if else is the way to go, we can still play with and find pleasure in language-enabled constructs.

The following If construct is available in my github.com/icza/gox library with lots of other methods, being the gox.If type.


Go allows to attach methods to any user-defined types, including primitive types such as bool. We can create a custom type having bool as its underlying type, and then with a simple type conversion on the condition, we have access to its methods. Methods that receive and select from the operands.

Something like this:

type If bool

func (c If) Int(a, b int) int {
    if c {
        return a
    }
    return b
}

How can we use it?

i := If(condition).Int(val1, val2)  // Short variable declaration, i is of type int
     |-----------|  \
   type conversion   \---method call

For example a ternary doing max():

i := If(a > b).Int(a, b)

A ternary doing abs():

i := If(a >= 0).Int(a, -a)

This looks cool, it's simple, elegant, and efficient (it's also eligible for inlining).

One downside compared to a "real" ternary operator: it always evaluates all operands.

To achieve deferred and only-if-needed evaluation, the only option is to use functions (either declared functions or methods, or function literals), which are only called when / if needed:

func (c If) Fint(fa, fb func() int) int {
    if c {
        return fa()
    }
    return fb()
}

Using it: Let's assume we have these functions to calculate a and b:

func calca() int { return 3 }
func calcb() int { return 4 }

Then:

i := If(someCondition).Fint(calca, calcb)

For example, the condition being current year > 2020:

i := If(time.Now().Year() > 2020).Fint(calca, calcb)

If we want to use function literals:

i := If(time.Now().Year() > 2020).Fint(
    func() int { return 3 },
    func() int { return 4 },
)

Final note: if you would have functions with different signatures, you could not use them here. In that case you may use a function literal with matching signature to make them still applicable.

For example if calca() and calcb() would have parameters too (besides the return value):

func calca2(x int) int { return 3 }
func calcb2(x int) int { return 4 }

This is how you could use them:

i := If(time.Now().Year() > 2020).Fint(
    func() int { return calca2(0) },
    func() int { return calcb2(0) },
)

Try these examples on the Go Playground.

Storing WPF Image Resources

If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all Image elements.

To do this, create a BitmapSource as a resource somewhere:

<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />

Then, in your code, use something like:

<Image Source="{StaticResource MyImageSource}" />

In my case, I found that I had to set the Image.png file to have a build action of Resource rather than just Content. This causes the image to be carried within your compiled assembly.

PHP Unset Session Variable

// set
$_SESSION['test'] = 1;

// destroy
unset($_SESSION['test']);

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

Java JTextField with input hint

Here is a fully working example based on Adam Gawne-Cain's earlier Posting. His solution is simple and actually works exceptionally well.

I've used the following text in a Grid of multiple Fields:

H__|__WWW__+__XXXX__+__WWW__|__H

this makes it possible to easily verify the x/y alignment of the hinted text.

A couple of observations:
- there are any number of solutions out there, but many only work superficially and/or are buggy
- sun.tools.jconsole.ThreadTab.PromptingTextField is a simple solution, but it only shows the prompting text when the Field doesn't have the focus & it's private, but nothing a little cut-and-paste won't fix.

The following works on JDK 8 and upwards:

import java.awt.*;
import java.util.stream.*;
import javax.swing.*;
/**
 * @author DaveTheDane, based on a suggestion from Adam Gawne-Cain
 */
public final class JTextFieldPromptExample extends JFrame {

    private static JTextField newPromptedJTextField (final String text, final String prompt) {

        final String promptPossiblyNullButNeverWhitespace = prompt == null || prompt.trim().isEmpty()  ?  null  :  prompt;

        return new JTextField(text) {
            @Override
            public void paintComponent(final Graphics    USE_g2d_INSTEAD) {
                final Graphics2D     g2d =  (Graphics2D) USE_g2d_INSTEAD;

                super.paintComponent(g2d);

//              System.out.println("Paint.: " + g2d);

                if (getText().isEmpty()
                &&  promptPossiblyNullButNeverWhitespace != null) {
                    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                    final Insets      ins = getInsets();
                    final FontMetrics fm  = g2d.getFontMetrics();

                    final int cB = getBackground().getRGB();
                    final int cF = getForeground().getRGB();
                    final int m  = 0xfefefefe;
                    final int c2 = ((cB & m) >>> 1) + ((cF & m) >>> 1); // "for X in (A, R, G, B) {Xnew = (Xb + Xf) / 2}"
                    /*
                     * The hint text color should be halfway between the foreground and background colors so it is always gently visible.
                     * The variables c0,c1,m,c2 calculate the halfway color's ARGB fields simultaneously without overflowing 8 bits.
                     * Swing sets the Graphics' font to match the JTextField's font property before calling the "paint" method,
                     * so the hint font will match the JTextField's font.
                     * Don't think there are any side effects because Swing discards the Graphics after painting.
                     * Adam Gawne-Cain, Aug 6 2019 at 15:55
                     */
                    g2d.setColor(new Color(c2, true));
                    g2d.drawString(promptPossiblyNullButNeverWhitespace, ins.left, getHeight() - fm.getDescent() - ins.bottom);
                    /*
                     * y Coordinate based on Descent & Bottom-inset seems to align Text spot-on.
                     * DaveTheDane, Apr 10 2020
                     */
                }
            }
        };
    }

    private static final GridBagConstraints GBC_LEFT  = new GridBagConstraints();
    private static final GridBagConstraints GBC_RIGHT = new GridBagConstraints();
    /**/    static {
        GBC_LEFT .anchor    = GridBagConstraints.LINE_START;
        GBC_LEFT .fill      = GridBagConstraints.HORIZONTAL;
        GBC_LEFT .insets    = new Insets(8, 8, 0, 0);

        GBC_RIGHT.gridwidth = GridBagConstraints.REMAINDER;
        GBC_RIGHT.fill      = GridBagConstraints.HORIZONTAL;
        GBC_RIGHT.insets    = new Insets(8, 8, 0, 8);
    }

    private <C extends Component> C addLeft (final C component) {
        this    .add           (component);
        this.gbl.setConstraints(component, GBC_LEFT);
        return                  component;
    }
    private <C extends Component> C addRight(final C component) {
        this    .add           (component);
        this.gbl.setConstraints(component, GBC_RIGHT);
        return                  component;
    }

    private static final String ALIGN = "H__|__WWW__+__XXXX__+__WWW__|__H";

    private final GridBagLayout gbl = new GridBagLayout();

    public JTextFieldPromptExample(final String title) {
        super(title);
        this.setLayout(gbl);

        final java.util.List<JTextField> texts = Stream.of(
                addLeft (newPromptedJTextField(ALIGN + ' ' + "Top-Left"    , ALIGN)),
                addRight(newPromptedJTextField(ALIGN + ' ' + "Top-Right"   , ALIGN)),

                addLeft (newPromptedJTextField(ALIGN + ' ' + "Middle-Left" , ALIGN)),
                addRight(newPromptedJTextField(                       null , ALIGN)),

                addLeft (new        JTextField("x"        )),
                addRight(newPromptedJTextField("x",   ""  )),

                addLeft (new        JTextField(null       )),
                addRight(newPromptedJTextField(null,  null)),

                addLeft (newPromptedJTextField(ALIGN + ' ' + "Bottom-Left" , ALIGN)),
                addRight(newPromptedJTextField(ALIGN + ' ' + "Bottom-Right", ALIGN)) ).collect(Collectors.toList());

        final JButton button = addRight(new JButton("Get texts"));
        /**/                   addRight(Box.createVerticalStrut(0)); // 1 last time forces bottom inset

        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setPreferredSize(new Dimension(740, 260));
        this.pack();
        this.setResizable(false);
        this.setVisible(true);

        button.addActionListener(e -> {
            texts.forEach(text -> System.out.println("Text..: " + text.getText()));
        });
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(() -> new JTextFieldPromptExample("JTextField with Prompt"));
    }
}

UINavigationBar custom back button without title

  • Change backItem.title = "" to using topItem.title = ""
  • Setting navigationItem.hidesBackButton = true & navigationItem.leftBarButtonItem will lose the back gesture
  • Remember we have to create 2 instances of the back image

My solution will change the image & keep the back gesture:

navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back")
navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "back")
navigationController?.navigationBar.topItem?.title = ""

PostgreSQL visual interface similar to phpMyAdmin?

Azure Data Studio with Postgres addin is the tool of choice to manage postgres databases for me. Check it out. https://docs.microsoft.com/en-us/sql/azure-data-studio/quickstart-postgres?view=sql-server-ver15

Android button with different background colors

in Mono Android you can use filter like this:

your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));

Sending email with PHP from an SMTP server

When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).

For example, I usually use PHPMailer with similar settings to this ones:

$mail = new PHPMailer();

// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';

$mail->Host       = "mail.example.com"; // SMTP server example
$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Port       = 25;                    // set the SMTP port for the GMAIL server
$mail->Username   = "username"; // SMTP account username example
$mail->Password   = "password";        // SMTP account password example

// Content
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();

You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer

Oracle Add 1 hour in SQL

You can use INTERVAL type or just add calculated number value - "1" is equal "1 day".

first way:

select date_column + INTERVAL '0 01:00:00' DAY TO SECOND from dual;

second way:

select date_column + 1/24 from dual;

First way is more convenient when you need to add a complicated value - for example, "1 day 3 hours 25 minutes 49 seconds". See also: http://www.oracle-base.com/articles/misc/oracle-dates-timestamps-and-intervals.php

Also you have to remember that oracle have two interval types - DAY TO SECOND and YEAR TO MONTH. As for me, one interval type would be better, but I hope people in oracle knows, what they do ;)

Run reg command in cmd (bat file)?

You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)

Increasing (or decreasing) the memory available to R processes

Use memory.limit(). You can increase the default using this command, memory.limit(size=2500), where the size is in MB. You need to be using 64-bit in order to take real advantage of this.

One other suggestion is to use memory efficient objects wherever possible: for instance, use a matrix instead of a data.frame.

Using SSIS BIDS with Visual Studio 2012 / 2013

First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]

Basically this question has the title ...Visual Studio 2012 / 2013 What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.

So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj project. Now this computer does not yet have sql server installed on it yet.

Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates

Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.

In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396

Replacing characters in Ant property

Two possibilities :

via script task and builtin javascript engine (if using jdk >= 1.6)

<project>

 <property name="propA" value="This is a value"/>

 <script language="javascript">
  project.setProperty('propB', project.getProperty('propA').
   replace(" ", "_"));
 </script>
 <echo>$${propB} => ${propB}</echo>

</project>

or using Ant addon Flaka

<project xmlns:fl="antlib:it.haefelinger.flaka">

 <property name="propA" value="This is a value"/>

 <fl:let> propB := replace('${propA}', '_', ' ')</fl:let>

 <echo>$${propB} => ${propB}</echo>

</project>

to overwrite exisiting property propA simply replace propB with propA

Why is using "for...in" for array iteration a bad idea?

Mainly two reasons:

One

Like others have said, You might get keys which aren't in your array or that are inherited from the prototype. So if, let's say, a library adds a property to the Array or Object prototypes:

Array.prototype.someProperty = true

You'll get it as part of every array:

for(var item in [1,2,3]){
  console.log(item) // will log 1,2,3 but also "someProperty"
}

you could solve this with the hasOwnProperty method:

var ary = [1,2,3];
for(var item in ary){
   if(ary.hasOwnProperty(item)){
      console.log(item) // will log only 1,2,3
   }
}

but this is true for iterating over any object with a for-in loop.

Two

Usually the order of the items in an array is important, but the for-in loop won't necessarily iterate in the right order, that's because it treats the array as an object, which is the way it is implemented in JS, and not as an array. This seems like a small thing, but it can really screw up applications and is hard to debug.

How to make URL/Phone-clickable UILabel?

You can use a UITextView and select Detection for Links, Phone Numbers and other things in the inspector.

How to sum array of numbers in Ruby?

ruby 1.8.7 way is the following:

array.inject(0, &:+) 

Default value of 'boolean' and 'Boolean' in Java

The default value of any Object, such as Boolean, is null.

The default value for a boolean is false.

Note: Every primitive has a wrapper class. Every wrapper uses a reference which has a default of null. Primitives have different default values:

boolean -> false

byte, char, short, int, long -> 0

float, double -> 0.0

Note (2): void has a wrapper Void which also has a default of null and is it's only possible value (without using hacks).

How to make child process die after parent exits?

Install a trap handler to catch SIGINT, which kills off your child process if it's still alive, though other posters are correct that it won't catch SIGKILL.

Open a .lockfile with exclusive access and have the child poll on it trying to open it - if the open succeeds, the child process should exit

Conda: Installing / upgrading directly from github

There's better support for this now through conda-env. You can, for example, now do:

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"

It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml file.

If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml), then run the command: conda env update -f environment.yml.

It's more likely that you would want to create a new environment:

conda env create -f environment.yml (changed as supposed in the comments)

How to make a local variable (inside a function) global

You could use module scope. Say you have a module called utils:

f_value = 'foo'

def f():
    return f_value

f_value is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils from one module will be accessible to all other modules that have it imported:

>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'

Note that you can import the function by name:

>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'

But not the attribute:

>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'

This is because you're labeling the object referenced by the module attribute as f_value in the local scope, but then rebinding it to the string bar, while the function f is still referring to the module attribute.

Find mouse position relative to element

For people using JQuery:

Sometimes, when you have nested elements, one of them with the event attached to it, it can be confusing to understand what your browser sees as the parent. Here, you can specify which parent.

You take the mouse position, and then subtract it from the parent element's offset position.

var x = evt.pageX - $('#element').offset().left;
var y = evt.pageY - $('#element').offset().top;

If you're trying to get the mouse position on a page inside a scrolling pane:

var x = (evt.pageX - $('#element').offset().left) + self.frame.scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + self.frame.scrollTop();

Or the position relative to the page:

var x = (evt.pageX - $('#element').offset().left) + $(window).scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + $(window).scrollTop();

Note the following performance optimisation:

var offset = $('#element').offset();
// Then refer to 
var x = evt.pageX - offset.left;

In this way, JQuery does not have to look up #element for each line.

Update

There is a newer, JavaScript-only version in an answer by @anytimecoder -- see also browser support for getBoundingClientRect().

Get the position of a spinner in Android

if (position ==0) {
    if (rYes.isChecked()) {
        Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
    } else if (rNo.isChecked()) {
        Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
    }
}

This code is supposed to select both check boxes.
Is there a problem with it?

How do you check if a certain index exists in a table?

For SQL 2008 and newer, a more concise method, coding-wise, to detect index existence is by using the INDEXPROPERTY built-in function:

INDEXPROPERTY ( object_ID , index_or_statistics_name , property )  

The simplest usage is with the IndexID property:

If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexID') Is Null

If the index exists, the above will return its ID; if it doesn't, it will return NULL.

Bash or KornShell (ksh)?

Bash is the benchmark, but that's mostly because you can be reasonably sure it's installed on every *nix out there. If you're planning to distribute the scripts, use Bash.

I can not really address the actual programming differences between the shells, unfortunately.

Alter a MySQL column to be AUTO_INCREMENT

You can use the following query to make document_id to increment automatically

ALTER TABLE document MODIFY COLUMN document_id INT auto_increment

It is preferred to make document_id primary key as well

ALTER TABLE document MODIFY COLUMN document_id INT auto_increment PRIMARY KEY;

git-diff to ignore ^M

Try git diff --ignore-space-at-eol, or git diff --ignore-space-change, or git diff --ignore-all-space.

calling server side event from html button control

The easiest way to accomplish this is to override the RaisePostBackEvent method.

<input type="button" ID="btnRaisePostBack" runat="server" onclick="raisePostBack();" ... />

And in your JavaScript:

raisePostBack = function(){
    __doPostBack("<%=btnRaisePostBack.ClientID%>", "");
}

And in your code:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    //call the RaisePostBack event 
    base.RaisePostBackEvent(source, eventArgument);

    if (source == btnRaisePostBack)
    {
         //do some logic
    }
}

Remove the complete styling of an HTML button/submit

Your question says "Internet Explorer," but for those interested in other browsers, you can now use all: unset on buttons to unstyle them.

It doesn't work in IE, but it's well-supported everywhere else.

https://caniuse.com/#feat=css-all

Old Safari color warning: Setting the text color of the button after using all: unset can fail in Safari 13.1, due to a bug in WebKit. (The bug is fixed in Safari 14 and up.) "all: unset is setting -webkit-text-fill-color to black, and that overrides color." If you need to set text color after using all: unset, be sure to set both the color and the -webkit-text-fill-color to the same color.

Accessibility warning: For the sake of users who aren't using a mouse pointer, be sure to re-add some :focus styling, e.g. button:focus { outline: orange auto 5px } for keyboard accessibility.

And don't forget cursor: pointer. all: unset removes all styling, including the cursor: pointer, which makes your mouse cursor look like a pointing hand when you hover over the button. You almost certainly want to bring that back.

_x000D_
_x000D_
button {
  all: unset;
  color: blue;
  -webkit-text-fill-color: blue;
  cursor: pointer;
}

button:focus {
  outline: orange 5px auto;
}
_x000D_
<button>check it out</button>
_x000D_
_x000D_
_x000D_

How to join a slice of strings into a single string?

The title of your question is:

How to join a slice of strings into a single string?

but in fact, reg is not a slice, but a length-three array. [...]string is just syntactic sugar for (in this case) [3]string.

To get an actual slice, you should write:

reg := []string {"a","b","c"}

(Try it out: https://play.golang.org/p/vqU5VtDilJ.)

Incidentally, if you ever really do need to join an array of strings into a single string, you can get a slice from the array by adding [:], like so:

fmt.Println(strings.Join(reg[:], ","))

(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)

Set focus to field in dynamically loaded DIV

Dynamically added items have to be added to the DOM... clone().append() adds it to the DOM... which allows it to be selected via jquery.

How can I change the text inside my <span> with jQuery?

$('#abc span').text('baa baa black sheep');
$('#abc span').html('baa baa <strong>black sheep</strong>');

text() if just text content. html() if it contains, well, html content.

jquery clone div and append it after specific div

You can do it using clone() function of jQuery, Accepted answer is ok but i am providing alternative to it, you can use append(), but it works only if you can change html slightly as below:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('#clone_btn').click(function(){_x000D_
      $("#car_parent").append($("#car2").clone());_x000D_
    });_x000D_
});
_x000D_
.car-well{_x000D_
  border:1px solid #ccc;_x000D_
  text-align: center;_x000D_
  margin: 5px;_x000D_
  padding:3px;_x000D_
  font-weight:bold;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="car_parent">_x000D_
  <div id="car1" class="car-well">Normal div</div>_x000D_
  <div id="car2" class="car-well" style="background-color:lightpink;color:blue">Clone div</div>_x000D_
  <div id="car3" class="car-well">Normal div</div>_x000D_
  <div id="car4" class="car-well">Normal div</div>_x000D_
  <div id="car5" class="car-well">Normal div</div>_x000D_
</div>_x000D_
<button type="button" id="clone_btn" class="btn btn-primary">Clone</button>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do you get the selected value of a Spinner?

mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()) works based on Rich's description.

What is android:ems attribute in Edit Text?

An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —

-Tim Bray

Most efficient way to see if an ArrayList contains an object in Java

I would say the simplest solution would be to wrap the object and delegate the contains call to a collection of the wrapped class. This is similar to the comparator but doesn't force you to sort the resulting collection, you can simply use ArrayList.contains().

public class Widget {
        private String name;
        private String desc;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }



    public abstract class EqualsHashcodeEnforcer<T> {

        protected T wrapped;

        public T getWrappedObject() {
            return wrapped;
        }

        @Override
        public boolean equals(Object obj) {
            return equalsDelegate(obj);
        }

        @Override
        public int hashCode() {
            return hashCodeDelegate();
        }

        protected abstract boolean equalsDelegate(Object obj);

        protected abstract int hashCodeDelegate();
    }


    public class WrappedWidget extends EqualsHashcodeEnforcer<Widget> {

        @Override
        protected boolean equalsDelegate(Object obj) {
            if (obj == null) {
                return false;
            }
            if (obj == getWrappedObject()) {
                return true;
            }
            if (obj.getClass() != getWrappedObject().getClass()) {
                return false;
            }
            Widget rhs = (Widget) obj;

            return new EqualsBuilder().append(getWrappedObject().getName(),
                    rhs.getName()).append(getWrappedObject().getDesc(),
                    rhs.getDesc()).isEquals();
        }

        @Override
        protected int hashCodeDelegate() {

            return new HashCodeBuilder(121, 991).append(
                    getWrappedObject().getName()).append(
                    getWrappedObject().getDesc()).toHashCode();
        }

    }

Using a bitmask in C#

To combine bitmasks you want to use bitwise-or. In the trivial case where every value you combine has exactly 1 bit on (like your example), it's equivalent to adding them. If you have overlapping bits however, or'ing them handles the case gracefully.

To decode the bitmasks you and your value with a mask, like so:

if(val & (1<<1)) SusanIsOn();
if(val & (1<<2)) BobIsOn();
if(val & (1<<3)) KarenIsOn();

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

your manifest application name should contain application class name. Like

<application
        android:name="your package name.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/AppTheme"> 

Why emulator is very slow in Android Studio?

The emulator is much much faster when running on Linux. In Ubuntu 13.04, it launches within 10 seconds, and it runs nearly as smoothly as on a physical device. I haven't been able to reproduce the performance on Windows.

EDIT: Actually, after the first boot, when using the Atom arch. and GPU acceleration, the Windows emulator runs nearly as well as in Linux.

Mockito : how to verify method was called on an object created within a method?

Another simple way would be add some log statement to the bar.someMethod() and then ascertain you can see the said message when your test executed, see examples here: How to do a JUnit assert on a message in a logger

That is especially handy when your Bar.someMethod() is private.

How to "pretty" format JSON output in Ruby on Rails

I have used the gem CodeRay and it works pretty well. The format includes colors and it recognises a lot of different formats.

I have used it on a gem that can be used for debugging rails APIs and it works pretty well.

By the way, the gem is named 'api_explorer' (http://www.github.com/toptierlabs/api_explorer)

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

(9.61 + "").replace('.',':')

Or if your 9.61 is already a string:

"9.61".replace('.',':')

How to prevent http file caching in Apache httpd (MAMP)

Tried this? Should work in both .htaccess, httpd.conf and in a VirtualHost (usually placed in httpd-vhosts.conf if you have included it from your httpd.conf)

<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

100% Prevent Files from being cached

This is similar to how google ads employ the header Cache-Control: private, x-gzip-ok="" > to prevent caching of ads by proxies and clients.

From http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html

And optionally add the extension for the template files you are retrieving if you are using an extension other than .html for those.

ActionBarActivity is deprecated

android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."

checkout changes for Android Support Library, revision 22.1.0 (April 2015)

What is the difference between exit(0) and exit(1) in C?

exit(0) indicates that the program terminated without errors. exit(1) indicates that there were an error.

You can use different values other than 1 to differentiate between different kind of errors.

Registry key Error: Java version has value '1.8', but '1.7' is required

One possible solution to this problem is to add at Sencha CMD folder a bat file as sugested at this thread Sencha Cmd 5 + Java 8 Error.

The batch will have the name "sencha.bat" with this code:

@echo off
set JAVA_HOME=<YOUR JDK 7 HOME>
set PATH=%JAVA_HOME%\bin;%PATH%
set SENCHA_HOME=%~dp0
java -jar "%SENCHA_HOME%\sencha.jar" %*

Place it at sencha folder, in my case is

C:\Users\<YOUR USER>\bin\Sencha\Architect\Cmd\6.2.0.103

The following step is to change PATHEXT enviroment varible. Change at user variables to have the least impact possible.

I change from

COM;.CMD;.EXE;.BAT;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

to

COM;.BAT;.EXE;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

The idea is to make windows run .bat files first than .exe files. This is important because in sencha folder there is already an "sencha.exe" file. And in the command line if you type "sencha" it will execute "sencha.exe" instead of "sencha.bat".

This was the only solution that worked for because I'm very restricted when it comes to permissions.

Count immediate child div elements using jQuery

$("#foo > div").length

jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property. From here: http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/

Non-static variable cannot be referenced from a static context

You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.

At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.

So the class says "all cars have a color" and the instance says "this specific car is red".

In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.

Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).

To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).

In your case, try this code as a starting block:

public static void main (String[] args)
{
    try
    {
        MyProgram7 obj = new MyProgram7 ();
        obj.run (args);
    }
    catch (Exception e)
    {
        e.printStackTrace ();
    }
}

// instance variables here

public void run (String[] args) throws Exception
{
    // put your code here
}

The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

NULL vs nullptr (Why was it replaced?)

You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:

This problem falls into the following categories:

  • Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.

  • Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.

  • Make C++ easier to teach and learn.

Linux Command History with date and time

It depends on the shell (and its configuration) in standard bash only the command is stored without the date and time (check .bash_history if there is any timestamp there).

To have bash store the timestamp you need to set HISTTIMEFORMAT before executing the commands, e.g. in .bashrc or .bash_profile. This will cause bash to store the timestamps in .bash_history (see the entries starting with #).

Visual Studio Code how to resolve merge conflicts with git?

After trial and error I discovered that you need to stage the file that had the merge conflict, then you can commit the merge.

Removing padding gutter from grid columns in Bootstrap 4

Need an edge-to-edge design? Drop the parent .container or .container-fluid.

Still if you need to remove padding from .row and immediate child columns you have to add the class .no-gutters with the code from @Brian above to your own CSS file, actually it's Not 'right out of the box', check here for official details on the final Bootstrap 4 release: https://getbootstrap.com/docs/4.0/layout/grid/#no-gutters

Where is virtualenvwrapper.sh after pip install?

I can find one in macOS Mojave (10.14) while playing with virtualenvwrapper-4.8.4

/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh

What is a "web service" in plain English?

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards (XML, SOAP, HTTP).

All the standard Web Services works using following components:

  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)

It works somewhat like this:

  • The client program bundles the account registration information into a SOAP message.
  • This SOAP message is sent to the Web Service as the body of an HTTP POST request.
  • The Web Service unpacks the SOAP request and converts it into a command that the application can understand.
  • The application processes the information as required and responds with a new unique account number for that customer.
  • Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
  • The client program unpacks the SOAP message to obtain the results of the account registration process.

Setting the height of a SELECT in IE

Use a UI library, like jquery or yui, that provides an alternative to the native SELECT element, typically as part of the implementation of a combo box.

What is a Windows Handle?

A handle is a unique identifier for an object managed by Windows. It's like a pointer, but not a pointer in the sence that it's not an address that could be dereferenced by user code to gain access to some data. Instead a handle is to be passed to a set of functions that can perform actions on the object the handle identifies.

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

Extension exists but uuid_generate_v4 fails

if you do it from unix command (apart from PGAdmin) dont forget to pass the DB as a parameter. otherwise this extension will not be enabled when executing requests on this DB

psql -d -c "create EXTENSION pgcrypto;"

MySql : Grant read only options?

Note for MySQL 8 it's different

You need to do it in two steps:

CREATE USER 'readonly_user'@'localhost' IDENTIFIED BY 'some_strong_password';
GRANT SELECT, SHOW VIEW ON *.* TO 'readonly_user'@'localhost';
flush privileges;

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

I changed all support library versions to 25.3.1 and worked like a charm:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'

You also need to change compileSdkVersion and targetSdkVersion to 25:

compileSdkVersion 25
targetSdkVersion 25

Create a folder inside documents folder in iOS apps

Swift 1.2 and iOS 8

Create custom directory (name = "MyCustomData") inside the documents directory but only if the directory does not exist.

// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String

// create the custom folder path
let myCustomDataDirectoryPath = documentDirectoryPath.stringByAppendingPathComponent("/MyCustomData")

// check if directory does not exist
if NSFileManager.defaultManager().fileExistsAtPath(myCustomDataDirectoryPath) == false {

    // create the directory
    var createDirectoryError: NSError? = nil
    NSFileManager.defaultManager().createDirectoryAtPath(myCustomDataDirectoryPath, withIntermediateDirectories: false, attributes: nil, error: &createDirectoryError)

    // handle the error, you may call an exception
    if createDirectoryError != nil {
        println("Handle directory creation error...")
    }

}

change cursor from block or rectangle to line?

You're in replace mode. Press the Insert key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.

Auto generate function documentation in Visual Studio

Visual Assist has a nice solution too, and is highly costumizable.

After tweaking it to generate doxygen-style comments, these two clicks would produce -

/**
* Method:    FindTheFoo
* FullName:  FindTheFoo
* Access:    private 
* Qualifier:
* @param    int numberOfFoos
* @return   bool
*/
private bool FindTheFoo(int numberOfFoos)
{

}

(Under default settings, its a bit different.)


Edit: The way to customize the 'document method' text is under VassistX->Visual Assist Options->Suggestions, select 'Edit VA Snippets', Language: C++, Type: Refactoring, then go to 'Document Method' and customize. The above example is generated by:

va_doxy

What would be the Unicode character for big bullet in the middle of the character?

Here's full list of black dotlikes from unicode

● - &#9679; - Black Circle
⏺ - &#9210; - Black Circle for Record
⚫ - &#9899; - Medium Black Circle
⬤ - &#11044; - Black Large Circle
⧭ - &#10733; - Black Circle with Down Arrow
🞄 - &#128900; - Black Slightly Small Circle
• - &#8226; - Bullet (also • - &#149; - Message Waiting)
∙ - &#8729; - Bullet Operator
⋅ - &#8901; - Dot Operator (also · - &#183; - Middle Dot)
🌑 - &#127761; - New Moon Symbol

JAVA_HOME and PATH are set but java -version still shows the old one

In Linux Mint 18 Cinnamon be sure to check /etc/profile.d/jdk_home.sh I renamed this file to jdk_home.sh.old and now my path does not keep getting overridden and I can call java -version and see Java 9 as expected. Even though I correctly selected Java 9 in update-aternatives --config java this jdk_home.sh file kept overriding the $PATH on boot-up.

removing new line character from incoming stream using sed

To remove newlines, use tr:

tr -d '\n'

If you want to replace each newline with a single space:

tr '\n' ' '

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$\!ba;s/\n/ /g'  # Suitable for csh only!!

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

How can I replace the deprecated set_magic_quotes_runtime in php?

I used FPDF v. 1.53 and didn't want to upgrade because of possible side effects. I used the following code according to Yacoby:

Line 1164:

if (version_compare(PHP_VERSION, '5.3.0', '<')) {
    $mqr=get_magic_quotes_runtime();
    set_magic_quotes_runtime(0);
}

Line 1203:

if (version_compare(PHP_VERSION, '5.3.0', '<')) {
    set_magic_quotes_runtime($mqr);
}

MySQL config file location - redhat linux server

In the docker containers(centos based images) it is located at

/etc/mysql/my.cnf

Convert String XML fragment to Document Node in Java

If you're using dom4j, you can just do:

Document document = DocumentHelper.parseText(text);

(dom4j now found here: https://github.com/dom4j/dom4j)

Best way to convert strings to symbols in hash

In ruby I find this to be the most simple and easy to understand way to turn string keys in hashes to symbols :

my_hash.keys.each { |key| my_hash[key.to_sym] = my_hash.delete(key)}

For each key in the hash we call delete on it which removes it from the hash (also delete returns the value associated with the key that was deleted) and we immediately set this equal to the symbolized key.

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

How to get WooCommerce order details

$order = new WC_Order(get_query_var('order-received'));

Does a `+` in a URL scheme/host/path represent a space?

Try below:

<script type="text/javascript">

function resetPassword() {
   url: "submitForgotPassword.html?email="+fixEscape(Stringwith+char);
}
function fixEscape(str)
{
    return escape(str).replace( "+", "%2B" );
}
</script>