Programs & Examples On #Infinite sequence

Angular ui-grid dynamically calculate height of the grid

following @tony's approach, changed the getTableHeight() function to

<div id="grid1" ui-grid="$ctrl.gridOptions" class="grid" ui-grid-auto-resize style="{{$ctrl.getTableHeight()}}"></div>

getTableHeight() {
    var offsetValue = 365;
    return "height: " + parseInt(window.innerHeight - offsetValue ) + "px!important";
}

the grid would have a dynamic height with regards to window height as well.

When to use RSpec let()?

Dissenting voice here: after 5 years of rspec I don't like let very much.

1. Lazy evaluation often makes test setup confusing

It becomes difficult to reason about setup when some things that have been declared in setup are not actually affecting state, while others are.

Eventually, out of frustration someone just changes let to let! (same thing without lazy evaluation) in order to get their spec working. If this works out for them, a new habit is born: when a new spec is added to an older suite and it doesn't work, the first thing the writer tries is to add bangs to random let calls.

Pretty soon all the performance benefits are gone.

2. Special syntax is unusual to non-rspec users

I would rather teach Ruby to my team than the tricks of rspec. Instance variables or method calls are useful everywhere in this project and others, let syntax will only be useful in rspec.

3. The "benefits" allow us to easily ignore good design changes

let() is good for expensive dependencies that we don't want to create over and over. It also pairs well with subject, allowing you to dry up repeated calls to multi-argument methods

Expensive dependencies repeated in many times, and methods with big signatures are both points where we could make the code better:

  • maybe I can introduce a new abstraction that isolates a dependency from the rest of my code (which would mean fewer tests need it)
  • maybe the code under test is doing too much
  • maybe I need to inject smarter objects instead of a long list of primitives
  • maybe I have a violation of tell-don't-ask
  • maybe the expensive code can be made faster (rarer - beware of premature optimisation here)

In all these cases, I can address the symptom of difficult tests with a soothing balm of rspec magic, or I can try address the cause. I feel like I spent way too much of the last few years on the former and now I want some better code.

To answer the original question: I would prefer not to, but I do still use let. I mostly use it to fit in with the style of the rest of the team (it seems like most Rails programmers in the world are now deep into their rspec magic so that is very often). Sometimes I use it when I'm adding a test to some code that I don't have control of, or don't have time to refactor to a better abstraction: i.e. when the only option is the painkiller.

How to get all child inputs of a div element (jQuery)

The 'find' method can be used to get all child inputs of a container that has already been cached to save looking it up again (whereas the 'children' method will only get the immediate children). e.g.

var panel= $("#panel");
var inputs = panel.find("input");

how to change listen port from default 7001 to something different?

if your port is 7001, since it's the default it might not be mentioned in the config.xml. config.xml only reports stuff which differs from the default, for sake of simplicity.

apart from the config.xml, you should look into a number of other places under your domain-home:

bin/stopWebLogic.sh
bin/stopManagedWebLogic.sh
bin/startManagedWebLogic.sh
config/fmwconfig/servers/osbts1as/applications/em/META-INF/emoms.properties
config/config.xml
init-info/startscript.xml
init-info/tokenValue.properties

servers/osbts1as/data/nodemanager/osbts1as.url
servers/osbts1as/data/ldap/conf/replicas.prop
servers/osbts1ms1/data/nodemanager/osbts1ms1.url
servers/osbts1ms1/data/nodemanager/startup.properties

servers/osbts1ms2/data/nodemanager/osbts1ms2.url
servers/osbts1ms2/data/nodemanager/startup.properties
startManagedWebLogic_readme.txt
sysman/state/targets.xml

And don't forget to update any internal URIs of your deployed code.

See also http://www.javamonamour.org/2013/04/weblogic-change-admin-port-number.html

Especially changing the listen address/port of the admin can be troublesome. If you change only the managed server, it's a lot easier.

The best option is just rebuilding the domain.

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

SQL join on multiple columns in same tables

Join like this:

ON a.userid = b.sourceid AND a.listid = b.destinationid;

C compile error: Id returned 1 exit status

1d returned 1 exit status error

First of all you have to create a project by clicking file new and then project and give project name select the language c or c++ and select empty also. Then your program is under that project... And then give a program name save it.... Ensure that your under some project to compile and run a program...

How can I select random files from a directory in bash?

This is an even later response to @gniourf_gniourf's late answer, which I just upvoted because it's by far the best answer, twice over. (Once for avoiding eval and once for safe filename handling.)

But it took me a few minutes to untangle the "not very well documented" feature(s) this answer uses. If your Bash skills are solid enough that you saw immediately how it works, then skip this comment. But I didn't, and having untangled it I think it's worth explaining.

Feature #1 is the shell's own file globbing. a=(*) creates an array, $a, whose members are the files in the current directory. Bash understands all the weirdnesses of filenames, so that list is guaranteed correct, guaranteed escaped, etc. No need to worry about properly parsing textual file names returned by ls.

Feature #2 is Bash parameter expansions for arrays, one nested within another. This starts with ${#ARRAY[@]}, which expands to the length of $ARRAY.

That expansion is then used to subscript the array. The standard way to find a random number between 1 and N is to take the value of random number modulo N. We want a random number between 0 and the length of our array. Here's the approach, broken into two lines for clarity's sake:

LENGTH=${#ARRAY[@]}
RANDOM=${a[RANDOM%$LENGTH]}

But this solution does it in a single line, removing the unnecessary variable assignment.

Feature #3 is Bash brace expansion, although I have to confess I don't entirely understand it. Brace expansion is used, for instance, to generate a list of 25 files named filename1.txt, filename2.txt, etc: echo "filename"{1..25}".txt".

The expression inside the subshell above, "${a[RANDOM%${#a[@]}]"{1..42}"}", uses that trick to produce 42 separate expansions. The brace expansion places a single digit in between the ] and the }, which at first I thought was subscripting the array, but if so it would be preceded by a colon. (It would also have returned 42 consecutive items from a random spot in the array, which is not at all the same thing as returning 42 random items from the array.) I think it's just making the shell run the expansion 42 times, thereby returning 42 random items from the array. (But if someone can explain it more fully, I'd love to hear it.)

The reason N has to be hardcoded (to 42) is that brace expansion happens before variable expansion.

Finally, here's Feature #4, if you want to do this recursively for a directory hierarchy:

shopt -s globstar
a=( ** )

This turns on a shell option that causes ** to match recursively. Now your $a array contains every file in the entire hierarchy.

fatal: git-write-tree: error building trees

To follow up on malat's response, you can avoid losing changes by creating a patch and reapply it at a later time.

git diff --no-prefix > patch.txt
patch -p0 < patch.txt

Store your patch outside the repository folder for safety.

How can I show data using a modal when clicking a table row (using bootstrap)?

One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.

I am just going to show as a static example which you can accommodate in your real world.

On each of your <tr>'s add a data attribute for id (i.e. data-id) with the corresponding id value and specify a data-target, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal to make this a trigger for modal.

  <tr data-toggle="modal" data-id="1" data-target="#orderModal">
            <td>1</td>
            <td>24234234</td>
            <td>A</td>
  </tr>
  <tr data-toggle="modal" data-id="2" data-target="#orderModal">
            <td>2</td>
            <td>24234234</td>
            <td>A</td>
        </tr>
  <tr data-toggle="modal" data-id="3" data-target="#orderModal">
            <td>3</td>
            <td>24234234</td>
            <td>A</td>
  </tr>

And now in the javascript just set up the modal just once and event listen to its events so you can do your work.

$(function(){
    $('#orderModal').modal({
        keyboard: true,
        backdrop: "static",
        show:false,

    }).on('show', function(){ //subscribe to show method
          var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });
});

Demo

Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.

Alternative ways here:

Demo2 or Demo3

Facebook Post Link Image

Use the facebook lintter available here. http://developers.facebook.com/tools/lint/

This will check your link and re fetch any images. this also clears any old cache.

Or try this - https://developers.facebook.com/tools/debug

Can git undo a checkout of unstaged files

Dude,

lets say you're a very lucky guy just like I've been, go back to your editor and do an undo(command + Z for mac), you should see your lost content in the file. Hope it helped you. Of course, this will work only for existing files.

Difference between Statement and PreparedStatement

Advantages of a PreparedStatement:

  • Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.

  • Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the values

    preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email, birthdate, photo) VALUES (?, ?, ?, ?)");
    preparedStatement.setString(1, person.getName());
    preparedStatement.setString(2, person.getEmail());
    preparedStatement.setTimestamp(3, new Timestamp(person.getBirthdate().getTime()));
    preparedStatement.setBinaryStream(4, person.getPhoto());
    preparedStatement.executeUpdate();
    

    and thus don't inline the values in the SQL string by string-concatenating.

    preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email) VALUES ('" + person.getName() + "', '" + person.getEmail() + "'");
    preparedStatement.executeUpdate();
    
  • Eases setting of non-standard Java objects in a SQL string, e.g. Date, Time, Timestamp, BigDecimal, InputStream (Blob) and Reader (Clob). On most of those types you can't "just" do a toString() as you would do in a simple Statement. You could even refactor it all to using PreparedStatement#setObject() inside a loop as demonstrated in the utility method below:

    public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException {
        for (int i = 0; i < values.length; i++) {
            preparedStatement.setObject(i + 1, values[i]);
        }
    }
    

    Which can be used as below:

    preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email, birthdate, photo) VALUES (?, ?, ?, ?)");
    setValues(preparedStatement, person.getName(), person.getEmail(), new Timestamp(person.getBirthdate().getTime()), person.getPhoto());
    preparedStatement.executeUpdate();
    

How do I split a string in Rust?

There are three simple ways:

  1. By separator:

     s.split("separator")  |  s.split('/')  |  s.split(char::is_numeric)
    
  2. By whitespace:

     s.split_whitespace()
    
  3. By newlines:

     s.lines()
    
  4. By regex: (using regex crate)

     Regex::new(r"\s").unwrap().split("one two three")
    

The result of each kind is an iterator:

let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());

Foreign key referencing a 2 columns primary key in SQL Server

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

How to check if that data already exist in the database during update (Mongoose And Express)

There is a more simpler way using the mongoose exists function

router.post("/groups/members", async (ctx) => {
    const group_name = ctx.request.body.group_membership.group_name;
    const member_name = ctx.request.body.group_membership.group_members;
    const GroupMembership = GroupModels.GroupsMembers;
    console.log("group_name : ", group_name, "member : ", member_name);
    try {
        if (
            (await GroupMembership.exists({
                "group_membership.group_name": group_name,
            })) === false
        ) {
            console.log("new function");
            const newGroupMembership = await GroupMembership.insertMany({
                group_membership: [
                    { group_name: group_name, group_members: [member_name] },
                ],
            });
            await newGroupMembership.save();
        } else {
            const UpdateGroupMembership = await GroupMembership.updateOne(
                { "group_membership.group_name": group_name },
                { $push: { "group_membership.$.group_members": member_name } },
            );
            console.log("update function");
            await UpdateGroupMembership.save();
        }
        ctx.response.status = 201;
        ctx.response.message = "A member added to group successfully";
    } catch (error) {
        ctx.body = {
            message: "Some validations failed for Group Member Creation",
            error: error.message,
        };
        console.log(error);
        ctx.throw(400, error);
    }
});

Ubuntu says "bash: ./program Permission denied"

Try this:

sudo chmod +x program_name
./program_name 

$_POST not working. "Notice: Undefined index: username..."

You should check if the POST['username'] is defined. Use this above:

$username = "";

if(isset($_POST['username'])){
    $username = $_POST['username'];
}

"SELECT password FROM users WHERE username='".$username."'"

Java Embedded Databases Comparison

I have used Derby and i really hate it's data type conversion functions, especially date/time functions. (Number Type)<--> Varchar conversion it's a pain.

So that if you plan use data type conversions in your DB statements consider the use of othe embedded DB, i learn it too late.

Latest Derby Version data type conversions

How to click or tap on a TextView text

Although you can resolve the problem by setting the listener to textview, it's recommended not to. You should use flat button as it is a subclass of Button and it provides many attributes which TextView doesn't.


To use flat button, add style="?android:attr/borderlessButtonStyle" attribute -

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="DONE"
    style="?android:attr/borderlessButtonStyle"/>

Setting focus on an HTML input box on page load

This line:

<input type="password" name="PasswordInput"/>

should have an id attribute, like so:

<input type="password" name="PasswordInput" id="PasswordInput"/>

Is it possible to ping a server from Javascript?

Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:

function ping(host, port, pong) {

  var started = new Date().getTime();

  var http = new XMLHttpRequest();

  http.open("GET", "http://" + host + ":" + port, /*async*/true);
  http.onreadystatechange = function() {
    if (http.readyState == 4) {
      var ended = new Date().getTime();

      var milliseconds = ended - started;

      if (pong != null) {
        pong(milliseconds);
      }
    }
  };
  try {
    http.send(null);
  } catch(exception) {
    // this is expected
  }

}

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

I'm using ASP.NET SPA Extensions which creates me a proxy on ports 5000 and 5001 that pass through to Angular's port 4200 during development.

I had had CORS correctly setup for https port 5001 and everything was fine, but I inadvertently went to an old bookmark which was for port 5000. Then suddenly this message arose. As others have said in the console there was a 'preflight' error message.

So regardless of your environment, if you're using CORS make sure you have all ports specified - as the host and port both matter.

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How to inject a Map using the @Value Spring Annotation?

You can inject values into a Map from the properties file using the @Value annotation like this.

The property in the properties file.

propertyname={key1:'value1',key2:'value2',....}

In your code.

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

Note the hashtag as part of the annotation.

ImportError: No module named Crypto.Cipher

Try with pip3:

sudo pip3 install pycrypto

Where are static variables stored in C and C++?

This is how (easy to understand):

stack, heap and static data

iPhone UIView Animation Best Practice

Anyway the "Block" method is preffered now-a-days. I will explain the simple block below.

Consider the snipped below. bug2 and bug 3 are imageViews. The below animation describes an animation with 1 second duration after a delay of 1 second. The bug3 is moved from its center to bug2's center. Once the animation is completed it will be logged "Center Animation Done!".

-(void)centerAnimation:(id)sender
{
NSLog(@"Center animation triggered!");
CGPoint bug2Center = bug2.center;

[UIView animateWithDuration:1
                      delay:1.0
                    options: UIViewAnimationCurveEaseOut
                 animations:^{
                     bug3.center = bug2Center;
                 } 
                 completion:^(BOOL finished){
                     NSLog(@"Center Animation Done!");
                 }];
}

Hope that's clean!!!

replace String with another in java

     String s1 = "HelloSuresh";
     String m = s1.replace("Hello","");
     System.out.println(m);

Why does Node.js' fs.readFile() return a buffer instead of string?

The data variable contains a Buffer object. Convert it into ASCII encoding using the following syntax:

data.toString('ascii', 0, data.length)

Asynchronously:

fs.readFile('test.txt', 'utf8', function (error, data) {
    if (error) throw error;
    console.log(data.toString());
});

Javascript : get <img> src and set as variable?

var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);

Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

When I had this issue with tf.train.string_input_producer() and tf.train.batch() initializing the local variables before I started the Coordinator solved the problem. I had been getting the error when I initialized the local variables after starting the Coordinator.

Javascript isnull

All mentioned solutions are legit but if we're talking about elegance then I'll pitch in with the following example:

//function that checks if an object is null
var isNull = function(obj) {
  return obj == null;
}            

if(isNull(results)){
 return 0;
} else {
  return results[1] || 0;
}

Using the isNull function helps the code be more readable.

What are database normal forms and can you give examples?

1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.

2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:

The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me Codd).

2NF

Say you have a table containing courses that are taken in a certain semester, and you have the following data:

|-----Primary Key----|               uh oh |
                                           V
CourseID | SemesterID | #Places  | Course Name  |
------------------------------------------------|
IT101    |   2009-1   | 100      | Programming  |
IT101    |   2009-2   | 100      | Programming  |
IT102    |   2009-1   | 200      | Databases    |
IT102    |   2010-1   | 150      | Databases    |
IT103    |   2009-2   | 120      | Web Design   |

This is not in 2NF, because the fourth column does not rely upon the entire key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.

Primary Key |

CourseID    |  Course Name |
---------------------------|
IT101       | Programming  |
IT102       | Databases    |
IT103       | Web Design   |

No redundancy!

3NF

Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:

|-----Primary Key----|                           uh oh |
                                                       V
Course  |  Semester  |  #Places   |  TeacherID  | TeacherName  |
---------------------------------------------------------------|
IT101   |   2009-1   |  100       |  332        |  Mr Jones    |
IT101   |   2009-2   |  100       |  332        |  Mr Jones    |
IT102   |   2009-1   |  200       |  495        |  Mr Bentley  |
IT102   |   2010-1   |  150       |  332        |  Mr Jones    |
IT103   |   2009-2   |  120       |  242        |  Mrs Smith   |

Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is not in 3NF. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.

 Primary Key |

 TeacherID   | TeacherName  |
 ---------------------------|
 332         |  Mr Jones    |
 495         |  Mr Bentley  |
 242         |  Mrs Smith   |

No redundancy!!

One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires everything that the lower normal forms had, plus some extra conditions, which must all be fulfilled.

How to terminate a thread when main program ends?

Check this question. The correct answer has great explanation on how to terminate threads the right way: Is there any way to kill a Thread in Python?

To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception "KeyboardInterrupt" and cleanup before exiting. Like this:

try:
    start_thread()  
except (KeyboardInterrupt, SystemExit):
    cleanup_stop_thread()
    sys.exit()

This way you can control what to do whenever the program is abruptly terminated.

You can also use the built-in signal module that lets you setup signal handlers (in your specific case the SIGINT signal): http://docs.python.org/library/signal.html

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

Clear ComboBox selected text

The following code will work:

ComboBox1.SelectedIndex.Equals(String.Empty);

Dynamic WHERE clause in LINQ

This project on CodePlex have what you want.

System.Linq.Dynamic - http://dynamiclinq.codeplex.com/

Project Description

Extends System.Linq.Dynamic to support Execution of Lambda expressions defined in a string against Entity Framework or any provider that supports IQueryable.

As it is an extension of the source code you can find on Scott Guthrie's Blog it will allow you to do things like this:

enter image description here

And things like this:

enter image description here

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

I've just installed the latest idea verion 2108.1 and found this issue, after installed lombok plugin and restart the Idea resolve it.

Bootstrap datetimepicker is not a function

Try to use datepicker/ timepicker instead of datetimepicker like:

replace:

$('#datetimepicker1').datetimepicker();

with:

$('#datetimepicker1').datepicker(); // or timepicker for time picker

How to assign more memory to docker container

If you want to change the default container and you are using Virtualbox, you can do it via the commandline / CLI:

docker-machine stop
VBoxManage modifyvm default --cpus 2
VBoxManage modifyvm default --memory 4096
docker-machine start

Query to count the number of tables I have in MySQL

Hope this helps, and returns only number of tables in a database

Use database;

SELECT COUNT(*) FROM sys.tables;

Javascript : natural sort of alphanumerical strings

Building on @Adrien Be's answer above and using the code that Brian Huisman & David koelle created, here is a modified prototype sorting for an array of objects:

//Usage: unsortedArrayOfObjects.alphaNumObjectSort("name");
//Test Case: var unsortedArrayOfObjects = [{name: "a1"}, {name: "a2"}, {name: "a3"}, {name: "a10"}, {name: "a5"}, {name: "a13"}, {name: "a20"}, {name: "a8"}, {name: "8b7uaf5q11"}];
//Sorted: [{name: "8b7uaf5q11"}, {name: "a1"}, {name: "a2"}, {name: "a3"}, {name: "a5"}, {name: "a8"}, {name: "a10"}, {name: "a13"}, {name: "a20"}]

// **Sorts in place**
Array.prototype.alphaNumObjectSort = function(attribute, caseInsensitive) {
  for (var z = 0, t; t = this[z]; z++) {
    this[z].sortArray = new Array();
    var x = 0, y = -1, n = 0, i, j;

    while (i = (j = t[attribute].charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        this[z].sortArray[++y] = "";
        n = m;
      }
      this[z].sortArray[y] += j;
    }
  }

  this.sort(function(a, b) {
    for (var x = 0, aa, bb; (aa = a.sortArray[x]) && (bb = b.sortArray[x]); x++) {
      if (caseInsensitive) {
        aa = aa.toLowerCase();
        bb = bb.toLowerCase();
      }
      if (aa !== bb) {
        var c = Number(aa), d = Number(bb);
        if (c == aa && d == bb) {
          return c - d;
        } else {
          return (aa > bb) ? 1 : -1;
        }
      }
    }

    return a.sortArray.length - b.sortArray.length;
  });

  for (var z = 0; z < this.length; z++) {
    // Here we're deleting the unused "sortArray" instead of joining the string parts
    delete this[z]["sortArray"];
  }
}

Sublime Text 2 - View whitespace characters

I use Unicode Character Highlighter, can show whitespaces and some other special characters.

Add this by, Package Control

Install packages, unicode ...

How to exclude a directory from ant fileset, based on directories contents

I think one way is first to check whether your file exists and if it exists to exclude the folder from copy:

<target name="excludeLocales">

    <property name="de-DE.file" value="${basedir}/locale/de-DE/incompelte.flag"/>
    <available property="de-DE.file.exists" file="${de-DE.file}" />

    <copy todir="C:/temp/">
        <fileset dir="${basedir}/locale">
            <exclude name="de-DE/**" if="${de-DE.file.exists}"/>
            <include name="xy/**"/>
        </fileset>
    </copy>
</target>

This should work also for the other languages.

java.util.Date and getYear()

Use date format

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);

Disabling browser caching for all browsers from ASP.NET

For what it's worth, I just had to handle this in my ASP.NET MVC 3 application. Here is the code block I used in the Global.asax file to handle this for all requests.

    protected void Application_BeginRequest()
    {
        //NOTE: Stopping IE from being a caching whore
        HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
        Response.Cache.SetExpires(DateTime.Now);
        Response.Cache.SetValidUntilExpires(true);
    }

Disable developer mode extensions pop up in Chrome

Ruby based watir-webdriver use something like this:

browser=Watir::Browser.new( :chrome, :switches => %w[ --disable-extensions ] )

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

Use TO_TIMESTAMP function

TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')

The AWS Access Key Id does not exist in our records

I had the same problem in windows and using the module aws-sdk of javascript. I have changed my IAM credentials and the problem persisted even if i give the new credentials through the method update like this

s3.config.update({
    accessKeyId: 'ACCESS_KEY_ID',
    secretAccessKey: 'SECRET_ACCESS_KEY',
    region: 'REGION',
});

After a while i found that the module aws-sdk had created a file inside the folder User on windows with this path

C:\Users\User\.aws\credentials

. The credentials inside this file take precedence over the other data passed through the method update.

The solution for me was to write here

C:\Users\User\.aws\credentials

the new credentials and not with the method s3.config.update

How to fill color in a cell in VBA?

Non VBA Solution:

Use Conditional Formatting rule with formula: =ISNA(A1) (to highlight cells with all errors - not only #N/A, use =ISERROR(A1))

enter image description here

VBA Solution:

Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16) and .SpecialCells(xlCellTypeConstants, 16)to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then)

Sub ColorCells()
    Dim Data As Range, Data2 As Range, cell As Range
    Dim currentsheet As Worksheet

    Set currentsheet = ActiveWorkbook.Sheets("Comparison")

    With currentsheet.Range("A2:AW" & Rows.Count)
        .Interior.Color = xlNone
        On Error Resume Next
        'select only cells with errors
        Set Data = .SpecialCells(xlCellTypeFormulas, 16)
        Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
        On Error GoTo 0
    End With

    If Not Data2 Is Nothing Then
        If Not Data Is Nothing Then
            Set Data = Union(Data, Data2)
        Else
            Set Data = Data2
        End If
    End If

    If Not Data Is Nothing Then
        For Each cell In Data
            If cell.Text = "#N/A" Then
               cell.Interior.ColorIndex = 4
            End If
        Next
    End If
End Sub

Note, to highlight cells witn any error (not only "#N/A"), replace following code

If Not Data Is Nothing Then
   For Each cell In Data
       If cell.Text = "#N/A" Then
          cell.Interior.ColorIndex = 3
       End If
   Next
End If

with

If Not Data Is Nothing Then Data.Interior.ColorIndex = 3

UPD: (how to add CF rule through VBA)

Sub test()
    With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
        .Delete
        .Add Type:=xlExpression, Formula1:="=ISNA(A1)"
        .Item(1).Interior.ColorIndex = 3
    End With
End Sub

Ignore 'Security Warning' running script from command line

Try this, edit the file with:

notepad foo.ps1:Zone.Identifier

And set 'ZoneId=0'

Changing upload_max_filesize on PHP

I got this to work using a .user.ini file in the same directory as my index.php script that loads my app. Here are the contents:

upload_max_filesize = "20M"
post_max_size = "25M"

This is the recommended solution for Heroku.

How to make div fixed after you scroll to that div?

<script>
if($(window).width() >= 1200){
    (function($) {
        var element = $('.to_move_content'),
            originalY = element.offset().top;

        // Space between element and top of screen (when scrolling)
        var topMargin = 10;

        // Should probably be set in CSS; but here just for emphasis
        element.css('position', 'relative');

        $(window).on('scroll', function(event) {
            var scrollTop = $(window).scrollTop();

            element.stop(false, false).animate({
                top: scrollTop < originalY
                    ? 0
                    : scrollTop - originalY + topMargin
            }, 0);
        });
    })(jQuery);
}

Try this ! just add class .to_move_content to you div

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You can also use $.parseJSON(data) that will explicit convert a string thats come from a PHP script to a real JSON array.

Access a global variable in a PHP function

You can do one of the following:

<?php
    $data = 'My data';

    function menugen() {
        global $data;
        echo "[" . $data . "]";
    }

    menugen();

Or

<?php
    $data = 'My data';

    function menugen() {
        echo "[" . $GLOBALS['data'] . "]";
    }

    menugen();

That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example, instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called dependency injection. It makes your life a lot easier when you implement automated testing (which you should).

How do I (or can I) SELECT DISTINCT on multiple columns?

If your DBMS doesn't support distinct with multiple columns like this:

select distinct(col1, col2) from table

Multi select in general can be executed safely as follows:

select distinct * from (select col1, col2 from table ) as x

As this can work on most of the DBMS and this is expected to be faster than group by solution as you are avoiding the grouping functionality.

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

Find unused code

Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.

Get selected option from select element

With less jQuery:

<select name="ddlCodes"
 onchange="$('#txtEntry2').text(this.options[this.selectedIndex].value);">

this.options[this.selectedIndex].value is plain JavaScript.

(Source: German SelfHTML)

How to set default value to all keys of a dict object in python?

You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.

class cDefaultDict(dict):
    # dictionary that returns zero for missing keys
    # keys with zero values are not stored

    def __missing__(self,key):
        return 0

    def __setitem__(self, key, value):
        if value==0:
            if key in self:  # returns zero anyway, so no need to store it
                del self[key]
        else:
            dict.__setitem__(self, key, value)

WCF ServiceHost access rights

Please open your Visual Studio as administrator:

enter image description here

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

Find and copy files

i faced an issue something like this...

Actually, in two ways you can process find command output in copy command

  1. If find command's output doesn't contain any space i.e if file name doesn't contain space in it then you can use below mentioned command:

    Syntax: find <Path> <Conditions> | xargs cp -t <copy file path>

    Example: find -mtime -1 -type f | xargs cp -t inner/

  2. But most of the time our production data files might contain space in it. So most of time below mentioned command is safer:

    Syntax: find <path> <condition> -exec cp '{}' <copy path> \;

    Example find -mtime -1 -type f -exec cp '{}' inner/ \;

In the second example, last part i.e semi-colon is also considered as part of find command, that should be escaped before press the enter button. Otherwise you will get an error something like this

find: missing argument to `-exec'

In your case, copy command syntax is wrong in order to copy find file into /home/shantanu/tosend. The following command will work:

find /home/shantanu/processed/ -name '*2011*.xml' -exec cp  {} /home/shantanu/tosend \;

When is del useful in Python?

There is a specific example of when you should use del (there may be others, but I know about this one off hand) when you are using sys.exc_info() to inspect an exception. This function returns a tuple, the type of exception that was raised, the message, and a traceback.

The first two values are usually sufficient to diagnose an error and act on it, but the third contains the entire call stack between where the exception was raised and where the the exception is caught. In particular, if you do something like

try:
    do_evil()
except:
    exc_type, exc_value, tb = sys.exc_info()
    if something(exc_value):
        raise

the traceback, tb ends up in the locals of the call stack, creating a circular reference that cannot be garbage collected. Thus, it is important to do:

try:
    do_evil()
except:
    exc_type, exc_value, tb = sys.exc_info()
    del tb
    if something(exc_value):
        raise

to break the circular reference. In many cases where you would want to call sys.exc_info(), like with metaclass magic, the traceback is useful, so you have to make sure that you clean it up before you can possibly leave the exception handler. If you don't need the traceback, you should delete it immediately, or just do:

exc_type, exc_value = sys.exc_info()[:2]

To avoid it all together.

jQuery Array of all selected checkboxes (by class)

You can use the :checkbox and :checked pseudo-selectors and the .class selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.

Then you can easily use the Traversing/map method to get an array of values:

var values = $('input:checkbox:checked.group1').map(function () {
  return this.value;
}).get(); // ["18", "55", "10"]

SQL Statement with multiple SETs and WHEREs

No, you would need to create a seperate query for each update.

Get JavaScript object from array of objects by value of property

var result = jsObjects.filter(x=> x.b === 6);

will be better, using return in filter sometimes you can't get result (I dunno why)

How can I use JQuery to post JSON data?

You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.

If you pass the data as a string, it won't be serialized:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

How to print a dictionary's key?

# highlighting how to use a named variable within a string:
mapping = {'a': 1, 'b': 2}

# simple method:
print(f'a: {mapping["a"]}')
print(f'b: {mapping["b"]}')

# programmatic method:
for key, value in mapping.items():
    print(f'{key}: {value}')

# yields:
# a 1
# b 2

# using list comprehension
print('\n'.join(f'{key}: {value}' for key, value in dict.items()))


# yields:
# a: 1
# b: 2

Edit: Updated for python 3's f-strings...

How do you set EditText to only accept numeric values in Android?

Try the following code:

Edittext_name.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

It will allow you to enter just numbers. You cannot enter chars. if you want to enter chars, not numbers, you can edit the values between the quotes inside getInstance.

Colon (:) in Python list index

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

How can we draw a vertical line in the webpage?

There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0; and bottom:0; style.

Try this:

CSS

.vr {
    width:10px;
    background-color:#000;
    position:absolute;
    top:0;
    bottom:0;
    left:150px;
}

HTML

<div class="vr">&nbsp;</div>

Demo

range() for floats

There is no such built-in function, but you can use the following (Python 3 code) to do the job as safe as Python allows you to.

from fractions import Fraction

def frange(start, stop, jump, end=False, via_str=False):
    """
    Equivalent of Python 3 range for decimal numbers.

    Notice that, because of arithmetic errors, it is safest to
    pass the arguments as strings, so they can be interpreted to exact fractions.

    >>> assert Fraction('1.1') - Fraction(11, 10) == 0.0
    >>> assert Fraction( 0.1 ) - Fraction(1, 10) == Fraction(1, 180143985094819840)

    Parameter `via_str` can be set to True to transform inputs in strings and then to fractions.
    When inputs are all non-periodic (in base 10), even if decimal, this method is safe as long
    as approximation happens beyond the decimal digits that Python uses for printing.


    For example, in the case of 0.1, this is the case:

    >>> assert str(0.1) == '0.1'
    >>> assert '%.50f' % 0.1 == '0.10000000000000000555111512312578270211815834045410'


    If you are not sure whether your decimal inputs all have this property, you are better off
    passing them as strings. String representations can be in integer, decimal, exponential or
    even fraction notation.

    >>> assert list(frange(1, 100.0, '0.1', end=True))[-1] == 100.0
    >>> assert list(frange(1.0, '100', '1/10', end=True))[-1] == 100.0
    >>> assert list(frange('1', '100.0', '.1', end=True))[-1] == 100.0
    >>> assert list(frange('1.0', 100, '1e-1', end=True))[-1] == 100.0
    >>> assert list(frange(1, 100.0, 0.1, end=True))[-1] != 100.0
    >>> assert list(frange(1, 100.0, 0.1, end=True, via_str=True))[-1] == 100.0

    """
    if via_str:
        start = str(start)
        stop = str(stop)
        jump = str(jump)
    start = Fraction(start)
    stop = Fraction(stop)
    jump = Fraction(jump)
    while start < stop:
        yield float(start)
        start += jump
    if end and start == stop:
        yield(float(start))

You can verify all of it by running a few assertions:

assert Fraction('1.1') - Fraction(11, 10) == 0.0
assert Fraction( 0.1 ) - Fraction(1, 10) == Fraction(1, 180143985094819840)

assert str(0.1) == '0.1'
assert '%.50f' % 0.1 == '0.10000000000000000555111512312578270211815834045410'

assert list(frange(1, 100.0, '0.1', end=True))[-1] == 100.0
assert list(frange(1.0, '100', '1/10', end=True))[-1] == 100.0
assert list(frange('1', '100.0', '.1', end=True))[-1] == 100.0
assert list(frange('1.0', 100, '1e-1', end=True))[-1] == 100.0
assert list(frange(1, 100.0, 0.1, end=True))[-1] != 100.0
assert list(frange(1, 100.0, 0.1, end=True, via_str=True))[-1] == 100.0

assert list(frange(2, 3, '1/6', end=True))[-1] == 3.0
assert list(frange(0, 100, '1/3', end=True))[-1] == 100.0

Code available on GitHub

How to simulate POST request?

Dont forget to add user agent since some server will block request if there's no server agent..(you would get Forbidden resource response) example :

curl -X POST -A 'Mozilla/5.0 (X11; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0' -d "field=acaca&name=afadxx" https://example.com

Reset MySQL root password using ALTER USER statement after install on Mac

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

Use this line...

How to stop docker under Linux

if you have no systemctl and started the docker daemon by:

sudo service docker start

you can stop it by:

sudo service docker stop

Branch from a previous commit using Git

git checkout -b <branch-name> <sha1-of-commit>

Adding null values to arraylist

You can add nulls to the ArrayList, and you will have to check for nulls in the loop:

for(Item i : itemList) {
   if (i != null) {

   }
}

itemsList.size(); would take the null into account.

 List<Integer> list = new ArrayList<Integer>();
 list.add(null);
 list.add (5);
 System.out.println (list.size());
 for (Integer value : list) {
   if (value == null)
       System.out.println ("null value");
   else 
       System.out.println (value);
 }

Output :

2
null value
5

How to change Vagrant 'default' machine name?

I found the multiple options confusing, so I decided to test all of them to see exactly what they do.

I'm using VirtualBox 4.2.16-r86992 and Vagrant 1.3.3.

I created a directory called nametest and ran

vagrant init precise64 http://files.vagrantup.com/precise64.box

to generate a default Vagrantfile. Then I opened the VirtualBox GUI so I could see what names the boxes I create would show up as.

  1. Default Vagrantfile

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
    end
    

    VirtualBox GUI Name: "nametest_default_1386347922"

    Comments: The name defaults to the format DIRECTORY_default_TIMESTAMP.

  2. Define VM

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.define "foohost"
    end
    

    VirtualBox GUI Name: "nametest_foohost_1386347922"

    Comments: If you explicitly define a VM, the name used replaces the token 'default'. This is the name vagrant outputs on the console. Simplifying based on zook's (commenter) input

  3. Set Provider Name

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.provider :virtualbox do |vb|
            vb.name = "foohost"
        end
    end
    

    VirtualBox GUI Name: "foohost"

    Comments: If you set the name attribute in a provider configuration block, that name will become the entire name displayed in the VirtualBox GUI.

    Combined Example: Define VM -and- Set Provider Name

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.define "foohost"
        config.vm.provider :virtualbox do |vb|
            vb.name = "barhost"
        end
    end
    

    VirtualBox GUI Name: "barhost"

    Comments: If you use both methods at the same time, the value assigned to name in the provider configuration block wins. Simplifying based on zook's (commenter) input

  4. Set hostname (BONUS)

    Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
      config.vm.hostname = "buzbar"
    end
    

    Comments: This sets the hostname inside the VM. This would be the output of hostname command in the VM and also this is what's visible in the prompt like vagrant@<hostname>, here it will look like vagrant@buzbar

Final Code

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.hostname = "buzbar"
        config.vm.define "foohost"
        config.vm.provider :virtualbox do |vb|
            vb.name = "barhost"
        end
    end

So there it is. You now know 3 different options you can set and the effects they have. I guess it's a matter of preference at this point? (I'm new to Vagrant, so I can't speak to best practices yet.)

How can I send an email through the UNIX mailx command?

echo "Sending emails ..."
NOW=$(date +"%F %H:%M")
echo $NOW  " Running service" >> open_files.log
header=`echo "Service Restarting: " $NOW`


mail -s "$header" [email protected],   \
              [email protected], \ < open_files.log

MySQL, create a simple function

Try to change CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR this portion to CREATE FUNCTION F_TEST(PID INT) RETURNS TEXT

and change the following line too.

DECLARE NAME_FOUND TEXT DEFAULT "";

It should work.

JFrame Maximize window

Provided that you are extending JFrame:

public void run() {
    MyFrame myFrame = new MyFrame();
    myFrame.setVisible(true);
    myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}

Getting value GET OR POST variable using JavaScript?

With little php is very easy.

HTML part:

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

JavaScript

<script type="text/javascript">
    some_variable = "<?php echo $_POST['some_name']?>";
</script>

Delete worksheet in Excel using VBA

try this within your if statements:

Application.DisplayAlerts = False
Worksheets(“Sheetname”).Delete
Application.DisplayAlerts = True

Adding Python Path on Windows 7

For people getting the windows store window when writing python in the console, all you have to do is go to configuration -> Manage app execution aliases and disable the toggles that say python.

then, add the following folders to the PATH.

C:\Users\alber\AppData\Local\Programs\Python\Python39\
C:\Users\alber\AppData\Local\Programs\Python\Python39\Scripts\

What is %2C in a URL?

It's the ASCII keycode in hexadecimal for a comma (,).

i.e. , = %2C

like in my link suppose i want to order by two fields means in my link it will come like

order_by=id%2Cname which is equal to order_by=id,name .

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

How to get selected option using Selenium WebDriver with Java

Completing the answer:

String selectedOption = new Select(driver.findElement(By.xpath("Type the xpath of the drop-down element"))).getFirstSelectedOption().getText();

Assert.assertEquals("Please select any option...", selectedOption);

Create two threads, one display odd & other even numbers

public class ConsecutiveNumberPrint {

private static class NumberGenerator {

    public int MAX = 100;

    private volatile boolean evenNumberPrinted = true;

    public NumberGenerator(int max) {
        this.MAX = max;
    }

    public void printEvenNumber(int i) throws InterruptedException {
        synchronized (this) {
            if (evenNumberPrinted) {
                wait();
            }
            System.out.println("e = \t" + i);
            evenNumberPrinted = !evenNumberPrinted;
            notify();
        }
    }

    public void printOddNumber(int i) throws InterruptedException {
        synchronized (this) {
            if (!evenNumberPrinted) {
                wait();
            }
            System.out.println("o = \t" + i);
            evenNumberPrinted = !evenNumberPrinted;
            notify();
        }
    }

}

private static class EvenNumberGenerator implements Runnable {

    private NumberGenerator numberGenerator;

    public EvenNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for(int i = 2; i <= numberGenerator.MAX; i+=2)
            try {
                numberGenerator.printEvenNumber(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}

private static class OddNumberGenerator implements Runnable {

    private NumberGenerator numberGenerator;

    public OddNumberGenerator(NumberGenerator numberGenerator) {
        this.numberGenerator = numberGenerator;
    }

    @Override
    public void run() {
        for(int i = 1; i <= numberGenerator.MAX; i+=2) {
            try {
                numberGenerator.printOddNumber(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public static void main(String[] args) {
    NumberGenerator numberGenerator = new NumberGenerator(100);
    EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(numberGenerator);
    OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(numberGenerator);
    new Thread(oddNumberGenerator).start();
    new Thread(evenNumberGenerator).start();

}

}

Ruby combining an array into one string

While a bit more cryptic than join, you can also multiply the array by a string.

@arr * " "

Difference between $(window).load() and $(document).ready() functions

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
    $( document ).ready(function() {
        alert( "document loaded" );
    });

    $( window ).load(function() {
        alert( "window loaded" );
    });
    </script>
</head>
<body>
    <iframe src="http://stackoverflow.com"></iframe>
</body>
</html>

window.load will be triggered after all the iframe content is loaded

Converting Float to Dollars and Cents

Building on @JustinBarber's example and noting @eric.frederich's comment, if you want to format negative values like -$1,000.00 rather than $-1,000.00 and don't want to use locale:

def as_currency(amount):
    if amount >= 0:
        return '${:,.2f}'.format(amount)
    else:
        return '-${:,.2f}'.format(-amount)

Javascript Thousand Separator / string format

Update (7 years later)

The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString

So you can do:

(1234567.89).toLocaleString('en')              // for numeric input
parseFloat("1234567.89").toLocaleString('en')  // for string input

The function implemented below works, too, but simply isn't necessary.

(I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)


Original Answer

According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Edit: To go the other way (convert string with commas to number), you could do something like this:

parseFloat("1,234,567.89".replace(/,/g,''))

How to construct a REST API that takes an array of id's for the resources

As much as I prefer this approach:-

    api.com/users?id=id1,id2,id3,id4,id5

The correct way is

    api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

or

    api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5

This is how rack does it. This is how php does it. This is how node does it as well...

How to fade changing background image

Building on Rampant Creative Group's solution above, I was using jQuery to change the background image of the body tag:

e.g.

$('body').css({'background': 'url(/wp-content/themes/opdemand/img/bg-sea.jpg) fixed', 'background-size': '100% 100%'});

$('body').css({'background': 'url(/wp-content/themes/opdemand/img/bg-trees.jpg) fixed', 'background-size': '100% 100%'});

I had a javascript timer that switched between the two statements.

All I had to do to solve the issue of creating a fadeOut -> fadeIn effect was use Rampant Creative Group's suggestion and add

transition: background 1.5s linear;

to my code. Now it fades out and in beautifully.

Thanks Rampant Creative Group's and SoupEnvy for the edit!!

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also have a look at:

Convert char array to string use C

You're saying you have this:

char array[20]; char string[100];
array[0]='1'; 
array[1]='7'; 
array[2]='8'; 
array[3]='.'; 
array[4]='9';

And you'd like to have this:

string[0]= "178.9"; // where it was stored 178.9 ....in position [0]

You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).

Now if you want to copy the first x characters out of array to string you can do that with memcpy():

memcpy(string, array, x);
string[x] = '\0'; 

YouTube embedded video: set different thumbnail

No. Most YouTube videos only have one pre-generated "poster" thumbnail (480x360). They usually have several other lower resolution thumbnails (120x90). So even if there were an embedding parameter to use an alternate poster image (which there isn't), it's result wouldn't be acceptable.

You can theoretically use the Player API to seek the video to whatever location you want, but this would be a major hack for a minor result.

How can I disable selected attribute from select2() dropdown Jquery?

To disable the complete select2 box, that is no deletion of already selected values and no new insertion, use:

$("id-select2").prop("disabled", true);

where id-select2 is the unique id of select2. you can also use any particular class if defined to address the dropdown.

How can I disable all views inside the layout?

Details

  • Android studio 3.1.4
  • Kotlin 1.2.70
  • checked in minSdkVersion 19

Solution

fun View.forEachChildView(closure: (View) -> Unit) {
    closure(this)
    val groupView = this as? ViewGroup ?: return
    val size = groupView.childCount - 1
    for (i in 0..size) {
        groupView.getChildAt(i).forEachChildView(closure)
    }
}

Usage

val layout = LinearLayout(context!!)
layout.forEachChildView {  it.isEnabled = false  }

val view = View(context!!)
view.forEachChildView {  it.isEnabled = false  }

val fragment = Fragment.instantiate(context, "fragment_id")
fragment.view?.forEachChildView {  it.isEnabled = false  }

Start service in Android

Probably you don't have the service in your manifest, or it does not have an <intent-filter> that matches your action. Examining LogCat (via adb logcat, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.

More likely, you should start the service via:

startService(new Intent(this, UpdaterServiceManager.class));

C convert floating point to int

If you want to round it to lower, just cast it.

float my_float = 42.8f;
int my_int;
my_int = (int)my_float;          // => my_int=42

For other purpose, if you want to round it to nearest, you can make a little function or a define like this:

#define FLOAT_TO_INT(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))

float my_float = 42.8f;
int my_int;
my_int = FLOAT_TO_INT(my_float); // => my_int=43

Be careful, ideally you should verify float is between INT_MIN and INT_MAX before casting it.

How to delete columns in pyspark dataframe

Maybe a little bit off topic, but here is the solution using Scala. Make an Array of column names from your oldDataFrame and delete the columns that you want to drop ("colExclude"). Then pass the Array[Column] to select and unpack it.

val columnsToKeep: Array[Column] = oldDataFrame.columns.diff(Array("colExclude"))
                                               .map(x => oldDataFrame.col(x))
val newDataFrame: DataFrame = oldDataFrame.select(columnsToKeep: _*)

How can I make SMTP authenticated in C#

Set the Credentials property before sending the message.

How can I get the root domain URI in ASP.NET?

For anyone still wondering, a more complete answer is available at http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/.

public string FullyQualifiedApplicationPath
{
    get
    {
        //Return variable declaration
        var appPath = string.Empty;

        //Getting the current context of HTTP request
        var context = HttpContext.Current;

        //Checking the current context content
        if (context != null)
        {
            //Formatting the fully qualified website url/name
            appPath = string.Format("{0}://{1}{2}{3}",
                                    context.Request.Url.Scheme,
                                    context.Request.Url.Host,
                                    context.Request.Url.Port == 80
                                        ? string.Empty
                                        : ":" + context.Request.Url.Port,
                                    context.Request.ApplicationPath);
        }

        if (!appPath.EndsWith("/"))
            appPath += "/";

        return appPath;
    }
}

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

Get the distance between two geo points

Just use the following method, pass it lat and long and get distance in meter:

private static double distance_in_meter(final double lat1, final double lon1, final double lat2, final double lon2) {
    double R = 6371000f; // Radius of the earth in m
    double dLat = (lat1 - lat2) * Math.PI / 180f;
    double dLon = (lon1 - lon2) * Math.PI / 180f;
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(latlong1.latitude * Math.PI / 180f) * Math.cos(latlong2.latitude * Math.PI / 180f) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
    double c = 2f * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double d = R * c;
    return d;
}

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

    <mvc:annotation-driven />
    <mvc:default-servlet-handler />
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <context:component-scan base-package="com.sapta.hr" />

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

    <bean id="messageSource" 
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

Should I put input elements inside a label element?

Referring to the WHATWG (Writing a form's user interface) it is not wrong to put the input field inside the label. This saves you code because the for attribute from the label is no longer needed.

Check that a input to UITextField is numeric only

@property (strong) NSNumberFormatter *numberFormatter;
@property (strong) NSString *oldStringValue;

- (void)awakeFromNib 
{
  [super awakeFromNib];
  self.numberFormatter = [[NSNumberFormatter alloc] init];
  self.oldStringValue = self.stringValue;
  [self setDelegate:self];
}

- (void)controlTextDidChange:(NSNotification *)obj
{
  NSNumber *number = [self.numberFormatter numberFromString:self.stringValue];
  if (number) {
    self.oldStringValue = self.stringValue;
  } else {
    self.stringValue = self.oldStringValue;
  }
}

Pass accepts header parameter to jquery ajax

The other answers do not answer the actual question, but rather provide workarounds which is a shame because it literally takes 10 seconds to figure out what the correct syntax for accepts parameter.

The accepts parameter takes an object which maps the dataType to the Accept header. In your case you don't need to even need to pass the accepts object, as setting the data type to json should be sufficient. However if you do want to configure a custom Accept header this is what you do:

accepts: {"*": "my custom mime type" },

How do I know? Open jquery's source code and search for "accepts". The very first find tells you all you need to know:

    accepts: {
        "*": allTypes,
        text: "text/plain",
        html: "text/html",
        xml: "application/xml, text/xml",
        json: "application/json, text/javascript"
    },

As you see the are default mappings to text, html, xml and json data types.

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

How to convert Base64 String to javascript file object like as from file input form?

Heads up,

JAVASCRIPT

<script>
   function readMtlAtClient(){

       mtlFileContent = '';

       var mtlFile = document.getElementById('mtlFileInput').files[0];
       var readerMTL = new FileReader();

       // Closure to capture the file information.
       readerMTL.onload = (function(reader) {
           return function() {
               mtlFileContent = reader.result;
               mtlFileContent = mtlFileContent.replace('data:;base64,', '');
               mtlFileContent = window.atob(mtlFileContent);

           };
       })(readerMTL);

       readerMTL.readAsDataURL(mtlFile);
   }
</script>

HTML

    <input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput" 
onchange="readMtlAtClient()" accept=".mtl"/>

Then mtlFileContent has your text as a decoded string !

A child container failed during start java.util.concurrent.ExecutionException

You must have packaged the servlet-api.jar along with the other libraries in your war file. You can verify this by opening up your war file and navigating to the WEB-INF/lib folder.

Ideally, you should not provide the servlet-api jar. The container, in your case Tomcat, is responsible for providing it at deploy time to your application. If you try to provide it as well, then issues arise due to version mismatch etc. Best practise is to just avoid packaging it. Remove it from the WEB-INF/lib.

Additional Information

If you are using maven for your packaging, then simply add the provided tag with the dependency and maven will make sure not to package it in the final war file. Something like

<dependency>
    <artifact>..
    <group> ...
    <version> ...
    <scope>provided</scope>
</<dependency>

How to catch an Exception from a thread

Most likely;

  • you don't need to pass the exception from one thread to another.
  • if you want to handle an exception, just do it in the thread which threw it.
  • your main thread doesn't need to wait from the background thread in this example, which actually means you don't need a background thread at all.

However, lets assume you do need to handle an exception from a child thread another. I would use an ExecutorService like this:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Void> future = executor.submit(new Callable<Void>() {
    @Override
    public Void call() throws Exception {
        System.out.println("** Started");
        Thread.sleep(2000);
        throw new IllegalStateException("exception from thread");
    }
});
try {
    future.get(); // raises ExecutionException for any uncaught exception in child
} catch (ExecutionException e) {
    System.out.println("** RuntimeException from thread ");
    e.getCause().printStackTrace(System.out);
}
executor.shutdown();
System.out.println("** Main stopped");

prints

** Started
** RuntimeException from thread 
java.lang.IllegalStateException: exception from thread
    at Main$1.call(Main.java:11)
    at Main$1.call(Main.java:6)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
** Main stopped

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

One is a static import (<%=@ include...>"), the other is a dynamic one (jsp:include). It will affect for example the path you gonna have to specify for your included file. A little research on Google will tell you more.

How do I find the distance between two points?

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)

How to commit to remote git repository

just type "git push" if this doesn't give you a positive replay, then check if you are connected with your repository correctly.

Jquery each - Stop loop and return object

"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."

from http://api.jquery.com/jquery.each/

Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:

_x000D_
_x000D_
function findXX(word) {_x000D_
  $.each(someArray, function(index, value) {_x000D_
    $('body').append('-> ' + index + ":" + value + '<br />');_x000D_
    return !(value == word);_x000D_
  });_x000D_
}_x000D_
$(function() {_x000D_
  someArray = new Array();_x000D_
  someArray[0] = 't5';_x000D_
  someArray[1] = 'z12';_x000D_
  someArray[2] = 'b88';_x000D_
  someArray[3] = 's55';_x000D_
  someArray[4] = 'e51';_x000D_
  someArray[5] = 'o322';_x000D_
  someArray[6] = 'i22';_x000D_
  someArray[7] = 'k954';_x000D_
  findXX('o322');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

A bit more with comments:

_x000D_
_x000D_
function findXX(myA, word) {_x000D_
  let br = '<br />';//create once_x000D_
  let myHolder = $("<div />");//get a holder to not hit DOM a lot_x000D_
  let found = false;//default return_x000D_
  $.each(myA, function(index, value) {_x000D_
    found = (value == word);_x000D_
    myHolder.append('-> ' + index + ":" + value + br);_x000D_
    return !found;_x000D_
  });_x000D_
  $('body').append(myHolder.html());// hit DOM once_x000D_
  return found;_x000D_
}_x000D_
$(function() {_x000D_
  // no horrid global array, easier array setup;_x000D_
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];_x000D_
  // pass the array and the value we want to find, return back a value_x000D_
  let test = findXX(someArray, 'o322');_x000D_
  $('body').append("<div>Found:" + test + "</div>");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

NOTE: array .includes() may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Or just .find() to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

String replace a Backslash

sSource = sSource.replace("\\/", "/");
  • String is immutable - each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable)
  • replaceAll(..) uses regex. You don't need that.

In R, how to find the standard error of the mean?

more generally, for standard errors on any other parameter, you can use the boot package for bootstrap simulations (or write them on your own)

Convert Xml to Table SQL Server

The sp_xml_preparedocument stored procedure will parse the XML and the OPENXML rowset provider will show you a relational view of the XML data.

For details and more examples check the OPENXML documentation.

As for your question,

DECLARE @XML XML
SET @XML = '<rows><row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row></rows>'

DECLARE @handle INT  
DECLARE @PrepareXmlStatus INT  

EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML  

SELECT  *
FROM    OPENXML(@handle, '/rows/row', 2)  
    WITH (
    IdInvernadero INT,
    IdProducto INT,
    IdCaracteristica1 INT,
    IdCaracteristica2 INT,
    Cantidad INT,
    Folio INT
    )  


EXEC sp_xml_removedocument @handle 

Text File Parsing in Java

I'm not sure how efficient it is memory-wise, but my first approach would be using a Scanner as it is incredibly easy to use:

File file = new File("/path/to/my/file.txt");
Scanner input = new Scanner(file);

while(input.hasNext()) {
    String nextToken = input.next();
    //or to process line by line
    String nextLine = input.nextLine();
}

input.close();

Check the API for how to alter the delimiter it uses to split tokens.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had the same problem, you have to load first the Moment.js file!

_x000D_
_x000D_
<script src="path/moment.js"></script>_x000D_
<script src="path/bootstrap-datetimepicker.js"></script>
_x000D_
_x000D_
_x000D_

Definition of a Balanced Tree

  1. The height of a node in a tree is the length of the longest path from that node downward to a leaf, counting both the start and end vertices of the path.
  2. A node in a tree is height-balanced if the heights of its subtrees differ by no more than 1.
  3. A tree is height-balanced if all of its nodes are height-balanced.

Can HTTP POST be limitless?

POST allows for an arbitrary length of data to be sent to a server, but there are limitations based on timeouts/bandwidth etc.

I think basically, it's safer to assume that it's not okay to send lots of data.

python: [Errno 10054] An existing connection was forcibly closed by the remote host

I know this is a very old question but it may be that you need to set the request headers. This solved it for me.

For example 'user-agent', 'accept' etc. here is an example with user-agent:

url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)

How can I get the behavior of GNU's readlink -f on a Mac?

You may be interested in realpath(3), or Python's os.path.realpath. The two aren't exactly the same; the C library call requires that intermediary path components exist, while the Python version does not.

$ pwd
/tmp/foo
$ ls -l
total 16
-rw-r--r--  1 miles    wheel  0 Jul 11 21:08 a
lrwxr-xr-x  1 miles    wheel  1 Jul 11 20:49 b -> a
lrwxr-xr-x  1 miles    wheel  1 Jul 11 20:49 c -> b
$ python -c 'import os,sys;print(os.path.realpath(sys.argv[1]))' c
/private/tmp/foo/a

I know you said you'd prefer something more lightweight than another scripting language, but just in case compiling a binary is insufferable, you can use Python and ctypes (available on Mac OS X 10.5) to wrap the library call:

#!/usr/bin/python

import ctypes, sys

libc = ctypes.CDLL('libc.dylib')
libc.realpath.restype = ctypes.c_char_p
libc.__error.restype = ctypes.POINTER(ctypes.c_int)
libc.strerror.restype = ctypes.c_char_p

def realpath(path):
    buffer = ctypes.create_string_buffer(1024) # PATH_MAX
    if libc.realpath(path, buffer):
        return buffer.value
    else:
        errno = libc.__error().contents.value
        raise OSError(errno, "%s: %s" % (libc.strerror(errno), buffer.value))

if __name__ == '__main__':
    print realpath(sys.argv[1])

Ironically, the C version of this script ought to be shorter. :)

Delete column from SQLite table

PRAGMA foreign_keys=off;

BEGIN TRANSACTION;

ALTER TABLE table1 RENAME TO _table1_old;

CREATE TABLE table1 (
( column1 datatype [ NULL | NOT NULL ],
  column2 datatype [ NULL | NOT NULL ],
  ...
);

INSERT INTO table1 (column1, column2, ... column_n)
  SELECT column1, column2, ... column_n
  FROM _table1_old;

COMMIT;

PRAGMA foreign_keys=on;

For more info: https://www.techonthenet.com/sqlite/tables/alter_table.php

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

Just putting .encode('utf-8') at the end of object will do the job in recent versions of Python.

Map enum in JPA with fixed values?

My own solution to solve this kind of Enum JPA mapping is the following.

Step 1 - Write the following interface that we will use for all enums that we want to map to a db column:

public interface IDbValue<T extends java.io.Serializable> {

    T getDbVal();

}

Step 2 - Implement a custom generic JPA converter as follows:

import javax.persistence.AttributeConverter;

public abstract class EnumDbValueConverter<T extends java.io.Serializable, E extends Enum<E> & IDbValue<T>>
        implements AttributeConverter<E, T> {

    private final Class<E> clazz;

    public EnumDbValueConverter(Class<E> clazz){
        this.clazz = clazz;
    }

    @Override
    public T convertToDatabaseColumn(E attribute) {
        if (attribute == null) {
            return null;
        }
        return attribute.getDbVal();
    }

    @Override
    public E convertToEntityAttribute(T dbData) {
        if (dbData == null) {
            return null;
        }
        for (E e : clazz.getEnumConstants()) {
            if (dbData.equals(e.getDbVal())) {
                return e;
            }
        }
        // handle error as you prefer, for example, using slf4j:
        // log.error("Unable to convert {} to enum {}.", dbData, clazz.getCanonicalName());
        return null;
    }

}

This class will convert the enum value E to a database field of type T (e.g. String) by using the getDbVal() on enum E, and vice versa.

Step 3 - Let the original enum implement the interface we defined in step 1:

public enum Right implements IDbValue<Integer> {
    READ(100), WRITE(200), EDITOR (300);

    private final Integer dbVal;

    private Right(Integer dbVal) {
        this.dbVal = dbVal;
    }

    @Override
    public Integer getDbVal() {
        return dbVal;
    }
}

Step 4 - Extend the converter of step 2 for the Right enum of step 3:

public class RightConverter extends EnumDbValueConverter<Integer, Right> {
    public RightConverter() {
        super(Right.class);
    }
}

Step 5 - The final step is to annotate the field in the entity as follows:

@Column(name = "RIGHT")
@Convert(converter = RightConverter.class)
private Right right;

Conclusion

IMHO this is the cleanest and most elegant solution if you have many enums to map and you want to use a particular field of the enum itself as mapping value.

For all others enums in your project that need similar mapping logic, you only have to repeat steps 3 to 5, that is:

  • implement the interface IDbValue on your enum;
  • extend the EnumDbValueConverter with only 3 lines of code (you may also do this within your entity to avoid creating a separated class);
  • annotate the enum attribute with @Convert from javax.persistence package.

Hope this helps.

Why dict.get(key) instead of dict[key]?

One difference, that can be an advantage, is that if we are looking for a key that doesn't exist we will get None, not like when we use the brackets notation, in which case we will get an error thrown:

print(dictionary.get("address")) # None
print(dictionary["address"]) # throws KeyError: 'address'

Last thing that is cool about the get method, is that it receives an additional optional argument for a default value, that is if we tried to get the score value of a student, but the student doesn't have a score key we can get a 0 instead.

So instead of doing this (or something similar):

score = None
try:
    score = dictionary["score"]
except KeyError:
    score = 0

We can do this:

score = dictionary.get("score", 0)
# score = 0

How to add a JAR in NetBeans

Project Files Services Tabls

go files tabs

drag drop file to libs files hover.

return project tabs and what are you see :)

EXEC sp_executesql with multiple parameters

maybe this help :

declare 
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
'
exec sp_executesql @statement;

this is same as below :

select @text1 + ' beautifull ' + @text2

Crontab Day of the Week syntax

You can also use day names like Mon for Monday, Tue for Tuesday, etc. It's more human friendly.

Notepad++ add to every line

Follow these steps:

  1. Press Ctrl+H to bring up the Find/Replace Dialog.
  2. Choose the Regular expression option near the bottom of the dialog.

To add a word, such as test, at the beginning of each line:

  1. Type ^ in the Find what textbox
  2. Type test in the Replace with textbox
  3. Place cursor in the first line of the file to ensure all lines are affected
  4. Click Replace All button

To add a word, such as test, at the end of each line:

  1. Type $ in the Find what textbox
  2. Type test in the Replace with textbox
  3. Place cursor in the first line of the file to ensure all lines are affected
  4. Click Replace All button

Check whether an input string contains a number in javascript

You can do this using javascript. No need for Jquery or Regex

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

While implementing

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }

Update: To check if a string has numbers in them, you can use regular expressions to do that

var matches = val.match(/\d+/g);
if (matches != null) {
    alert('number');
}

Trigger function when date is selected with jQuery UI datepicker

Use the following code:

$(document).ready(function() {
    $('.date-pick').datepicker( {
     onSelect: function(date) {
        alert(date)
     },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1,
  });
});

You can adjust the parameters yourself :-)

How to use boolean 'and' in Python

As pointed out, "&" in python performs a bitwise and operation, just as it does in C#. and is the appropriate equivalent to the && operator.

Since we're dealing with booleans (i == 5 is True and ii == 10 is also True), you may wonder why this didn't either work anyway (True being treated as an integer quantity should still mean True & True is a True value), or throw an exception (eg. by forbidding bitwise operations on boolean types)

The reason is operator precedence. The "and" operator binds more loosely than ==, so the expression: "i==5 and ii==10" is equivalent to: "(i==5) and (ii==10)"

However, bitwise & has a higher precedence than "==" (since you wouldn't want expressions like "a & 0xff == ch" to mean "a & (0xff == ch)"), so the expression would actually be interpreted as:

if i == (5 & ii) == 10:

Which is using python's operator chaining to mean: does the valuee of ii anded with 5 equal both i and 10. Obviously this will never be true.

You would actually get (seemingly) the right answer if you had included brackets to force the precedence, so:

if (i==5) & (ii=10)

would cause the statement to be printed. It's the wrong thing to do, however - "&" has many different semantics to "and" - (precedence, short-cirtuiting, behaviour with integer arguments etc), so it's fortunate that you caught this here rather than being fooled till it produced less obvious bugs.

How can I divide two integers stored in variables in Python?

Use this line to get the division behavior you want:

from __future__ import division

Alternatively, you could use modulus:

if (a % b) == 0: #do something

Twitter Bootstrap - borders

If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.

For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:

.row {
    zoom: 1;
    margin-left: -20px;
}

.row > [class*="span"] {
    display: inline;
    float: left;
    margin-left: 20px;
}

.span4 {
    width: 220px;
}

To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).

Screenshot of Example Page

For example, to allow for the left border on the sidebar, they added this CSS in the <head> after the the main <link href="../bootstrap.css" rel="stylesheet">.

.content .span4 {
    margin-left: 0;
    padding-left: 19px;
    border-left: 1px solid #eee;
}

You'll see they've reduced padding-left by 1px to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.

I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.

Parse JSON from JQuery.ajax success data

you can use the jQuery parseJSON method:

var Data = $.parseJSON(response);

Launch Failed. Binary not found. CDT on Eclipse Helios

I faced the same problem. I have Eclipse Indigo and Eclipse Luna on Ubuntu. I tried many solutions, but none worked. Here's how you can try :) Try it in order :)

  1. Either do Build All and then compile :)
  2. Install G++ Compiler
  3. Windows->Preferences->NEW CDT PRoject-> Makefile-> Binary Parsers-> Choose Cywin or Window PE depending on your Os :)
  4. Change your toolchain to cywin gcc
  5. Project->Properties->Environment-> Release Active

After 1,2, 3, and 4, I tried changing paths, and other stuff, but nothing worked. In the end, I noticed that it mentioned Debug Active was not configured. So when I changed it to Release Active, it worked. Do note that change in environment and path is not required.

How to redirect single url in nginx?

location ~ /issue([0-9]+) {
    return 301 http://example.com/shop/issues/custom_isse_name$1;
}

How do I get bit-by-bit data from an integer value in C?

Here's one way to do it—there are many others:

bool b[4];
int v = 7;  // number to dissect

for (int j = 0;  j < 4;  ++j)
   b [j] =  0 != (v & (1 << j));

It is hard to understand why use of a loop is not desired, but it is easy enough to unroll the loop:

bool b[4];
int v = 7;  // number to dissect

b [0] =  0 != (v & (1 << 0));
b [1] =  0 != (v & (1 << 1));
b [2] =  0 != (v & (1 << 2));
b [3] =  0 != (v & (1 << 3));

Or evaluating constant expressions in the last four statements:

b [0] =  0 != (v & 1);
b [1] =  0 != (v & 2);
b [2] =  0 != (v & 4);
b [3] =  0 != (v & 8);

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

How to Use Sockets in JavaScript\HTML?

I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.

How to trigger a click on a link using jQuery

We can do it in many ways...

CASE - 1

We can use trigger like this : $("#myID").trigger("click");

CASE - 2

We can use click() function like this : $("#myID").click();

CASE - 3

If we want to write function on programmatically click then..

$("#myID").click(function() {
  console.log("Clicked");
// Do here whatever you want
});

CASE - 4

// Triggering a native browser event using the simulate plugin
$("#myID").simulate( "click" );  

Also you can refer this : https://learn.jquery.com/events/triggering-event-handlers/

Pyspark: display a spark data frame in a table format

Yes: call the toPandas method on your dataframe and you'll get an actual pandas dataframe !

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

Return a "NULL" object if search result not found

In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:

Attr *getAttribute(const string& attribute_name) const {
   //search collection
   //if found at i
        return &attributes[i];
   //if not found
        return nullptr;
}

Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.

(By the way, I'm a little worried about your method being const and returning a non-const attribute. For philosophical reasons, I'd suggest returning const Attr *. If you also may want to modify this attribute, you can overload with a non-const method returning a non-const attribute as well.)

on change event for file input element

Use the files filelist of the element instead of val()

$("input[type=file]").on('change',function(){
    alert(this.files[0].name);
});

VC++ fatal error LNK1168: cannot open filename.exe for writing

Enable “Application Experience” service. Launch a console window and type net start AeLookupSvc

How can I remove a commit on GitHub?

  1. git log to find out the commit you want to revert

  2. git push origin +7f6d03:master while 7f6d03 is the commit before the wrongly pushed commit. + was for force push

And that's it.

Here is a very good guide that solves your problem, easy and simple!

QByteArray to QString

you can use QString::fromAscii()

QByteArray data = entity->getData();
QString s_data = QString::fromAscii(data.data());

with data() returning a char*

for QT5, you should use fromCString() instead, as fromAscii() is deprecated, see https://bugreports.qt-project.org/browse/QTBUG-21872 https://bugreports.qt.io/browse/QTBUG-21872

Read a text file using Node.js?

The async way of life:

#! /usr/bin/node

const fs = require('fs');

function readall (stream)
{
  return new Promise ((resolve, reject) => {
    const chunks = [];
    stream.on ('error', (error) => reject (error));
    stream.on ('data',  (chunk) => chunk && chunks.push (chunk));
    stream.on ('end',   ()      => resolve (Buffer.concat (chunks)));
  });
}

function readfile (filename)
{
  return readall (fs.createReadStream (filename));
}

(async () => {
  let content = await readfile ('/etc/ssh/moduli').catch ((e) => {})
  if (content)
    console.log ("size:", content.length,
                 "head:", content.slice (0, 46).toString ());
})();

How to make html <select> element look like "disabled", but pass values?

if you don't want add the attr disabled can do it programmatically

can disable the edition into the <select class="yourClass"> element with this code:

//bloqueo selects
  //block all selects
  jQuery(document).on("focusin", 'select.yourClass', function (event) {
    var $selectDiabled = jQuery(this).attr('disabled', 'disabled');
    setTimeout(function(){ $selectDiabled.removeAttr("disabled"); }, 30);
  });

if you want try it can see it here: https://jsfiddle.net/9kjqjLyq/

How to use http.client in Node.js if there is basic authorization

var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";

request.get( {
    url : url,
    headers : {
        "Authorization" : auth
    }
  }, function(error, response, body) {
      console.log('body : ', body);
  } );

How can I conditionally require form inputs with AngularJS?

There's no need to write a custom directive. Angular's documentation is good but not complete. In fact, there is a directive called ngRequired, that takes an Angular expression.

<input type='email'
       name='email'
       ng-model='contact.email' 
       placeholder='[email protected]'
       ng-required='!contact.phone' />

<input type='text'
       ng-model='contact.phone'             
       placeholder='(xxx) xxx-xxxx'
       ng-required='!contact.email' />  

Here's a more complete example: http://jsfiddle.net/uptnx/1/

What is the best open-source java charting library? (other than jfreechart)

There is charts4j which is a charts and graphs API. It enables developers to programmatically create the charts available in the Google Chart API through a straightforward and intuitive Java API.

Disclaimer: I wrote charts4j. We will be doing another major release in the next few weeks.

Viewing PDF in Windows forms using C#

i think the easiest way is to use the Adobe PDF reader COM Component

  1. right click on your toolbox & select "Choose Items"
  2. Select the "COM Components" tab
  3. Select "Adobe PDF Reader" then click ok
  4. Drag & Drop the control on your form & modify the "src" Property to the PDF files you want to read

i hope this helps

Importing files from different folder

The code below imports the Python script given by it's path, no matter where it is located, in a Python version-save way:

def import_module_by_path(path):
    name = os.path.splitext(os.path.basename(path))[0]
    if sys.version_info[0] == 2:   
        # Python 2
        import imp
        return imp.load_source(name, path)
    elif sys.version_info[:2] <= (3, 4):  
        # Python 3, version <= 3.4
        from importlib.machinery import SourceFileLoader
        return SourceFileLoader(name, path).load_module()
    else:                            
        # Python 3, after 3.4
        import importlib.util
        spec = importlib.util.spec_from_file_location(name, path)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        return mod

This code is not written by me; I found it in the codebase of psutils, in psutils.test.__init__.py (line 1042; permalink to most recent commit as of 09.10.2020).

Usage example:

script = "/home/username/Documents/some_script.py"
some_module = import_module_by_path(script)
print(some_module.foo())

Caveat: The module will be treated as top-level. If it's a submodule of some bigger project, then relative imports from parent packages will fail.

Split function equivalent in T-SQL?

This simple CTE will give what's needed:

DECLARE @csv varchar(max) = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15';
--append comma to the list for CTE to work correctly
SET @csv = @csv + ',';
--remove double commas (empty entries)
SET @csv = replace(@csv, ',,', ',');
WITH CteCsv AS (
    SELECT CHARINDEX(',', @csv) idx, SUBSTRING(@csv, 1, CHARINDEX(',', @csv) - 1) [Value]
    UNION ALL
    SELECT CHARINDEX(',', @csv, idx + 1), SUBSTRING(@csv, idx + 1, CHARINDEX(',', @csv, idx + 1) - idx - 1) FROM CteCsv
    WHERE CHARINDEX(',', @csv, idx + 1) > 0
)

SELECT [Value] FROM CteCsv

Count the number of occurrences of each letter in string

You can use the following code.

main()
{
    int i = 0,j=0,count[26]={0};
    char ch = 97;
    char string[100]="Hello how are you buddy ?";
    for (i = 0; i < 100; i++)
    {
        for(j=0;j<26;j++)
            {
            if (tolower(string[i]) == (ch+j))
                {
                    count[j]++;
                }
        }
    }
    for(j=0;j<26;j++)
        {

            printf("\n%c -> %d",97+j,count[j]);

    }

}

Hope this helps.

Show/hide image with JavaScript

If you already have a JavaScript function called showImage defined to show the image, you can link as such:

<a href="javascript:showImage()">show image</a>

If you need help defining the function, I would try:

function showImage() {
    var img = document.getElementById('myImageId');
    img.style.visibility = 'visible';
}

Or, better yet,

function setImageVisible(id, visible) {
    var img = document.getElementById(id);
    img.style.visibility = (visible ? 'visible' : 'hidden');
}

Then, your links would be:

<a href="javascript:setImageVisible('myImageId', true)">show image</a>
<a href="javascript:setImageVisible('myImageId', false)">hide image</a>

The first day of the current month in php using date_modify as DateTime object

Here is what I use.

First day of the month:

date('Y-m-01');

Last day of the month:

date('Y-m-t');

Reverting single file in SVN to a particular revision

If you want to roll back an individual file from a specific revision and be able to commit, then do:

svn merge -c -[OldRev#] [Filename]

ie. svn merge -c -150 myfile.py

Note the negative on the revision number

Unexpected token < in first line of HTML

In my case I got this error because of a line

<script src="#"></script> 

Chrome tried to interpret the current HTML file then as javascript.

Import-CSV and Foreach

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
    $IP
}

Get-content Filename returns an array of strings for each line.

On the first string only, I split it based on ",". Dumping it into $IP_Array.

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
  if ($IP -eq "2.2.2.2") {
    Write-Host "Found $IP"
  }
}

Force browser to clear cache

I had similiar problem and this is how I solved it:

  1. In index.html file I've added manifest:

    <html manifest="cache.manifest">
    
  2. In <head> section included script updating the cache:

    <script type="text/javascript" src="update_cache.js"></script>
    
  3. In <body> section I've inserted onload function:

    <body onload="checkForUpdate()">
    
  4. In cache.manifest I've put all files I want to cache. It is important now that it works in my case (Apache) just by updating each time the "version" comment. It is also an option to name files with "?ver=001" or something at the end of name but it's not needed. Changing just # version 1.01 triggers cache update event.

    CACHE MANIFEST
    # version 1.01
    style.css
    imgs/logo.png
    #all other files
    

    It's important to include 1., 2. and 3. points only in index.html. Otherwise

    GET http://foo.bar/resource.ext net::ERR_FAILED
    

    occurs because every "child" file tries to cache the page while the page is already cached.

  5. In update_cache.js file I've put this code:

    function checkForUpdate()
    {
        if (window.applicationCache != undefined && window.applicationCache != null)
        {
            window.applicationCache.addEventListener('updateready', updateApplication);
        }
    }
    function updateApplication(event)
    {
        if (window.applicationCache.status != 4) return;
        window.applicationCache.removeEventListener('updateready', updateApplication);
        window.applicationCache.swapCache();
        window.location.reload();
    }
    

Now you just change files and in manifest you have to update version comment. Now visiting index.html page will update the cache.

The parts of solution aren't mine but I've found them through internet and put together so that it works.

How do I get the opposite (negation) of a Boolean in Python?

If you are trying to implement a toggle, so that anytime you re-run a persistent code its being negated, you can achieve that as following:

try:
    toggle = not toggle
except NameError:
    toggle = True

Running this code will first set the toggle to True and anytime this snippet ist called, toggle will be negated.

PHP Include for HTML?

I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.

Converting Columns into rows with their respective data in sql server

As an alternative:

Using CROSS APPLY and VALUES performs this operation quite simply and efficiently with just a single pass of the table (unlike union queries that do one pass for every column)

SELECT
    ca.ColName, ca.ColValue
FROM YOurTable
CROSS APPLY (
      Values
         ('ScripName' , ScripName),
         ('ScripCode' , ScripCode),
         ('Price'     , cast(Price as varchar(50)) )
  ) as CA (ColName, ColValue)

Personally I find this syntax easier than using unpivot.

NB: You must take care that all source columns are converted into compatible types for the single value column

PHP: convert spaces in string into %20?

Use the rawurlencode function instead.

How do I use JDK 7 on Mac OSX?

after installing the 1.7jdk from oracle, i changed my bash scripts to add:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home

and then running java -version showed the right version.

How to get the current time in milliseconds from C in Linux?

Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

How to get data by SqlDataReader.GetValue by column name

thisReader.GetString(int columnIndex)

Print <div id="printarea"></div> only?

I had multiple images each with a button and needed to click on a button to print each div with an image. This solution works if I have disabled cache in my browser, and the image size doesn't change in Chrome:

        function printDiv(divName) {

        var printContents = document.getElementById(divName).innerHTML;
        w = window.open();

        w.document.write(printContents);
        w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');

        w.document.close(); // necessary for IE >= 10
        w.focus(); // necessary for IE >= 10

        return true;
    }

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

How to remove Left property when position: absolute?

left: initial

This will also set left back to the browser default.

But important to know property: initial is not supported in IE.

Use jQuery to change value of a label

Validation (HTML5): Attribute 'name' is not a valid attribute of element 'label'.

How to extract URL parameters from a URL with Ruby or Rails?

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

Visual Studio 2012 Web Publish doesn't copy files

In Visual Studio 2012, switching between releases still causes problems.

We added a pre-build event to delete the obj folder: del /s /f /q $(ProjectDir)\obj and it fixed the issue of publishing. Cleaning works sometimes, but not always.

How can I draw vertical text with CSS cross-browser?

I am using the following code to write vertical text in a page. Firefox 3.5+, webkit, opera 10.5+ and IE

.rot-neg-90 {
    -moz-transform:rotate(-270deg); 
    -moz-transform-origin: bottom left;
    -webkit-transform: rotate(-270deg);
    -webkit-transform-origin: bottom left;
    -o-transform: rotate(-270deg);
    -o-transform-origin:  bottom left;
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
}

UL has margin on the left

The <ul> element has browser inherent padding & margin by default. In your case, Use

#footer ul {
    margin: 0; /* To remove default bottom margin */ 
    padding: 0; /* To remove default left padding */
}

or a CSS browser reset ( https://cssreset.com/ ) to deal with this.

How to return value from an asynchronous callback function?

It makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.

Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.

How to test code dependent on environment variables using JUnit?

The usual solution is to create a class which manages the access to this environmental variable, which you can then mock in your test class.

public class Environment {
    public String getVariable() {
        return System.getenv(); // or whatever
    }
}

public class ServiceTest {
    private static class MockEnvironment {
        public String getVariable() {
           return "foobar";
        }
    }

    @Test public void testService() {
        service.doSomething(new MockEnvironment());
    }
}

The class under test then gets the environment variable using the Environment class, not directly from System.getenv().

Which version of Python do I have installed?

You can get the version of Python by using the following command

python --version

You can even get the version of any package installed in venv using pip freeze as:

pip freeze | grep "package name"

Or using the Python interpreter as:

In [1]: import django
In [2]: django.VERSION
Out[2]: (1, 6, 1, 'final', 0)

How to print star pattern in JavaScript in a very simple manner?

It's very simple, Try this code as below:

for(var i = 1; i <= 5; i++) {

      for(var j = 1; j<= i; j++) {

        document.write("*");  

      }

      document.write("<br/>");
}

dyld: Library not loaded ... Reason: Image not found

if you use virtualenv just remove the folder of your environment and recreate it with this command virtualenv --python=/usr/local/bin/python3 the_name_of_my_env

How to use vim in the terminal?

Get started quickly

You simply type vim into the terminal to open it and start a new file.

You can pass a filename as an option and it will open that file, e.g. vim main.c. You can open multiple files by passing multiple file arguments.

Vim has different modes, unlike most editors you have probably used. You begin in NORMAL mode, which is where you will spend most of your time once you become familiar with vim.

To return to NORMAL mode after changing to a different mode, press Esc. It's a good idea to map your Caps Lock key to Esc, as it's closer and nobody really uses the Caps Lock key.

The first mode to try is INSERT mode, which is entered with a for append after cursor, or i for insert before cursor.

To enter VISUAL mode, where you can select text, use v. There are many other variants of this mode, which you will discover as you learn more about vim.

To save your file, ensure you're in NORMAL mode and then enter the command :w. When you press :, you will see your command appear in the bottom status bar. To save and exit, use :x. To quit without saving, use :q. If you had made a change you wanted to discard, use :q!.

Configure vim to your liking

You can edit your ~/.vimrc file to configure vim to your liking. It's best to look at a few first (here's mine) and then decide which options suits your style.

This is how mine looks:

vim screenshot

To get the file explorer on the left, use NERDTree. For the status bar, use vim-airline. Finally, the color scheme is solarized.

Further learning

You can use man vim for some help inside the terminal. Alternatively, run vimtutor which is a good hands-on starting point.

It's a good idea to print out a Vim Cheatsheet and keep it in front of you while you're learning vim.

Good luck!

How to use phpexcel to read data and insert into database?

Using the PHPExcel library, the following code will do.

require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';    
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true); //optional

$objPHPExcel = $objReader->load(__DIR__.'/YourExcelFile.xlsx');
$objWorksheet = $objPHPExcel->getActiveSheet();

$i=1;
foreach ($objWorksheet->getRowIterator() as $row) {

    $column_A_Value = $objPHPExcel->getActiveSheet()->getCell("A$i")->getValue();//column A
    //you can add your own columns B, C, D etc.

    //inset $column_A_Value value in DB query here

    $i++;
}

jQuery find() method not working in AngularJS directive

find() - Limited to lookups by tag name you can see more information https://docs.angularjs.org/api/ng/function/angular.element

Also you can access by name or id or call please following example:

angular.element(document.querySelector('#txtName')).attr('class', 'error');

how to use font awesome in own css?

you can do so by using the :before or :after pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/

change your code to this

.lb-prev:hover {
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
   text-decoration: none;
}

.lb-prev:before {
    font-family: FontAwesome;
    content: "\f053";
    font-size: 30px;
}

do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps

Set equal width of columns in table layout in Android

Try this.

It boils down to adding android:stretchColumns="*" to your TableLayout root and setting android:layout_width="0dp" to all the children in your TableRows.

<TableLayout
    android:stretchColumns="*"   // Optionally use numbered list "0,1,2,3,..."
>
    <TableRow
        android:layout_width="0dp"
    >

Creating an index on a table variable

The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.

SQL Server 2014

In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations.

Example syntax for that is below.

/*SQL Server 2014+ compatible inline index syntax*/
DECLARE @T TABLE (
C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
C2 INT INDEX IX2 NONCLUSTERED,
       INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
);

Filtered indexes and indexes with included columns can not currently be declared with this syntax however SQL Server 2016 relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it may be the case that included columns are also allowed but the current position is that they "will likely not make it into SQL16 due to resource constraints"

/*SQL Server 2016 allows filtered indexes*/
DECLARE @T TABLE
(
c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
)

SQL Server 2000 - 2012

Can I create a index on Name?

Short answer: Yes.

DECLARE @TEMPTABLE TABLE (
  [ID]   [INT] NOT NULL PRIMARY KEY,
  [Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
  UNIQUE NONCLUSTERED ([Name], [ID]) 
  ) 

A more detailed answer is below.

Traditional tables in SQL Server can either have a clustered index or are structured as heaps.

Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a uniqueifier to any duplicate keys to make them unique.

Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server adds the row locator (clustered index key or RID for a heap) to all index keys (not just duplicates) this again ensures they are unique.

In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a UNIQUE or PRIMARY KEY constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of NULLs is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.

Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the PRIMARY KEY will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying CLUSTERED or NONCLUSTERED explicitly with the constraint declaration (Example syntax)

DECLARE @T TABLE
(
A INT NULL UNIQUE CLUSTERED,
B INT NOT NULL PRIMARY KEY NONCLUSTERED
)

As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.

+-------------------------------------+-------------------------------------+
|             Index Type              | Can be created on a table variable? |
+-------------------------------------+-------------------------------------+
| Unique Clustered Index              | Yes                                 |
| Nonunique Clustered Index           |                                     |
| Unique NCI on a heap                | Yes                                 |
| Non Unique NCI on a heap            |                                     |
| Unique NCI on a clustered index     | Yes                                 |
| Non Unique NCI on a clustered index | Yes                                 |
+-------------------------------------+-------------------------------------+

The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the non unique non clustered index on Name is simulated by a unique index on Name,Id (recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).

A non unique clustered index can also be achieved by manually adding an IDENTITY column to act as a uniqueifier.

DECLARE @T TABLE
(
A INT NULL,
B INT NULL,
C INT NULL,
Uniqueifier INT NOT NULL IDENTITY(1,1),
UNIQUE CLUSTERED (A,Uniqueifier)
)

But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.

Android Studio - mergeDebugResources exception

There is a new Gradle task called "cleanBuildCache" just run this task clean the cache then re-build the project.

Start and stop a timer PHP

Also you can use HRTime package. It has a class StopWatch.