Programs & Examples On #Mips64

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

Do any of the following:

1- Update the play-services-maps library to the latest version:

com.google.android.gms:play-services-maps:16.1.0

2- Or include the following declaration within the <application> element of AndroidManifest.xml.

<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />

How to resolve "Waiting for Debugger" message?

In Debug mode Android Studio connects to your Device via socket(:8600). Somehow your socket connection is choked and thus not responding to incoming connections.

Restart Android Studio and your problem will be resolved

Converting a string to JSON object

JSON.parse() function will do.

or

Using Jquery,

var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );

How do I execute a bash script in Terminal?

$prompt: /path/to/script and hit enter. Note you need to make sure the script has execute permissions.

Remove a marker from a GoogleMap

Make a global variable to keep track of marker

private Marker currentLocationMarker;

//Remove old marker

            if (null != currentLocationMarker) {
                currentLocationMarker.remove();
            }

// Add updated marker in and move the camera

            currentLocationMarker = mMap.addMarker(new MarkerOptions().position(
                    new LatLng(getLatitude(), getLongitude()))
                    .title("You are now Here").visible(true)
                    .icon(Utils.getMarkerBitmapFromView(getActivity(), R.drawable.auto_front))
                    .snippet("Updated Location"));

            currentLocationMarker.showInfoWindow();

How to use sys.exit() in Python

you didn't import sys in your code, nor did you close the () when calling the function... try:

import sys
sys.exit()

How do you decompile a swf file

Usually 'lost' is a euphemism for "We stopped paying the developer and now he wont give us the source code."

That being said, I own a copy of Burak's ActionScript Viewer, and it works pretty well. A simple google search will find you many other SWF decompilers.

LaTeX package for syntax highlighting of code in various languages

LGrind does this. It's a mature LaTeX package that's been around since adam was a cowboy and has support for many programming languages.

MVC 4 - Return error message from Controller - Show in View

If you want to do a redirect, you can either:

ViewBag.Error = "error message";

or

TempData["Error"] = "error message";

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem

Is it possible to overwrite a function in PHP

You could use the PECL extension

but that is bad practise in my opinion. You are using functions, but check out the Decorator design pattern. Can borrow the basic idea from it.

how to create and call scalar function in sql server 2008

Or you can simply use PRINT command instead of SELECT command. Try this,

PRINT dbo.fn_HomePageSlider(9, 3025)

What is the total amount of public IPv4 addresses?

https://www.ripe.net/internet-coordination/press-centre/understanding-ip-addressing

For IPv4, this pool is 32-bits (2³²) in size and contains 4,294,967,296 IPv4 addresses.

In case of IPv6

The IPv6 address space is 128-bits (2¹²8) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.

inclusive of RESERVED IP

 Reserved address blocks
 Range  Description Reference

 0.0.0.0/8  Current network (only valid as source address)  RFC 6890
 10.0.0.0/8 Private network RFC 1918
 100.64.0.0/10  Shared Address Space    RFC 6598
 127.0.0.0/8    Loopback    RFC 6890
 169.254.0.0/16 Link-local  RFC 3927
 172.16.0.0/12  Private network RFC 1918
 192.0.0.0/24   IETF Protocol Assignments   RFC 6890
 192.0.2.0/24   TEST-NET-1, documentation and examples  RFC 5737
 192.88.99.0/24 IPv6 to IPv4 relay (includes 2002::/16) RFC 3068
 192.168.0.0/16 Private network RFC 1918
 198.18.0.0/15  Network benchmark tests RFC 2544
 198.51.100.0/24    TEST-NET-2, documentation and examples  RFC 5737
 203.0.113.0/24 TEST-NET-3, documentation and examples  RFC 5737
 224.0.0.0/4    IP multicast (former Class D network)   RFC 5771
 240.0.0.0/4    Reserved (former Class E network)   RFC 1700
 255.255.255.255    Broadcast   RFC 919

wiki has full details and this has details of IPv6.

PHP - Move a file into a different folder on the server

Use the rename() function.

rename("user/image1.jpg", "user/del/image1.jpg");

libxml/tree.h no such file or directory

Follow the directions here, under "Setting up your project file."

Setting up your project file

You need to add libxml2.dylib to your project (don't put it in the Frameworks section). On the Mac, you'll find it at /usr/lib/libxml2.dylib and for the iPhone, you'll want the /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.0.sdk/usr/lib/libxml2.dylib version.

Since libxml2 is a .dylib (not a nice friendly .framework) we still have one more thing to do. Go to the Project build settings (Project->Edit Project Settings->Build) and find the "Search Paths". In "Header Search Paths" add the following path:

$(SDKROOT)/usr/include/libxml2

Also see the OP's answer.

Custom method names in ASP.NET Web API

Just modify your WebAPIConfig.cs as bellow

Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}/{action}/{id}",
  defaults: new { action = "get", id = RouteParameter.Optional });

Then implement your API as bellow

    // GET: api/Controller_Name/Show/1
    [ActionName("Show")]
    [HttpGet]
    public EventPlanner Id(int id){}

MVC Calling a view from a different controller

I'm not really sure if I got your question right. Maybe something like

public class CommentsController : Controller
{
    [HttpPost]
    public ActionResult WriteComment(CommentModel comment)
    {
        // Do the basic model validation and other stuff
        try
        {
            if (ModelState.IsValid )
            {
                 // Insert the model to database like:
                 db.Comments.Add(comment);
                 db.SaveChanges();

                 // Pass the comment's article id to the read action
                 return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
            }
        }
        catch ( Exception e )
        {
             throw e;
        }
        // Something went wrong
        return View(comment);

    }
}


public class ArticlesController : Controller
{
    // id is the id of the article
    public ActionResult Read(int id)
    {
        // Get the article from database by id
        var model = db.Articles.Find(id);
        // Return the view
        return View(model);
    }
}

php refresh current page?

$_SERVER['REQUEST_URI'] should work.

Retrieve column values of the selected row of a multicolumn Access listbox

Just a little addition. If you've only selected 1 row then the code below will select the value of a column (index of 4, but 5th column) for the selected row:

me.lstIssues.Column(4)

This saves having to use the ItemsSelected property.

Kristian

Switch case: can I use a range instead of a one number

If-else should be used in that case, But if there is still a need of switch for any reason, you can do as below, first cases without break will propagate till first break is encountered. As previous answers have suggested I recommend if-else over switch.

switch (number){
            case 1:
            case 2:
            case 3:
            case 4: //do something;
                    break;
            case 5:
            case 6:
            case 7:
            case 8:
            case 9: //Do some other-thing;
                   break;
        }

How to set component default props on React component

You forgot to close the Class bracket.

_x000D_
_x000D_
class AddAddressComponent extends React.Component {_x000D_
  render() {_x000D_
    let {provinceList,cityList} = this.props_x000D_
    if(cityList === undefined || provinceList === undefined){_x000D_
      console.log('undefined props')_x000D_
    } else {_x000D_
      console.log('defined props')_x000D_
    }_x000D_
_x000D_
    return (_x000D_
      <div>rendered</div>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
AddAddressComponent.contextTypes = {_x000D_
  router: React.PropTypes.object.isRequired_x000D_
};_x000D_
_x000D_
AddAddressComponent.defaultProps = {_x000D_
  cityList: [],_x000D_
  provinceList: [],_x000D_
};_x000D_
_x000D_
AddAddressComponent.propTypes = {_x000D_
  userInfo: React.PropTypes.object,_x000D_
  cityList: React.PropTypes.array.isRequired,_x000D_
  provinceList: React.PropTypes.array.isRequired,_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <AddAddressComponent />,_x000D_
  document.getElementById('app')_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app" />
_x000D_
_x000D_
_x000D_

Split string into array

var foo = 'somestring'; 

// bad example https://stackoverflow.com/questions/6484670/how-do-i-split-a-string-into-an-array-of-characters/38901550#38901550

var arr = foo.split(''); 
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]

// good example
var arr = Array.from(foo);
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]

// best
var arr = [...foo]
console.log(arr); // ["s", "o", "m", "e", "s", "t", "r", "i", "n", "g"]

Bootstrap - Removing padding or margin when screen size is smaller

Another css that can make the margin problem is that you have direction:someValue in your css, so just remove it by setting it to initial.

For example:

body {
     direction:rtl;
 }
@media (max-width: 480px) {
    body {
     direction:initial;
    }
}

Remove an item from array using UnderscoreJS

You can use Underscore .filter

    var arr = [{
      id: 1,
      name: 'a'
    }, {
      id: 2,
      name: 'b'
    }, {
      id: 3,
      name: 'c'
    }];

    var filtered = _(arr).filter(function(item) {
         return item.id !== 3
    });

Can also be written as:

var filtered = arr.filter(function(item) {
    return item.id !== 3
});

var filtered = _.filter(arr, function(item) {
    return item.id !== 3
});

Check Fiddle

You can also use .reject

What is git fast-forwarding?

In Git, to "fast forward" means to update the HEAD pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...

Fast forwarding is not possible when the new HEAD is in a diverged state relative to the stream you want to integrate. For instance, you are on master and have local commits, and git fetch has brought new upstream commits into origin/master. The branch now diverges from its upstream and cannot be fast forwarded: your master HEAD commit is not an ancestor of origin/master HEAD. To simply reset master to the value of origin/master would discard your local commits. The situation requires a rebase or merge.

If your local master has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master. Usually, no special steps are needed to do fast-forwarding; it is done by merge or rebase in the situation when there are no local commits.

Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?

No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)

Change font color and background in html on mouseover

Either do it with CSS like the other answers did or change the text style color directly via the onMouseOver and onMouseOut event:

onmouseover="this.bgColor='white'; this.style.color='black'"

onmouseout="this.bgColor='black'; this.style.color='white'"

Switch statement for greater-than/less-than

An alternative:

var scrollleft = 1000;
switch (true)
{
    case (scrollleft > 1000):
      alert('gt');
      break;
    case (scrollleft <= 1000):
      alert('lt');
      break; 
}

Demo: http://jsfiddle.net/UWYzr/

How to download and save a file from Internet using Java?

It's possible to download the file with with Apache's HttpComponents instead of Commons-IO. This code allows you to download a file in Java according to its URL and save it at the specific destination.

public static boolean saveFile(URL fileURL, String fileSavePath) {

    boolean isSucceed = true;

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet(fileURL.toString());
    httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    httpGet.addHeader("Referer", "https://www.google.com");

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity fileEntity = httpResponse.getEntity();

        if (fileEntity != null) {
            FileUtils.copyInputStreamToFile(fileEntity.getContent(), new File(fileSavePath));
        }

    } catch (IOException e) {
        isSucceed = false;
    }

    httpGet.releaseConnection();

    return isSucceed;
}

In contrast to the single line of code:

FileUtils.copyURLToFile(fileURL, new File(fileSavePath),
                        URLS_FETCH_TIMEOUT, URLS_FETCH_TIMEOUT);

this code will give you more control over a process and let you specify not only time outs but User-Agent and Referer values, which are critical for many web-sites.

JavaScript: replace last occurrence of text in a string

Simple solution would be to use substring method. Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf method

str = str.substring(0, str.length - list[i].length) + "finish"

jQuery object equality

Since jQuery 1.6, you can use .is. Below is the answer from over a year ago...

var a = $('#foo');
var b = a;


if (a.is(b)) {
    // the same object!
}

If you want to see if two variables are actually the same object, eg:

var a = $('#foo');
var b = a;

...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.

if ($.data(a) == $.data(b)) {
    // the same object!
}

Though, the same could be achieved with a simple a === b, the above might at least show the next developer exactly what you're testing for.

In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:

$.fn.equals = function(compareTo) {
  if (!compareTo || this.length != compareTo.length) {
    return false;
  }
  for (var i = 0; i < this.length; ++i) {
    if (this[i] !== compareTo[i]) {
      return false;
    }
  }
  return true;
};

Source

var a = $('p');
var b = $('p');
if (a.equals(b)) {
    // same set
}

Pandas DataFrame column to list

The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values the output is an numpy array. So if the data has int and float in it then output will either have int or float and the columns will loose their original dtype. Consider df

a  b 
0  1  4
1  2  5 
2  3  6 

a    float64
b    int64 

So if you want to keep original dtype, you can do something like

row_list = df.to_csv(None, header=False, index=False).split('\n')

this will return each row as a string.

['1.0,4', '2.0,5', '3.0,6', '']

Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.

def f(row_str): 
  row_list = row_str.split(',')
  return [float(row_list[0]), int(row_list[1])]

df_list_of_list = map(f, row_list[:-1])

[[1.0, 4], [2.0, 5], [3.0, 6]]

PHP: HTML: send HTML select option attribute in POST

You can use jquery function.

<form name='add'>
   <input type='text' name='stud_name' id="stud_name" value=""/>
   Age: <select name='age' id="age">
   <option value='1' stud_name='sre'>23</option>
   <option value='2' stud_name='sam'>24</option>
   <option value='5' stud_name='john'>25</option>
   </select>
   <input type='submit' name='submit'/>
</form>

jquery code :

<script type="text/javascript" src="jquery.js"></script>

<script>
    $(function() {
          $("#age").change(function(){
          var option = $('option:selected', this).attr('stud_name');
          $('#stud_name').val(option);
       });
    });
</script>

How enable auto-format code for Intellij IDEA?

This can also be achieved by Ctrl+WindowsBtn+Alt+L. This will be important to some people,because in some Virtual Machines, Ctrl+Alt+L can log you out.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

    def wordCount(mystring):  
        tempcount = 0  
        count = 1  

        try:  
            for character in mystring:  
                if character == " ":  
                    tempcount +=1  
                    if tempcount ==1:  
                        count +=1  

                    else:  
                        tempcount +=1
                 else:
                     tempcount=0

             return count  

         except Exception:  
             error = "Not a string"  
             return error  

    mystring = "I   am having   a    very nice 23!@$      day."           

    print(wordCount(mystring))  

output is 8

Using prepared statements with JDBCTemplate

class Main {
    public static void main(String args[]) throws Exception {
        ApplicationContext ac = new
          ClassPathXmlApplicationContext("context.xml", Main.class);
        DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        String prasobhName = 
        jdbcTemplate.query(
           "select first_name from customer where last_name like ?",
            new PreparedStatementSetter() {
              public void setValues(PreparedStatement preparedStatement) throws
                SQLException {
                  preparedStatement.setString(1, "nair%");
              }
            }, 
            new ResultSetExtractor<Long>() {
              public Long extractData(ResultSet resultSet) throws SQLException,
                DataAccessException {
                  if (resultSet.next()) {
                      return resultSet.getLong(1);
                  }
                  return null;
              }
            }
        );
        System.out.println(machaceksName);
    }
}

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

MySQL dump by query

Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.

mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep  '^INSERT' > 5406.sql

Which concurrent Queue implementation should I use in Java?

Basically the difference between them are performance characteristics and blocking behavior.

Taking the easiest first, ArrayBlockingQueue is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.

The most important difference between LinkedBlockingQueue and ConcurrentLinkedQueue is that if you request an element from a LinkedBlockingQueue and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue will return right away with the behavior of an empty queue.

Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.

Where is svn.exe in my machine?

Yes reinstall and select command line to get the svn in Program Files-> Tortoise SVN folder.

What is the correct way to check for string equality in JavaScript?

Just one addition to answers: If all these methods return false, even if strings seem to be equal, it is possible that there is a whitespace to the left and or right of one string. So, just put a .trim() at the end of strings before comparing:

if(s1.trim() === s2.trim())
{
    // your code
}

I have lost hours trying to figure out what is wrong. Hope this will help to someone!

How to initialize a struct in accordance with C programming language standards

void function(void) {
  MY_TYPE a;
  a.flag = true;
  a.value = 15;
  a.stuff = 0.123;
}

jQuery animate backgroundColor

Simply add the following snippet bellow your jquery script and enjoy:

<script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>

See the example

Reference for more info

Drop default constraint on a column in TSQL

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from 
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where 
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

How to JUnit test that two List<E> contain the same elements in the same order?

Why not simply use List#equals?

assertEquals(argumentComponents, imapPathComponents);

Contract of List#equals:

two lists are defined to be equal if they contain the same elements in the same order.

Gem Command not found

On CentOS 7 you can do:

yum -y install rubygems-devel

That worked for me.

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

Why use the 'ref' keyword when passing an object?

By using the ref keyword with reference types you are effectively passing a reference to the reference. In many ways it's the same as using the out keyword but with the minor difference that there's no guarantee that the method will actually assign anything to the ref'ed parameter.

How to use boolean datatype in C?

If you have a compiler that supports C99 you can

#include <stdbool.h>

Otherwise, you can define your own if you'd like. Depending on how you want to use it (and whether you want to be able to compile your code as C++), your implementation could be as simple as:

#define bool int
#define true 1
#define false 0

In my opinion, though, you may as well just use int and use zero to mean false and nonzero to mean true. That's how it's usually done in C.

How does the bitwise complement operator (~ tilde) work?

int a=4; System.out.println(~a); Result would be :-5

'~' of any integer in java represents 1's complement of the no. for example i am taking ~4,which means in binary representation 0100. first , length of an integer is four bytes,i.e 4*8(8 bits for 1 byte)=32. So in system memory 4 is represented as 0000 0000 0000 0000 0000 0000 0000 0100 now ~ operator will perform 1's complement on the above binary no

i.e 1111 1111 1111 1111 1111 1111 1111 1011->1's complement the most significant bit represents sign of the no(either - or +) if it is 1 then sign is '-' if it is 0 then sign is '+' as per this our result is a negative number, in java the negative numbers are stored in 2's complement form, the acquired result we have to convert into 2's complement( first perform 1's complement and just add 1 to 1's complement). all the one will become zeros,except most significant bit 1(which is our sign representation of the number,that means for remaining 31 bits 1111 1111 1111 1111 1111 1111 1111 1011 (acquired result of ~ operator) 1000 0000 0000 0000 0000 0000 0000 0100 (1's complement)

1 (2's complement)

1000 0000 0000 0000 0000 0000 0000 0101 now the result is -5 check out this link for the video <[Bit wise operators in java] https://youtu.be/w4pJ4cGWe9Y

"Debug only" code that should run only when "turned on"

You could try this if you only need the code to run when you have a debugger attached to the process.

if (Debugger.IsAttached)
{
     // do some stuff here
}

Search for executable files using find command

Well the easy answer would be: "your executable files are in the directories contained in your PATH variable" but that would not really find your executables and could miss a lot of executables anyway.

I don't know much about mac but I think "mdfind 'kMDItemContentType=public.unix-executable'" might miss stuff like interpreted scripts

If it's ok for you to find files with the executable bits set (regardless of whether they are actually executable) then it's fine to do

find . -type f -perm +111 -print

where supported the "-executable" option will make a further filter looking at acl and other permission artifacts but is technically not much different to "-pemr +111".

Maybe in the future find will support "-magic " and let you look explicitly for files with a specific magic id ... but then you would haveto specify to fine all the executable formats magic id.

I'm unaware of a technically correct easy way out on unix.

How to find whether a ResultSet is empty or not in Java?

if (rs == null || !rs.first()) {
    //empty
} else {
    //not empty
}

Note that after this method call, if the resultset is not empty, it is at the beginning.

UIView Hide/Show with animation

I created category for UIView for this purpose and implemented a special little bit different concept: visibility. The main difference of my solution is that you can call [view setVisible:NO animated:YES] and right after that synchronously check [view visible] and get correct result. This is pretty simple but extremely useful.

Besides, it is allowed to avoid using "negative boolean logic" (see Code Complete, page 269, Use positive boolean variable names for more information).

Swift

UIView+Visibility.swift

import UIKit


private let UIViewVisibilityShowAnimationKey = "UIViewVisibilityShowAnimationKey"
private let UIViewVisibilityHideAnimationKey = "UIViewVisibilityHideAnimationKey"


private class UIViewAnimationDelegate: NSObject {
    weak var view: UIView?

    dynamic override func animationDidStop(animation: CAAnimation, finished: Bool) {
        guard let view = self.view where finished else {
            return
        }

        view.hidden = !view.visible
        view.removeVisibilityAnimations()
    }
}


extension UIView {

    private func removeVisibilityAnimations() {
        self.layer.removeAnimationForKey(UIViewVisibilityShowAnimationKey)
        self.layer.removeAnimationForKey(UIViewVisibilityHideAnimationKey)
    }

    var visible: Bool {
        get {
            return !self.hidden && self.layer.animationForKey(UIViewVisibilityHideAnimationKey) == nil
        }

        set {
            let visible = newValue

            guard self.visible != visible else {
                return
            }

            let animated = UIView.areAnimationsEnabled()

            self.removeVisibilityAnimations()

            guard animated else {
                self.hidden = !visible
                return
            }

            self.hidden = false

            let delegate = UIViewAnimationDelegate()
            delegate.view = self

            let animation = CABasicAnimation(keyPath: "opacity")
            animation.fromValue = visible ? 0.0 : 1.0
            animation.toValue = visible ? 1.0 : 0.0
            animation.fillMode = kCAFillModeForwards
            animation.removedOnCompletion = false
            animation.delegate = delegate

            self.layer.addAnimation(animation, forKey: visible ? UIViewVisibilityShowAnimationKey : UIViewVisibilityHideAnimationKey)
        }
    }

    func setVisible(visible: Bool, animated: Bool) {
        let wereAnimationsEnabled = UIView.areAnimationsEnabled()

        if wereAnimationsEnabled != animated {
            UIView.setAnimationsEnabled(animated)
            defer { UIView.setAnimationsEnabled(!animated) }
        }

        self.visible = visible
    }

}

Objective-C

UIView+Visibility.h

#import <UIKit/UIKit.h>

@interface UIView (Visibility)

- (BOOL)visible;
- (void)setVisible:(BOOL)visible;
- (void)setVisible:(BOOL)visible animated:(BOOL)animated;

@end

UIView+Visibility.m

#import "UIView+Visibility.h"

NSString *const UIViewVisibilityAnimationKeyShow = @"UIViewVisibilityAnimationKeyShow";
NSString *const UIViewVisibilityAnimationKeyHide = @"UIViewVisibilityAnimationKeyHide";

@implementation UIView (Visibility)

- (BOOL)visible
{
    if (self.hidden || [self.layer animationForKey:UIViewVisibilityAnimationKeyHide]) {
        return NO;
    }

    return YES;
}

- (void)setVisible:(BOOL)visible
{
    [self setVisible:visible animated:NO];
}

- (void)setVisible:(BOOL)visible animated:(BOOL)animated
{
    if (self.visible == visible) {
        return;
    }

    [self.layer removeAnimationForKey:UIViewVisibilityAnimationKeyShow];
    [self.layer removeAnimationForKey:UIViewVisibilityAnimationKeyHide];

    if (!animated) {
        self.alpha = 1.f;
        self.hidden = !visible;
        return;
    }

    self.hidden = NO;

    CGFloat fromAlpha = visible ? 0.f : 1.f;
    CGFloat toAlpha = visible ? 1.f : 0.f;
    NSString *animationKey = visible ? UIViewVisibilityAnimationKeyShow : UIViewVisibilityAnimationKeyHide;

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    animation.duration = 0.25;
    animation.fromValue = @(fromAlpha);
    animation.toValue = @(toAlpha);
    animation.delegate = self;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:animation forKey:animationKey];
}

#pragma mark - CAAnimationDelegate

- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)finished
{
    if ([[self.layer animationForKey:UIViewVisibilityAnimationKeyHide] isEqual:animation]) {
        self.hidden = YES;
    }
}

@end

How to use MySQLdb with Python and Django in OSX 10.6?

mysql_config must be on the path. On Mac, do

export PATH=$PATH:/usr/local/mysql/bin/
pip install MySQL-python

Powershell 2 copy-item which creates a folder if doesn't exist

Here's an example that worked for me. I had a list of about 500 specific files in a text file, contained in about 100 different folders, that I was supposed to copy over to a backup location in case those files were needed later. The text file contained full path and file name, one per line. In my case, I wanted to strip off the Drive letter and first sub-folder name from each file name. I wanted to copy all these files to a similar folder structure under another root destination folder I specified. I hope other users find this helpful.

# Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
$rootDestFolder = "F:\DestinationFolderName"
$sourceFiles = Get-Content C:\temp\filelist.txt
foreach($sourceFile in $sourceFiles){
    $filesplit = $sourceFile.split("\")
    $splitcount = $filesplit.count
    # This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
    $destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
    # Output List of source and dest 
    Write-Host ""
    Write-Host "===$sourceFile===" -ForegroundColor Green
    Write-Host "+++$destFile+++"
    # Create path and file, if they do not already exist
    $destPath = Split-Path $destFile
    If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
    If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
}

How to extract a value from a string using regex and a shell?

Using ripgrep's replace option, it is possible to change the output to a capture group:

rg --only-matching --replace '$1' '(\d+) rofl'
  • --only-matching or -o outputs only the part that matches instead of the whole line.
  • --replace '$1' or -r replaces the output by the first capture group.

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

What about casting to Number in Javascript using the Unary (+) Operator

lat: 12.23
lat: +12.23

Depends on the use case. Here is a fullchart what works and what not: parseInt vs unary plus - when to use which

Wildcard string comparison in Javascript

Instead Animals == "bird*" Animals = "bird*" should work.

gnuplot : plotting data from multiple input files in a single graph

You're so close!

Change

plot "print_1012720" using 1:2 title "Flow 1", \
plot "print_1058167" using 1:2 title "Flow 2", \
plot "print_193548"  using 1:2 title "Flow 3", \ 
plot "print_401125"  using 1:2 title "Flow 4", \
plot "print_401275"  using 1:2 title "Flow 5", \
plot "print_401276"  using 1:2 title "Flow 6"

to

plot "print_1012720" using 1:2 title "Flow 1", \
     "print_1058167" using 1:2 title "Flow 2", \
     "print_193548"  using 1:2 title "Flow 3", \ 
     "print_401125"  using 1:2 title "Flow 4", \
     "print_401275"  using 1:2 title "Flow 5", \
     "print_401276"  using 1:2 title "Flow 6"

The error arises because gnuplot is trying to interpret the word "plot" as the filename to plot, but you haven't assigned any strings to a variable named "plot" (which is good – that would be super confusing).

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How do I get the row count of a Pandas DataFrame?

How do I get the row count of a Pandas DataFrame?

This table summarises the different situations in which you'd want to count something in a DataFrame (or Series, for completeness), along with the recommended method(s).

Enter image description here

Footnotes

  1. DataFrame.count returns counts for each column as a Series since the non-null count varies by column.
  2. DataFrameGroupBy.size returns a Series, since all columns in the same group share the same row-count.
  3. DataFrameGroupBy.count returns a DataFrame, since the non-null count could differ across columns in the same group. To get the group-wise non-null count for a specific column, use df.groupby(...)['x'].count() where "x" is the column to count.

#Minimal Code Examples

Below, I show examples of each of the methods described in the table above. First, the setup -

df = pd.DataFrame({
    'A': list('aabbc'), 'B': ['x', 'x', np.nan, 'x', np.nan]})
s = df['B'].copy()

df

   A    B
0  a    x
1  a    x
2  b  NaN
3  b    x
4  c  NaN

s

0      x
1      x
2    NaN
3      x
4    NaN
Name: B, dtype: object

Row Count of a DataFrame: len(df), df.shape[0], or len(df.index)

len(df)
# 5

df.shape[0]
# 5

len(df.index)
# 5

It seems silly to compare the performance of constant time operations, especially when the difference is on the level of "seriously, don't worry about it". But this seems to be a trend with other answers, so I'm doing the same for completeness.

Of the three methods above, len(df.index) (as mentioned in other answers) is the fastest.

Note

  • All the methods above are constant time operations as they are simple attribute lookups.
  • df.shape (similar to ndarray.shape) is an attribute that returns a tuple of (# Rows, # Cols). For example, df.shape returns (8, 2) for the example here.

Column Count of a DataFrame: df.shape[1], len(df.columns)

df.shape[1]
# 2

len(df.columns)
# 2

Analogous to len(df.index), len(df.columns) is the faster of the two methods (but takes more characters to type).

Row Count of a Series: len(s), s.size, len(s.index)

len(s)
# 5

s.size
# 5

len(s.index)
# 5

s.size and len(s.index) are about the same in terms of speed. But I recommend len(df).

Note size is an attribute, and it returns the number of elements (=count of rows for any Series). DataFrames also define a size attribute which returns the same result as df.shape[0] * df.shape[1].

Non-Null Row Count: DataFrame.count and Series.count

The methods described here only count non-null values (meaning NaNs are ignored).

Calling DataFrame.count will return non-NaN counts for each column:

df.count()

A    5
B    3
dtype: int64

For Series, use Series.count to similar effect:

s.count()
# 3

Group-wise Row Count: GroupBy.size

For DataFrames, use DataFrameGroupBy.size to count the number of rows per group.

df.groupby('A').size()

A
a    2
b    2
c    1
dtype: int64

Similarly, for Series, you'll use SeriesGroupBy.size.

s.groupby(df.A).size()

A
a    2
b    2
c    1
Name: B, dtype: int64

In both cases, a Series is returned. This makes sense for DataFrames as well since all groups share the same row-count.

Group-wise Non-Null Row Count: GroupBy.count

Similar to above, but use GroupBy.count, not GroupBy.size. Note that size always returns a Series, while count returns a Series if called on a specific column, or else a DataFrame.

The following methods return the same thing:

df.groupby('A')['B'].size()
df.groupby('A').size()

A
a    2
b    2
c    1
Name: B, dtype: int64

Meanwhile, for count, we have

df.groupby('A').count()

   B
A
a  2
b  1
c  0

...called on the entire GroupBy object, vs.,

df.groupby('A')['B'].count()

A
a    2
b    1
c    0
Name: B, dtype: int64

Called on a specific column.

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

My mistake was simply using the CSR file instead of the CERT file.

How to get hex color value rather than RGB value?

Here is the cleaner solution I wrote based on @Matt suggestion:

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

Some browsers already returns colors as hexadecimal (as of Internet Explorer 8 and below). If you need to deal with those cases, just append a condition inside the function, like @gfrobenius suggested:

function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

If you're using jQuery and want a more complete approach, you can use CSS Hooks available since jQuery 1.4.3, as I showed when answering this question: Can I force jQuery.css("backgroundColor") returns on hexadecimal format?

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

This happens when JDK and JRE have different versions installed on your system. Update the JDK with the matching version of JRE. Also verify that System variable path has bin value from same JDK version.

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

Ran into this issue where the linked server would work for users who were local admins on the server, but not for anyone else. After many hours of messing around, I managed to fix the problem using the following steps:

  1. Run (CTRL + R) “dcomcnfg”. Navigate to “Component Services -> Computers -> My Computer -> DCOM Config”.
  2. Open the properties page of “MSDAINITIALIZE”.
  3. Copy the “Application ID” on the properties page.
  4. Close out of “dcomcnfg”.
  5. Run “regedit”. Navigate to “HKEY_CLASSES_ROOT\AppID{???}” with the ??? representing the application ID you copied in step #3.
  6. Right click the “{???}” folder and select “Permissions”
  7. Add the local administrators group to the permissions, grant them full control.
  8. Close out of “regedit”.
  9. Reboot the server.
  10. Run “dcomconfig”. Navigate to “Component Services -> Computers -> My Computer -> DCOM Config”.
  11. Open the properties page of “MSDAINITIALIZE”.
  12. On the “Security” tab, select “Customize” under “Launch and Activation Permissions”, then click the “Edit” button.
  13. Add “Authenticated Users” and grant them all 4 launch and activation permissions.
  14. Close out of “dcomcnfg”.
  15. Find the Oracle install root directory. “E:\Oracle” in my case.
  16. Edit the security properties of the Oracle root directory. Add “Authenticated Users” and grant them “Read & Execute”, “List folder contents” and “Read” permissions. Apply the new permissions.
  17. Click the “Advanced Permissions” button, then click “Change Permissions”. Select “Replace all child object permissions with inheritable permissions from this object”. Apply the new permissions.
  18. Find the “OraOLEDB.Oracle” provider in SQL Server. Make sure the “Allow Inprocess” parameter is checked.
  19. Reboot the server.

There is already an open DataReader associated with this Command which must be closed first

In addition to Ladislav Mrnka's answer:

If you are publishing and overriding container on Settings tab, you can set MultipleActiveResultSet to True. You can find this option by clicking Advanced... and it's going to be under Advanced group.

ExpressionChangedAfterItHasBeenCheckedError Explained

I'm using ng2-carouselamos (Angular 8 and Bootstrap 4)

Taking these steps fixed my problem:

  1. Implement AfterViewChecked
  2. Add constructor(private changeDetector : ChangeDetectorRef ) {}
  3. Then ngAfterViewChecked(){ this.changeDetector.detectChanges(); }

What underlies this JavaScript idiom: var self = this?

Actually self is a reference to window (window.self) therefore when you say var self = 'something' you override a window reference to itself - because self exist in window object.

This is why most developers prefer var that = this over var self = this;

Anyway; var that = this; is not in line with the good practice ... presuming that your code will be revised / modified later by other developers you should use the most common programming standards in respect with developer community

Therefore you should use something like var oldThis / var oThis / etc - to be clear in your scope // ..is not that much but will save few seconds and few brain cycles

Catch a thread's exception in the caller thread in Python

pygolang provides sync.WorkGroup which, in particular, propagates exception from spawned worker threads to the main thread. For example:

#!/usr/bin/env python
"""This program demostrates how with sync.WorkGroup an exception raised in
spawned thread is propagated into main thread which spawned the worker."""

from __future__ import print_function
from golang import sync, context

def T1(ctx, *argv):
    print('T1: run ... %r' % (argv,))
    raise RuntimeError('T1: problem')

def T2(ctx):
    print('T2: ran ok')

def main():
    wg = sync.WorkGroup(context.background())
    wg.go(T1, [1,2,3])
    wg.go(T2)

    try:
        wg.wait()
    except Exception as e:
        print('Tmain: caught exception: %r\n' %e)
        # reraising to see full traceback
        raise

if __name__ == '__main__':
    main()

gives the following when run:

T1: run ... ([1, 2, 3],)
T2: ran ok
Tmain: caught exception: RuntimeError('T1: problem',)

Traceback (most recent call last):
  File "./x.py", line 28, in <module>
    main()
  File "./x.py", line 21, in main
    wg.wait()
  File "golang/_sync.pyx", line 198, in golang._sync.PyWorkGroup.wait
    pyerr_reraise(pyerr)
  File "golang/_sync.pyx", line 178, in golang._sync.PyWorkGroup.go.pyrunf
    f(pywg._pyctx, *argv, **kw)
  File "./x.py", line 10, in T1
    raise RuntimeError('T1: problem')
RuntimeError: T1: problem

The original code from the question would be just:

    wg = sync.WorkGroup(context.background())

    def _(ctx):
        shul.copytree(sourceFolder, destFolder)
    wg.go(_)

    # waits for spawned worker to complete and, on error, reraises
    # its exception on the main thread.
    wg.wait()

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

this is your html code where you are calling function to convert 24 hour time format to 12 hour with am/pm

_x000D_
_x000D_
<pre id="tests" onClick="tConvert('18:00:00')">_x000D_
  test on click 18:00:00_x000D_
</pre>_x000D_
<span id="rzlt"></span>
_x000D_
_x000D_
_x000D_

now in js code write this tConvert function as it is

_x000D_
_x000D_
 function tConvert (time)_x000D_
  {_x000D_
     _x000D_
   // Check correct time format and split into components_x000D_
   time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];_x000D_
_x000D_
    if (time.length > 1) _x000D_
    { // If time format correct_x000D_
        _x000D_
      time = time.slice (1);  // Remove full string match value_x000D_
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM_x000D_
      time[0] = +time[0] % 12 || 12; // Adjust hours_x000D_
    }_x000D_
    //return time; // return adjusted time or original string_x000D_
      var tel = document.getElementById ('rzlt');_x000D_
      _x000D_
      tel.innerHTML= time.join ('');_x000D_
  }
_x000D_
_x000D_
_x000D_

converting 18:00:00 to 6:00:00PM working for me

Bootstrap Collapse not Collapsing

You need jQuery see bootstrap's basic template

Add a "sort" to a =QUERY statement in Google Spreadsheets

You can use ORDER BY clause to sort data rows by values in columns. Something like

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")

If you’d like to order by some columns descending, others ascending, you can add desc/asc, ie:

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")

Android Room - simple select query - Cannot access database on the main thread

Kotlin Coroutines (Clear & Concise)

AsyncTask is really clunky. Coroutines are a cleaner alternative (just sprinkle a couple of keywords and your sync code becomes async).

// Step 1: add `suspend` to your fun
suspend fun roomFun(...): Int
suspend fun notRoomFun(...) = withContext(Dispatchers.IO) { ... }

// Step 2: launch from coroutine scope
private fun myFun() {
    lifecycleScope.launch { // coroutine on Main
        val queryResult = roomFun(...) // coroutine on IO
        doStuff() // ...back on Main
    }
}

Dependencies (adds coroutine scopes for arch components):

// lifecycleScope:
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha04'

// viewModelScope:
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha04'

-- Updates:
08-May-2019: Room 2.1 now supports suspend
13-Sep-2019: Updated to use Architecture components scope

How do I get the latest version of my code?

If the above commands didn't help you use this method:

  1. Go to the git archive where you have Fork
  2. Click Settings> Scroll down and click Delete this repository
  3. Confirm delete
  4. Fork again, and re-enter the git clone <url_git>
  5. You already have the latest version

How to code a very simple login system with java

import java.<span class="q39pbqr9" id="q39pbqr9_9">net</span>.*;
import java.io.*;

<span class="q39pbqr9" id="q39pbqr9_1">public class</span> A
{
    static String user = "user";
    static String pass = "pass";
    static String param_user = "username";
    static String param_pass = "password";
    static String content = "";
    static String action = "action_url";
    static String urlName = "url_name";
    public static void main(String[] args)
    {
        try
        {
            user = URLEncoder.encode(user, "UTF-8");
            pass = URLEncoder.encode(pass, "UTF-8");
            content = "action=" + action +"&amp;" + param_user +"=" + user + "&amp;" + param_pass + "=" + pass;
            URL url = new URL(urlName);
            HttpURLConnection urlConnection = (HttpURLConnection)(url.openConnection());
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestMethod("POST");
            DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
            dataOutputStream.writeBytes(content);
            dataOutputStream.flush();
            dataOutputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String responeLine;
            StringBuilder response = new StringBuilder();
            while ((responeLine = bufferedReader.readLine()) != null)
            {
                response.append(responeLine);
            }
            System.out.println(response);
        }catch(Exception ex){ex.printStackTrace();}
    }

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

You need an extra reference for this; the most convenient way to do this is via the NuGet package System.IO.Compression.ZipFile

<!-- Version here correct at time of writing, but please check for latest -->
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />

If you are working on .NET Framework without NuGet, you need to add a dll reference to the assembly, "System.IO.Compression.FileSystem.dll" - and ensure you are using at least .NET 4.5 (since it doesn't exist in earlier frameworks).

For info, you can find the assembly and .NET version(s) from MSDN

How to refresh a page with jQuery by passing a parameter to URL

Click these links to see these more flexible and robust solutions. They're answers to a similar question:

These allow you to programmatically set the parameter, and, unlike the other hacks suggested for this question, won't break for URLs that already have a parameter, or if something else isn't quite what you thought might happen.

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

Feb 2020
android 3.4+
Go to File -> Settings -> Kotlin Compiler -> Target JVM Version > set to 1.8 and then make sure to do File -> Sync project with Gradle files

Or add this into build.gradle(module:app) in android block:

kotlinOptions {
           jvmTarget = "1.8"
         }

Wait until all jQuery Ajax requests are done?

I'm using size check when all ajax load completed

_x000D_
_x000D_
function get_ajax(link, data, callback) {_x000D_
    $.ajax({_x000D_
        url: link,_x000D_
        type: "GET",_x000D_
        data: data,_x000D_
        dataType: "json",_x000D_
        success: function (data, status, jqXHR) {_x000D_
            callback(jqXHR.status, data)_x000D_
        },_x000D_
        error: function (jqXHR, status, err) {_x000D_
            callback(jqXHR.status, jqXHR);_x000D_
        },_x000D_
        complete: function (jqXHR, status) {_x000D_
        }_x000D_
    })_x000D_
}_x000D_
_x000D_
function run_list_ajax(callback){_x000D_
    var size=0;_x000D_
    var max= 10;_x000D_
    for (let index = 0; index < max; index++) {_x000D_
        var link = 'http://api.jquery.com/ajaxStop/';_x000D_
        var data={i:index}_x000D_
        get_ajax(link,data,function(status, data){_x000D_
            console.log(index)_x000D_
            if(size>max-2){_x000D_
                callback('done')_x000D_
            }_x000D_
            size++_x000D_
            _x000D_
        })_x000D_
    }_x000D_
}_x000D_
_x000D_
run_list_ajax(function(info){_x000D_
    console.log(info)_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Can two applications listen to the same port?

The answer differs depending on what OS is being considered. In general though:

For TCP, no. You can only have one application listening on the same port at one time. Now if you had 2 network cards, you could have one application listen on the first IP and the second one on the second IP using the same port number.

For UDP (Multicasts), multiple applications can subscribe to the same port.

Edit: Since Linux Kernel 3.9 and later, support for multiple applications listening to the same port was added using the SO_REUSEPORT option. More information is available at this lwn.net article.

What is an application binary interface (ABI)?

If you know assembly and how things work at the OS-level, you are conforming to a certain ABI. The ABI govern things like how parameters are passed, where return values are placed. For many platforms there is only one ABI to choose from, and in those cases the ABI is just "how things work".

However, the ABI also govern things like how classes/objects are laid out in C++. This is necessary if you want to be able to pass object references across module boundaries or if you want to mix code compiled with different compilers.

Also, if you have an 64-bit OS which can execute 32-bit binaries, you will have different ABIs for 32- and 64-bit code.

In general, any code you link into the same executable must conform to the same ABI. If you want to communicate between code using different ABIs, you must use some form of RPC or serialization protocols.

I think you are trying too hard to squeeze in different types of interfaces into a fixed set of characteristics. For example, an interface doesn't necessarily have to be split into consumers and producers. An interface is just a convention by which two entities interact.

ABIs can be (partially) ISA-agnostic. Some aspects (such as calling conventions) depend on the ISA, while other aspects (such as C++ class layout) do not.

A well defined ABI is very important for people writing compilers. Without a well defined ABI, it would be impossible to generate interoperable code.

EDIT: Some notes to clarify:

  • "Binary" in ABI does not exclude the use of strings or text. If you want to link a DLL exporting a C++ class, somewhere in it the methods and type signatures must be encoded. That's where C++ name-mangling comes in.
  • The reason why you never provided an ABI is that the vast majority of programmers will never do it. ABIs are provided by the same people designing the platform (i.e. operating system), and very few programmers will ever have the privilege to design a widely-used ABI.

Fatal error: Call to a member function query() on null

put this line in parent construct : $this->load->database();

function  __construct() {
    parent::__construct();
    $this->load->library('lib_name');
    $model=array('model_name');
    $this->load->model($model);
    $this->load->database();
}

this way.. it should work..

jQuery vs. javascript?

Personally i think you should learn the hard way first. It will make you a better programmer and you will be able to solve that one of a kind issue when it comes up. After you can do it with pure JavaScript then using jQuery to speed up development is just an added bonus.

If you can do it the hard way then you can do it the easy way, it doesn't work the other way around. That applies to any programming paradigm.

How does cellForRowAtIndexPath work?

Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement

In Objective C

-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if(tableView == firstTableView)
  {
      //code for first table view 
      [cell.contentView addSubview: someView];
  }

  if(tableview == secondTableView)
  {
      //code for secondTableView 
      [cell.contentView addSubview: someView];
  }
  return cell;
}

In Swift 3.0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

  if(tableView == firstTableView)   {
     //code for first table view 
  }

  if(tableview == secondTableView)      {
     //code for secondTableView 
  }

  return cell
}

How do I extract data from a DataTable?

Please, note that Open and Close the connection is not necessary when using DataAdapter.

So I suggest please update this code and remove the open and close of the connection:

        SqlDataAdapter adapt = new SqlDataAdapter(cmd);

conn.Open(); // this line of code is uncessessary

        Console.WriteLine("connection opened successfuly");
        adapt.Fill(table);

conn.Close(); // this line of code is uncessessary

        Console.WriteLine("connection closed successfuly");

Reference Documentation

The code shown in this example does not explicitly open and close the Connection. The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. If Fill opened the connection, it also closes the connection when Fill is finished. This can simplify your code when you deal with a single operation such as a Fill or an Update. However, if you are performing multiple operations that require an open connection, you can improve the performance of your application by explicitly calling the Open method of the Connection, performing the operations against the data source, and then calling the Close method of the Connection. You should try to keep connections to the data source open as briefly as possible to free resources for use by other client applications.

Permission denied (publickey) when SSH Access to Amazon EC2 instance

You need to do the following steps:

  1. Open your ssh client or terminal if you are using Linux.
  2. Locate your private key file and change your directory.
    cd <path to your .pem file>
  3. Execute below commands:
    chmod 400 <filename>.pem
    ssh -i <filename>.pem ubuntu@<ipaddress.com>

If ubuntu user is not working then try with ec2-user.

JavaScript Object Id

Actually, you don't need to modify the object prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.

var __next_objid=1;
function objectId(obj) {
    if (obj==null) return null;
    if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
    return obj.__obj_id;
}

Disable/Enable Submit Button until all forms have been filled

Just use

document.getElementById('submitbutton').disabled = !cansubmit;

instead of the the if-clause that works only one-way.

Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.

Unity Scripts edited in Visual studio don't provide autocomplete

I solved to install the same version of .NET on WIN that was configured in my Unity project. (Player Settings)

Android: Force EditText to remove focus?

editText.setFocusableInTouchMode(true)

The EditText will be able to get the focus when the user touch it. When the main layout (activity, dialog, etc.) becomes visible the EditText doesn't automatically get the focus even though it is the first view in the layout.

Comparing Dates in Oracle SQL

from your query:

Select employee_id, count(*) From Employee 
Where to_char(employee_date_hired, 'DD-MON-YY') > '31-DEC-95' 

i think its not to display the number of employees that are hired after June 20, 1994. if you want show number of employees, you can use:

Select count(*) From Employee 
Where to_char(employee_date_hired, 'YYYMMMDDD') > 19940620 

I think for best practice to compare dates you can use:

employee_date_hired > TO_DATE('20-06-1994', 'DD-MM-YYYY');
or
to_char(employee_date_hired, 'YYYMMMDDD') > 19940620;

How to use the gecko executable with Selenium

You need to specify the system property with the path the .exe when starting the Selenium server node. See also the accepted anwser to Selenium grid with Chrome driver (WebDriverException: The path to the driver executable must be set by the webdriver.chrome.driver system property)

Include files from parent or other directory

Depends on where the file you are trying to include from is located.

Example:

/rootdir/pages/file.php

/someotherDir/index.php

If you wrote the following in index.php: include('/rootdir/pages/file.php');it would error becuase it would try to get:

/someotherDir/rootdir/pages/file.php Which of course doesn't exist...

So you would have to use include('../rootdir/pages/file.php');

Limiting the number of characters per line with CSS

The latest way to go is to use the unit 'ch' which stands for character.

You can simply write:

p { max-width: 75ch; }

The only trick is that whitespaces won't be counted as characters..

Check also this post: https://stackoverflow.com/a/26975271/4069992

What's the common practice for enums in Python?

I've seen this pattern several times:

>>> class Enumeration(object):
        def __init__(self, names):  # or *names, with no .split()
            for number, name in enumerate(names.split()):
                setattr(self, name, number)

>>> foo = Enumeration("bar baz quux")
>>> foo.quux
2

You can also just use class members, though you'll have to supply your own numbering:

>>> class Foo(object):
        bar  = 0
        baz  = 1
        quux = 2

>>> Foo.quux
2

If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.

Display UIViewController as Popup in iPhone

You can use EzPopup (https://github.com/huynguyencong/EzPopup), it is a Swift pod and very easy to use:

// init YourViewController
let contentVC = ...

// Init popup view controller with content is your content view controller
let popupVC = PopupViewController(contentController: contentVC, popupWidth: 100, popupHeight: 200)

// show it by call present(_ , animated:) method from a current UIViewController
present(popupVC, animated: true)

mysql update query with sub query

For the impatient:

UPDATE target AS t
INNER JOIN (
  SELECT s.id, COUNT(*) AS count
  FROM source_grouped AS s
  -- WHERE s.custom_condition IS (true)
  GROUP BY s.id
) AS aggregate ON aggregate.id = t.id
SET t.count = aggregate.count

That's @mellamokb's answer, as above, reduced to the max.

JAVA Unsupported major.minor version 51.0

This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7

You may also check Unsupported major.minor version 51.0

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)

As here str(u'\u2013') is causing error so use isinstance(foo,basestring) to check for unicode/string, if not of type base string convert it into Unicode and then apply encode

if isinstance(foo,basestring):
    foo.encode('utf8')
else:
    unicode(foo).encode('utf8')

further read

Warning - Build path specifies execution environment J2SE-1.4

Whether you're using the maven eclipse plugin or m2eclipse, Eclipse's project configuration is derived from the POM, so you need to configure the maven compiler plugin for 1.6 (it defaults to 1.4).

Add the following to your project's pom.xml, save, then go to your Eclipse project and select Properties > Maven > Update Project Configuration:

<project>
 <build>
  <pluginManagement>
   <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>          
        <configuration>
            <source>1.6</source>
            <target>1.6</target>
        </configuration>
    </plugin>
   </plugins>
  </pluginManagement>
 </build>
</project>

How to check if a python module exists without importing it

Use one of the functions from pkgutil, for example:

from pkgutil import iter_modules

def module_exists(module_name):
    return module_name in (name for loader, name, ispkg in iter_modules())

Labels for radio buttons in rails form

This an example from my project for rating using radio buttons and its labels

<div class="rating">
  <%= form.radio_button :star, '1' %>
  <%= form.label :star, '?', value: '1' %>

  <%= form.radio_button :star, '2' %>
  <%= form.label :star, '?', value: '2' %>

  <%= form.radio_button :star, '3' %>
  <%= form.label :star, '?', value: '3' %>

  <%= form.radio_button :star, '4' %>
  <%= form.label :star, '?', value: '4' %>

  <%= form.radio_button :star, '5' %>
  <%= form.label :star, '?', value: '5' %>
</div>

How to save S3 object to a file using boto3

boto3 now has a nicer interface than the client:

resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)

This by itself isn't tremendously better than the client in the accepted answer (although the docs say that it does a better job retrying uploads and downloads on failure) but considering that resources are generally more ergonomic (for example, the s3 bucket and object resources are nicer than the client methods) this does allow you to stay at the resource layer without having to drop down.

Resources generally can be created in the same way as clients, and they take all or most of the same arguments and just forward them to their internal clients.

Synchronization vs Lock

Brian Goetz's "Java Concurrency In Practice" book, section 13.3: "...Like the default ReentrantLock, intrinsic locking offers no deterministic fairness guarantees, but the statistical fairness guarantees of most locking implementations are good enough for almost all situations..."

Select top 2 rows in Hive

Yes, here you can use LIMIT.

You can try it by the below query:

SELECT * FROM employee_list SORT BY salary DESC LIMIT 2

How can I represent an 'Enum' in Python?

I prefer to define enums in Python like so:

class Animal:
  class Dog: pass
  class Cat: pass

x = Animal.Dog

It's more bug-proof than using integers since you don't have to worry about ensuring that the integers are unique (e.g. if you said Dog = 1 and Cat = 1 you'd be screwed).

It's more bug-proof than using strings since you don't have to worry about typos (e.g. x == "catt" fails silently, but x == Animal.Catt is a runtime exception).

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project

maven -> update project

GROUP_CONCAT ORDER BY

The group_concat supports its own order by clause

http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/

So you should be able to write:

SELECT li.clientid, group_concat(li.views order by views) AS views,
group_concat(li.percentage order by percentage) 
FROM table_views GROUP BY client_id

Android SeekBar setOnSeekBarChangeListener

Seekbar called onProgressChanged method when we initialize first time. We can skip by using below code We need to check boolean it return false when initialize automatically

volumeManager.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(b){
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

Here an alternative using SUBSTRING

SELECT
            SUBSTRING([Field], LEN([Field]) - 2, 3) [Right3],
            SUBSTRING([Field], 0, LEN([Field]) - 2) [TheRest]
    FROM 
            [Fields]

with fiddle

Adding one day to a date

It Worked for me: For Current Date

$date = date('Y-m-d', strtotime("+1 day"));

for anydate:

date('Y-m-d', strtotime("+1 day", strtotime($date)));

Rolling back local and remote git repository by 1 commit

for me works this two commands:

git checkout commit_id
git push origin +name_of_branch

Get current date in DD-Mon-YYY format in JavaScript/Jquery

const date = new Date();

date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }))

Google API authentication: Not valid origin for the client

Trying on a different browser(chrome) worked for me and clearing cache on firefox cleared the issue.

(PS: Not add the hosting URIs to Authorized JavaScript origins in API credentials would give you Error:redirect_uri_mismatch)

Why is it OK to return a 'vector' from a function?

Pre C++11:

The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.

See this question & answer for further details.

C++11:

The function will move the value. See this answer for further details.

Passing Arrays to Function in C++

The syntaxes

int[]

and

int[X] // Where X is a compile-time positive integer

are exactly the same as

int*

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

Clang vs GCC for my Linux Development project

I use both Clang and GCC, I find Clang has some useful warnings, but for my own ray-tracing benchmarks - its consistently 5-15% slower then GCC (take that with grain of salt of course, but attempted to use similar optimization flags for both).

So for now I use Clang static analysis and its warnings with complex macros: (though now GCC's warnings are pretty much as good - gcc4.8 - 4.9).

Some considerations:

  • Clang has no OpenMP support, only matters if you take advantage of that but since I do, its a limitation for me. (*****)
  • Cross compilation may not be as well supported (FreeBSD 10 for example still use GCC4.x for ARM), gcc-mingw for example is available on Linux... (YMMV).
  • Some IDE's don't yet support parsing Clangs output (QtCreator for example *****). EDIT: QtCreator now supports Clang's output
  • Some aspects of GCC are better documented and since GCC has been around for longer and is widely used, you might find it easier to get help with warnings / error messages.

***** - these areas are in active development and may soon be supported

How can I install a package with go get?

First, we need GOPATH

The $GOPATH is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT directory where Go is installed.

export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin

We used ~/gocode path in our computer to store the source of our application and its dependencies. The GOPATH directory will also store the binaries of their packages.

Then check Go env

You system must have $GOPATH and $GOROOT, below is my Env:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Now, you run download go package:

go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]

Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.

How to remove time portion of date in C# in DateTime object only?

Declare the variable as a string.

example :

public string dateOfBirth ;

then assign a value like :

dateOfBirth = ((DateTime)(datetimevaluefromDB)).ToShortDateString();

Which font is used in Visual Studio Code Editor and how to change fonts?

Open vscode.

Press ctrl,.

The setting is "editor.fontFamily".

On Linux to get a list of fonts (and their names which you have to use) run this in another shell:

fc-list | awk '{$1=""}1' | cut -d: -f1 | sort| uniq

You can specify a list of fonts, to have fallback values in case a font is missing.

Simple Vim commands you wish you'd known earlier

gv starts visual mode and automatically selects what you previously had selected.

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

auto refresh for every 5 mins

Page should be refresh auto using meta tag

<meta http-equiv="Refresh" content="60"> 

content value in seconds.after one minute page should be refresh

How to debug PDO database queries?

No. PDO queries are not prepared on the client side. PDO simply sends the SQL query and the parameters to the database server. The database is what does the substitution (of the ?'s). You have two options:

  • Use your DB's logging function (but even then it's normally shown as two separate statements (ie, "not final") at least with Postgres)
  • Output the SQL query and the paramaters and piece it together yourself

python: how to identify if a variable is an array or a scalar

Combining @jamylak and @jpaddison3's answers together, if you need to be robust against numpy arrays as the input and handle them in the same way as lists, you should use

import numpy as np
isinstance(P, (list, tuple, np.ndarray))

This is robust against subclasses of list, tuple and numpy arrays.

And if you want to be robust against all other subclasses of sequence as well (not just list and tuple), use

import collections
import numpy as np
isinstance(P, (collections.Sequence, np.ndarray))

Why should you do things this way with isinstance and not compare type(P) with a target value? Here is an example, where we make and study the behaviour of NewList, a trivial subclass of list.

>>> class NewList(list):
...     isThisAList = '???'
... 
>>> x = NewList([0,1])
>>> y = list([0,1])
>>> print x
[0, 1]
>>> print y
[0, 1]
>>> x==y
True
>>> type(x)
<class '__main__.NewList'>
>>> type(x) is list
False
>>> type(y) is list
True
>>> type(x).__name__
'NewList'
>>> isinstance(x, list)
True

Despite x and y comparing as equal, handling them by type would result in different behaviour. However, since x is an instance of a subclass of list, using isinstance(x,list) gives the desired behaviour and treats x and y in the same manner.

Add Bootstrap Glyphicon to Input Box

If you are fortunate enough to only need modern browsers: try css transform translate. This requires no wrappers, and can be customized so that you can allow more spacing for input[type=number] to accomodate the input spinner, or move it to the left of the handle.

    @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");


.is-invalid {
  height: 30px;
  box-sizing: border-box;
}

.is-invalid-x {
  font-size:27px;
  vertical-align:middle;
  color: red;
  top: initial;
  transform: translateX(-100%);
}




 <h1>Tasty Field Validation Icons using only css transform</h1>
    <label>I am just a poor boy nobody loves me</label>
    <input class="is-invalid"><span class="glyphicon glyphicon-exclamation-sign is-invalid-x"></span>

http://codepen.io/anon/pen/RPRmNq?editors=110

How to call a Python function from Node.js

You can now use RPC libraries that support Python and Javascript such as zerorpc

From their front page:

Node.js Client

var zerorpc = require("zerorpc");

var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");

client.invoke("hello", "RPC", function(error, res, more) {
    console.log(res);
});

Python Server

import zerorpc

class HelloRPC(object):
    def hello(self, name):
        return "Hello, %s" % name

s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()

How to change language of app when user selects language?

Udhay's sample code works well. Except the question of Sofiane Hassaini and Chirag SolankI, for the re-entrance, it doesn't work. I try to call Udhay's code without restart the activity in onCreate() , before super.onCreate(savedInstanceState);. Then it is OK! Only a little problem, the menu strings still not changed to the set Locale.

    public void setLocale(String lang) { //call this in onCreate()
      Locale myLocale = new Locale(lang); 
      Resources res = getResources(); 
      DisplayMetrics dm = res.getDisplayMetrics(); 
      Configuration conf = res.getConfiguration(); 
      conf.locale = myLocale; 
      res.updateConfiguration(conf, dm); 
      //Intent refresh = new Intent(this, AndroidLocalize.class); 
      //startActivity(refresh); 
      //finish();
    } 

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

First off, if you're starting a new project, go with Entity Framework ("EF") - it now generates much better SQL (more like Linq to SQL does) and is easier to maintain and more powerful than Linq to SQL ("L2S"). As of the release of .NET 4.0, I consider Linq to SQL to be an obsolete technology. MS has been very open about not continuing L2S development further.

1) Performance

This is tricky to answer. For most single-entity operations (CRUD) you will find just about equivalent performance with all three technologies. You do have to know how EF and Linq to SQL work in order to use them to their fullest. For high-volume operations like polling queries, you may want to have EF/L2S "compile" your entity query such that the framework doesn't have to constantly regenerate the SQL, or you can run into scalability issues. (see edits)

For bulk updates where you're updating massive amounts of data, raw SQL or a stored procedure will always perform better than an ORM solution because you don't have to marshal the data over the wire to the ORM to perform updates.

2) Speed of Development

In most scenarios, EF will blow away naked SQL/stored procs when it comes to speed of development. The EF designer can update your model from your database as it changes (upon request), so you don't run into synchronization issues between your object code and your database code. The only time I would not consider using an ORM is when you're doing a reporting/dashboard type application where you aren't doing any updating, or when you're creating an application just to do raw data maintenance operations on a database.

3) Neat/Maintainable code

Hands down, EF beats SQL/sprocs. Because your relationships are modeled, joins in your code are relatively infrequent. The relationships of the entities are almost self-evident to the reader for most queries. Nothing is worse than having to go from tier to tier debugging or through multiple SQL/middle tier in order to understand what's actually happening to your data. EF brings your data model into your code in a very powerful way.

4) Flexibility

Stored procs and raw SQL are more "flexible". You can leverage sprocs and SQL to generate faster queries for the odd specific case, and you can leverage native DB functionality easier than you can with and ORM.

5) Overall

Don't get caught up in the false dichotomy of choosing an ORM vs using stored procedures. You can use both in the same application, and you probably should. Big bulk operations should go in stored procedures or SQL (which can actually be called by the EF), and EF should be used for your CRUD operations and most of your middle-tier's needs. Perhaps you'd choose to use SQL for writing your reports. I guess the moral of the story is the same as it's always been. Use the right tool for the job. But the skinny of it is, EF is very good nowadays (as of .NET 4.0). Spend some real time reading and understanding it in depth and you can create some amazing, high-performance apps with ease.

EDIT: EF 5 simplifies this part a bit with auto-compiled LINQ Queries, but for real high volume stuff, you'll definitely need to test and analyze what fits best for you in the real world.

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes it is possible to have multiple $(document).ready() calls. However, I don't think you can know in which way they will be executed. (source)

How do you clear the focus in javascript?

.focus() and then .blur() something else arbitrary on your page. Since only one element can have the focus, it is transferred to that element and then removed.

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I also had a similar problem

My problem was solved by doing the following:

enter image description here

enter image description here

MySQL Workbench: How to keep the connection alive

I was getting this error 2013 and none of the above preference changes did anything to fix the problem. I restarted mysql service and the problem went away.

Sorting an Array of int using BubbleSort

Your sort logic is wrong. This is the pseudo-code for bubble sort:

for i = 1:n,
    swapped = false
    for j = n:i+1, 
        if a[j] < a[j-1], 
            swap a[j,j-1]
            swapped = true
    ? invariant: a[1..i] in final position
    break if not swapped
end

See this sorting web site for good tutorial on all the various sorting methods.

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

error: package com.android.annotations does not exist

Use implementation androidx.appcompat:appcompat:1.0.2 in gradle and then

change import android.support.annotation.Nullable; to import androidx.annotation.NonNull; in the classes imports

Angular 6: How to set response type as text while making http call

Have you tried not setting the responseType and just type casting the response?

This is what worked for me:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');


  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

How to use setprecision in C++

Below code runs correctly.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    double num1 = 3.12345678;
    cout << fixed << showpoint;
    cout << setprecision(2);
    cout << num1 << endl;
}

Java Map equivalent in C#

You can index Dictionary, you didn't need 'get'.

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

An efficient way to test/get values is TryGetValue (thanx to Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

With this method you can fast and exception-less get values (if present).

Resources:

Dictionary-Keys

Try Get Value

Should I put input elements inside a label element?

Both are correct, but putting the input inside the label makes it much less flexible when styling with CSS.

First, a <label> is restricted in which elements it can contain. For example, you can only put a <div> between the <input> and the label text, if the <input> is not inside the <label>.

Second, while there are workarounds to make styling easier like wrapping the inner label text with a span, some styles will be in inherited from parent elements, which can make styling more complicated.

How to tackle daylight savings using TimeZone in Java

Implementing the TimeZone class to set the timezone to the Calendar takes care of the daylight savings.

java.util.TimeZone represents a time zone offset, and also figures out daylight savings.

sample code:

TimeZone est_timeZone = TimeZoneIDProvider.getTimeZoneID(TimeZoneID.US_EASTERN).getTimeZone();
Calendar enteredCalendar = Calendar.getInstance();
enteredCalendar.setTimeZone(est_timeZone);

What is the difference between a token and a lexeme?

CS researchers, as those from Math, are fond of creating "new" terms. The answers above are all nice but apparently, there is no such a great need to distinguish tokens and lexemes IMHO. They are like two ways to represent the same thing. A lexeme is concrete -- here a set of char; a token, on the other hand, is abstract -- usually referring to the type of a lexeme together with its semantic value if that makes sense. Just my two cents.

How to do jquery code AFTER page loading?

Edit: This code will wait until all content (images and scripts) are fully loaded and rendered in the browser.

I've had this problem where $(window).on('load',function(){ ... }) would fire too quick for my code since the Javascript I used was for formatting purposes and hiding elements. The elements where hidden too soon and where left with a height of 0.

I now use $(window).on('pageshow',function(){ //code here }); and it fires at the time I need.

How to use Angular4 to set focus by element id

Component

import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
... 

@ViewChild('input1', {static: false}) inputEl: ElementRef;
    
ngAfterViewInit() {
   setTimeout(() => this.inputEl.nativeElement.focus());
}

HTML

<input type="text" #input1>

Decimal number regular expression, where digit after decimal is optional

In Perl, use Regexp::Common which will allow you to assemble a finely-tuned regular expression for your particular number format. If you are not using Perl, the generated regular expression can still typically be used by other languages.

Printing the result of generating the example regular expressions in Regexp::Common::Number:

$ perl -MRegexp::Common=number -E 'say $RE{num}{int}'
(?:(?:[-+]?)(?:[0123456789]+))

$ perl -MRegexp::Common=number -E 'say $RE{num}{real}'
(?:(?i)(?:[-+]?)(?:(?=[.]?[0123456789])(?:[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:(?:[E])(?:(?:[-+]?)(?:[0123456789]+))|))

$ perl -MRegexp::Common=number -E 'say $RE{num}{real}{-base=>16}'
(?:(?i)(?:[-+]?)(?:(?=[.]?[0123456789ABCDEF])(?:[0123456789ABCDEF]*)(?:(?:[.])(?:[0123456789ABCDEF]{0,}))?)(?:(?:[G])(?:(?:[-+]?)(?:[0123456789ABCDEF]+))|))

How to change XML Attribute

Mike; Everytime I need to modify an XML document I work it this way:

//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(xmlFile);

XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;

xmlDoc.Save(xmlFile);

//xmlFile is the path of your file to be modified

I hope you find it useful

DateTime2 vs DateTime in SQL Server

while there is increased precision with datetime2, some clients doesn't support date, time, or datetime2 and force you to convert to a string literal. Specifically Microsoft mentions "down level" ODBC, OLE DB, JDBC, and SqlClient issues with these data types and has a chart showing how each can map the type.

If value compatability over precision, use datetime

Stopping a CSS3 Animation on last frame

The best way seems to put the final state at the main part of css. Like here, i put width to 220px, so that it finally becomes 220px. But starting to 0px;

div.menu-item1 {
  font-size: 20px;
  border: 2px solid #fff;
  width: 220px;
  animation: slide 1s;
  -webkit-animation: slide 1s; /* Safari and Chrome */
}
@-webkit-keyframes slide { /* Safari and Chrome */
  from {width:0px;}
  to {width:220px;}
}  

How to Delete node_modules - Deep Nested Folder in Windows

Any file manager allow to avoid such issues, e.g Far Manager

enter image description here

Passing arrays as parameters in bash

Commenting on Ken Bertelson solution and answering Jan Hettich:

How it works

the takes_ary_as_arg descTable[@] optsTable[@] line in try_with_local_arys() function sends:

  1. This is actually creates a copy of the descTable and optsTable arrays which are accessible to the takes_ary_as_arg function.
  2. takes_ary_as_arg() function receives descTable[@] and optsTable[@] as strings, that means $1 == descTable[@] and $2 == optsTable[@].
  3. in the beginning of takes_ary_as_arg() function it uses ${!parameter} syntax, which is called indirect reference or sometimes double referenced, this means that instead of using $1's value, we use the value of the expanded value of $1, example:

    baba=booba
    variable=baba
    echo ${variable} # baba
    echo ${!variable} # booba
    

    likewise for $2.

  4. putting this in argAry1=("${!1}") creates argAry1 as an array (the brackets following =) with the expanded descTable[@], just like writing there argAry1=("${descTable[@]}") directly. the declare there is not required.

N.B.: It is worth mentioning that array initialization using this bracket form initializes the new array according to the IFS or Internal Field Separator which is by default tab, newline and space. in that case, since it used [@] notation each element is seen by itself as if he was quoted (contrary to [*]).

My reservation with it

In BASH, local variable scope is the current function and every child function called from it, this translates to the fact that takes_ary_as_arg() function "sees" those descTable[@] and optsTable[@] arrays, thus it is working (see above explanation).

Being that case, why not directly look at those variables themselves? It is just like writing there:

argAry1=("${descTable[@]}")

See above explanation, which just copies descTable[@] array's values according to the current IFS.

In summary

This is passing, in essence, nothing by value - as usual.

I also want to emphasize Dennis Williamson comment above: sparse arrays (arrays without all the keys defines - with "holes" in them) will not work as expected - we would loose the keys and "condense" the array.

That being said, I do see the value for generalization, functions thus can get the arrays (or copies) without knowing the names:

  • for ~"copies": this technique is good enough, just need to keep aware, that the indices (keys) are gone.
  • for real copies: we can use an eval for the keys, for example:

    eval local keys=(\${!$1})
    

and then a loop using them to create a copy. Note: here ! is not used it's previous indirect/double evaluation, but rather in array context it returns the array indices (keys).

  • and, of course, if we were to pass descTable and optsTable strings (without [@]), we could use the array itself (as in by reference) with eval. for a generic function that accepts arrays.

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

i had the same problem i had linked jquery twice . The later version was overwriting my plugin.

I just removed the later jquery it started working.

SQL query for finding records where count > 1

I wouldn't recommend the HAVING keyword for newbies, it is essentially for legacy purposes.

I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:

I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.

So I've taken a literal interpretation.

The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES but it could be a VIEW:

WITH PAYMENT_TALLIES (user_id, zip, tally)
     AS
     (
      SELECT user_id, zip, COUNT(*) AS tally
        FROM PAYMENT
       GROUP 
          BY user_id, zip
     )
SELECT DISTINCT *
  FROM PAYMENT AS P
 WHERE EXISTS (
               SELECT * 
                 FROM PAYMENT_TALLIES AS PT
                WHERE P.user_id = PT.user_id
                      AND PT.tally > 1
              );

not finding android sdk (Unity)

These are the steps that eventually worked for me...

  • Install JDK jdk1.8.0_131 (yes, this specific version, not a later version) and set it as the JDK Path in Unity.

  • Delete android sdk tools folder : [android_sdk_root]/tools

  • Download SDK Tools v25.2.5 (this specific version) from http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip

  • Extract the tools folder in that archive to Android SDK root

  • Build your project

How do you create vectors with specific intervals in R?

In R the equivalent function is seq and you can use it with the option by:

seq(from = 5, to = 100, by = 5)
# [1]   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

In addition to by you can also have other options such as length.out and along.with.

length.out: If you want to get a total of 10 numbers between 0 and 1, for example:

seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1

along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).

seq(along.with=c(10,20,30))
# [1] 1 2 3

Although, instead of using the along.with option, it is recommended to use seq_along in this case. From the documentation for ?seq

seq is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

seq_along: Instead of seq(along.with(.))

seq_along(c(10,20,30))
# [1] 1 2 3

Hope this helps.

Converting SVG to PNG using C#

To add to the response from @Anish, if you are having issues with not seeing the text when exporting the SVG to an image, you can create a recursive function to loop through the children of the SVGDocument, try to cast it to a SvgText if possible (add your own error checking) and set the font family and style.

    foreach(var child in svgDocument.Children)
    {
        SetFont(child);
    }

    public void SetFont(SvgElement element)
    {
        foreach(var child in element.Children)
        {
            SetFont(child); //Call this function again with the child, this will loop
                            //until the element has no more children
        }

        try
        {
            var svgText = (SvgText)parent; //try to cast the element as a SvgText
                                           //if it succeeds you can modify the font

            svgText.Font = new Font("Arial", 12.0f);
            svgText.FontSize = new SvgUnit(12.0f);
        }
        catch
        {

        }
    }

Let me know if there are questions.

how to customise input field width in bootstrap 3

In Bootstrap 3, .form-control (the class you give your inputs) has a width of 100%, which allows you to wrap them into col-lg-X divs for arrangement. Example from the docs:

<div class="row">
  <div class="col-lg-2">
    <input type="text" class="form-control" placeholder=".col-lg-2">
  </div>
  <div class="col-lg-3">
    <input type="text" class="form-control" placeholder=".col-lg-3">
  </div>
  <div class="col-lg-4">
    <input type="text" class="form-control" placeholder=".col-lg-4">
  </div>
</div>

See under Column sizing.

It's a bit different than in Bootstrap 2.3.2, but you get used to it quickly.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

How to workaround 'FB is not defined'?

There is solution for you :)

You must run your script after window loaded

if you use jQuery, you can use simple way:

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId      : 'your-app-id',
            xfbml      : true,
            status     : true,
            version    : 'v2.5'
        });
    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>

<script>
$(window).load(function() {
    var comment_callback = function(response) {
        console.log("comment_callback");
        console.log(response);
    }
    FB.Event.subscribe('comment.create', comment_callback);
    FB.Event.subscribe('comment.remove', comment_callback);
});
</script>

How to use hex color values

Swift 5

extension UIColor{

/// Converting hex string to UIColor
///
/// - Parameter hexString: input hex string
convenience init(hexString: String) {
    let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    var int = UInt64()
    Scanner(string: hex).scanHexInt64(&int)
    let a, r, g, b: UInt64
    switch hex.count {
    case 3:    
        (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6: 
        (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8: 
        (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
        (a, r, g, b) = (255, 0, 0, 0)
    }
    self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}

Call using UIColor(hexString: "your hex string")

Adjust list style image position?

Or you can use

list-style-position: inside;

How to change root logging level programmatically for logback

As pointed out by others, you simply create mockAppender and then create a LoggingEvent instance which essentially listens to the logging event registered/happens inside mockAppender.

Here is how it looks like in test:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;

@RunWith(MockitoJUnitRunner.class)
public class TestLogEvent {

// your Logger
private Logger log = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

// here we mock the appender
@Mock
private Appender<ILoggingEvent> mockAppender;

// Captor is generic-ised with ch.qos.logback.classic.spi.LoggingEvent
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;

/**
 * set up the test, runs before each test
 */
@Before
public void setUp() {
    log.addAppender(mockAppender);
}

/**
 * Always have this teardown otherwise we can stuff up our expectations. 
 * Besides, it's good coding practise
 */
@After
public void teardown() {
    log.detachAppender(mockAppender);
}


// Assuming this is your method
public void yourMethod() {
    log.info("hello world");
}

@Test
public void testYourLoggingEvent() {

    //invoke your method
    yourMethod();

    // now verify our logging interaction
    // essentially appending the event to mockAppender
    verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture());

    // Having a generic captor means we don't need to cast
    final LoggingEvent loggingEvent = captorLoggingEvent.getValue();

    // verify that info log level is called
    assertThat(loggingEvent.getLevel(), is(Level.INFO));

    // Check the message being logged is correct
    assertThat(loggingEvent.getFormattedMessage(), containsString("hello world"));
}
}

"Could not find a version that satisfies the requirement opencv-python"

It happened with me on Windows, pip was not able to install opencv-python==3.4.0.12.

Later found out that it was due to the Python version, Python 3.7 has some issue with not getting linked to https://github.com/skvark/opencv-python.

Downgraded to Python 3.6 and it worked with:

pip3 install opencv-python

How do I add a ToolTip to a control?

I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.

private void Info_MouseHover(object sender, EventArgs e)
{
    Control senderObject = sender as Control;
    string hoveredControl = senderObject.Tag.ToString();

    // only instantiate a tooltip if the control's tag contains data
    if (hoveredControl != "")
    {
        ToolTip info = new ToolTip
        {
            AutomaticDelay = 500
        };

        string tooltipMessage = string.Empty;

        // add all conditionals here to modify message based on the tag 
        // of the hovered control
        if (hoveredControl == "save button")
        {
            tooltipMessage = "This button will save stuff.";
        }

        info.SetToolTip(senderObject, tooltipMessage);
    }
}

Can you split a stream into two streams?

This was the least bad answer I could come up with.

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;

public class Test {

    public static <T, L, R> Pair<L, R> splitStream(Stream<T> inputStream, Predicate<T> predicate,
            Function<Stream<T>, L> trueStreamProcessor, Function<Stream<T>, R> falseStreamProcessor) {

        Map<Boolean, List<T>> partitioned = inputStream.collect(Collectors.partitioningBy(predicate));
        L trueResult = trueStreamProcessor.apply(partitioned.get(Boolean.TRUE).stream());
        R falseResult = falseStreamProcessor.apply(partitioned.get(Boolean.FALSE).stream());

        return new ImmutablePair<L, R>(trueResult, falseResult);
    }

    public static void main(String[] args) {

        Stream<Integer> stream = Stream.iterate(0, n -> n + 1).limit(10);

        Pair<List<Integer>, String> results = splitStream(stream,
                n -> n > 5,
                s -> s.filter(n -> n % 2 == 0).collect(Collectors.toList()),
                s -> s.map(n -> n.toString()).collect(Collectors.joining("|")));

        System.out.println(results);
    }

}

This takes a stream of integers and splits them at 5. For those greater than 5 it filters only even numbers and puts them in a list. For the rest it joins them with |.

outputs:

 ([6, 8],0|1|2|3|4|5)

Its not ideal as it collects everything into intermediary collections breaking the stream (and has too many arguments!)

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

Align text in JLabel to the right

This can be done in two ways.

JLabel Horizontal Alignment

You can use the JLabel constructor:

JLabel(String text, int horizontalAlignment) 

To align to the right:

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

JLabel also has setHorizontalAlignment:

label.setHorizontalAlignment(SwingConstants.RIGHT);

This assumes the component takes up the whole width in the container.

Using Layout

A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout:

    Box box = Box.createVerticalBox();
    JLabel label1 = new JLabel("test1, the beginning");
    label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label1);

    JLabel label2 = new JLabel("test2, some more");
    label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label2);

    JLabel label3 = new JLabel("test3");
    label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label3);


    add(box);

orderBy multiple fields in Angular

Please see this:

http://jsfiddle.net/JSWorld/Hp4W7/32/

<div ng-repeat="division in divisions | orderBy:['group','sub']">{{division.group}}-{{division.sub}}</div>

Convert date time string to epoch in Bash

get_curr_date () {
    # get unix time
    DATE=$(date +%s)
    echo "DATE_CURR : "$DATE
}

conv_utime_hread () {
    # convert unix time to human readable format
    DATE_HREAD=$(date -d @$DATE +%Y%m%d_%H%M%S)
    echo "DATE_HREAD          : "$DATE_HREAD
}

How to create a self-signed certificate with OpenSSL

this worked for me

openssl req -x509 -nodes -subj '/CN=localhost'  -newkey rsa:4096 -keyout ./sslcert/key.pem -out ./sslcert/cert.pem -days 365

server.js

var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var compression = require('compression');
var express = require('express');
var app = express();

app.use(compression());
app.use(express.static(__dirname + '/www'));    

app.get('/*', function(req,res) {
  res.sendFile(path.join(__dirname+'/www/index.html'));
});

// your express configuration here

var httpServer = http.createServer(app);
var credentials = {
    key: fs.readFileSync('./sslcert/key.pem', 'utf8'),
    cert: fs.readFileSync('./sslcert/cert.pem', 'utf8')
};
var httpsServer = https.createServer(credentials, app);

httpServer.listen(8080);
httpsServer.listen(8443);

console.log(`RUNNING ON  http://127.0.0.1:8080`);
console.log(`RUNNING ON  http://127.0.0.1:8443`);

Can't get value of input type="file"?

It's old question but just in case someone bump on this tread...

var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];

No need for regex, jQuery....

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

Change this part in your Web.config, according to the below code.(try this, it works to me.)

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=.; Integrated Security=True; MultipleActiveResultSets=True" />   
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

$('input').focus(function () {
    var self = $(this);
    setTimeout(function () {
        self.select();
    }, 1);        
});

Edit: Per @DavidG's request, I can't provide details because I'm not sure why this works, but I believe it has something to do with the focus event propagating up or down or whatever it does and the input element getting the notification it's received focus. Setting the timeout gives the element a moment to realize it's done so.

Could not find method compile() for arguments Gradle

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

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

What does it mean to "call" a function in Python?

When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:

def add(a,b):
    return a + b

you would call the function like this:

add(3,5)

which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:

answer = add(4,7)

Which would set the variable answer equal to 11 in this case.

JQUERY ajax passing value from MVC View to Controller

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatu`enter code here`s) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

How to clear the cache in NetBeans

On a Mac with NetBeans 8.1,

  1. NetBeans ? About
  2. Find User Directory path in the About screen
  3. rm -fr 8.1 In your case the version could be different; remove the right version folder.
  4. Reopen NetBeans

how to change attribute "hidden" in jquery

Use prop() for updating the hidden property, and change() for handling the change event.

_x000D_
_x000D_
$('#check').change(function() {_x000D_
  $("#delete").prop("hidden", !this.checked);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <input id="check" type="checkbox" name="del_attachment_id[]" value="<?php echo $attachment['link'];?>">_x000D_
    </td>_x000D_
_x000D_
    <td id="delete" hidden="true">_x000D_
      the file will be deleted from the newsletter_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Compiling an application for use in highly radioactive environments

Here are some thoughts and ideas:

Use ROM more creatively.

Store anything you can in ROM. Instead of calculating things, store look-up tables in ROM. (Make sure your compiler is outputting your look-up tables to the read-only section! Print out memory addresses at runtime to check!) Store your interrupt vector table in ROM. Of course, run some tests to see how reliable your ROM is compared to your RAM.

Use your best RAM for the stack.

SEUs in the stack are probably the most likely source of crashes, because it is where things like index variables, status variables, return addresses, and pointers of various sorts typically live.

Implement timer-tick and watchdog timer routines.

You can run a "sanity check" routine every timer tick, as well as a watchdog routine to handle the system locking up. Your main code could also periodically increment a counter to indicate progress, and the sanity-check routine could ensure this has occurred.

Implement error-correcting-codes in software.

You can add redundancy to your data to be able to detect and/or correct errors. This will add processing time, potentially leaving the processor exposed to radiation for a longer time, thus increasing the chance of errors, so you must consider the trade-off.

Remember the caches.

Check the sizes of your CPU caches. Data that you have accessed or modified recently will probably be within a cache. I believe you can disable at least some of the caches (at a big performance cost); you should try this to see how susceptible the caches are to SEUs. If the caches are hardier than RAM then you could regularly read and re-write critical data to make sure it stays in cache and bring RAM back into line.

Use page-fault handlers cleverly.

If you mark a memory page as not-present, the CPU will issue a page fault when you try to access it. You can create a page-fault handler that does some checking before servicing the read request. (PC operating systems use this to transparently load pages that have been swapped to disk.)

Use assembly language for critical things (which could be everything).

With assembly language, you know what is in registers and what is in RAM; you know what special RAM tables the CPU is using, and you can design things in a roundabout way to keep your risk down.

Use objdump to actually look at the generated assembly language, and work out how much code each of your routines takes up.

If you are using a big OS like Linux then you are asking for trouble; there is just so much complexity and so many things to go wrong.

Remember it is a game of probabilities.

A commenter said

Every routine you write to catch errors will be subject to failing itself from the same cause.

While this is true, the chances of errors in the (say) 100 bytes of code and data required for a check routine to function correctly is much smaller than the chance of errors elsewhere. If your ROM is pretty reliable and almost all the code/data is actually in ROM then your odds are even better.

Use redundant hardware.

Use 2 or more identical hardware setups with identical code. If the results differ, a reset should be triggered. With 3 or more devices you can use a "voting" system to try to identify which one has been compromised.

How To Raise Property Changed events on a Dependency Property?

I question the logic of raising a PropertyChanged event on the second property when it's the first property that's changing. If the second properties value changes then the PropertyChanged event could be raised there.

At any rate, the answer to your question is you should implement INotifyPropertyChange. This interface contains the PropertyChanged event. Implementing INotifyPropertyChanged lets other code know that the class has the PropertyChanged event, so that code can hook up a handler. After implementing INotifyPropertyChange, the code that goes in the if statement of your OnPropertyChanged is:

if (PropertyChanged != null)
    PropertyChanged(new PropertyChangedEventArgs("MySecondProperty"));

How do you upload a file to a document library in sharepoint?

You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.

Upload using Object Model:

String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";

using (SPSite oSite = new SPSite(sharePointSite))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        if (!System.IO.File.Exists(fileToUpload))
            throw new FileNotFoundException("File not found.", fileToUpload);                    

        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

        // Prepare to upload
        Boolean replaceExistingFiles = true;
        String fileName = System.IO.Path.GetFileName(fileToUpload);
        FileStream fileStream = File.OpenRead(fileToUpload);

        // Upload document
        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

        // Commit 
        myLibrary.Update();
    }
}

How to change background color in the Notepad++ text editor?

Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.

The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.

C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes

https://draculatheme.com/notepad-plus-plus

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

You might want to add the following to your pom and try compiling

   <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/libs-snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/libs-snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

How can I post an array of string to ASP.NET MVC Controller without a form?

FYI: JQuery changed the way they serialize post data.

http://forum.jquery.com/topic/nested-param-serialization

You have to set the 'Traditional' setting to true, other wise

{ Values : ["1", "2", "3"] }

will come out as

Values[]=1&Values[]=2&Values[]=3

instead of

Values=1&Values=2&Values=3

Using CMake with GNU Make: How can I see the exact commands?

When you run make, add VERBOSE=1 to see the full command output. For example:

cmake .
make VERBOSE=1

Or you can add -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON to the cmake command for permanent verbose command output from the generated Makefiles.

cmake -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make

To reduce some possibly less-interesting output you might like to use the following options. The option CMAKE_RULE_MESSAGES=OFF removes lines like [ 33%] Building C object..., while --no-print-directory tells make to not print out the current directory filtering out lines like make[1]: Entering directory and make[1]: Leaving directory.

cmake -DCMAKE_RULE_MESSAGES:BOOL=OFF -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make --no-print-directory

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

docker inspect <container id> | grep -i ip

For example:

docker inspect 2b0c4b617a8c | grep -i ip

Callback to a Fragment from a DialogFragment

Maybe a bit late, but may help other people with the same question like I did.

You can use setTargetFragment on Dialog before showing, and in dialog you can call getTargetFragment to get the reference.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

How can I use different certificates on specific connections?

I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).

This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.

So this is in our LocalSSLSocketFactory:

static {
    try {
        SSL_CONTEXT = SSLContext.getInstance("SSL");
        SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    } catch (KeyManagementException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });

    return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}

Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

How can I add NSAppTransportSecurity to my info.plist file?

Just to clarify ... You should always use httpS

But you can bypass it adding the exception:

enter image description here

How to increment a pointer address and pointer's value?

checked the program and the results are as,

p++;    // use it then move to next int position
++p;    // move to next int and then use it
++*p;   // increments the value by 1 then use it 
++(*p); // increments the value by 1 then use it
++*(p); // increments the value by 1 then use it
*p++;   // use the value of p then moves to next position
(*p)++; // use the value of p then increment the value
*(p)++; // use the value of p then moves to next position
*++p;   // moves to the next int location then use that value
*(++p); // moves to next location then use that value

CREATE DATABASE permission denied in database 'master' (EF code-first)

I'm going to add what I've had to do, as it is an amalgamation of the above. I'm using Code First, tried using 'create-database' but got the error in the title. Closed and re-opened (as Admin this time) - command not recognised but 'update-database' was so used that. Same error.

Here are the steps I took to resolve it:

1) Opened SQL Server Management Studio and created a database "Videos"

2) Opened Server Explorer in VS2013 (under 'View') and connected to the database.

3) Right clicked on the connection -> properties, and grabbed the connection string.

4) In the web.config I added the connection string

   <connectionStrings>
<add name="DefaultConnection"
  connectionString="Data Source=MyMachine;Initial Catalog=Videos;Integrated Security=True" providerName="System.Data.SqlClient"
  />
  </connectionStrings>

5) Where I set up the context, I need to reference DefaultConnection:

using System.Data.Entity;

namespace Videos.Models
{
public class VideoDb : DbContext
{
    public VideoDb()
        : base("name=DefaultConnection")
    {

    }

    public DbSet<Video> Videos { get; set; }
}
}

6) In Package Manager console run 'update-database' to create the table(s).

Remember you can use Seed() to insert values when creating, in Configuration.cs:

        protected override void Seed(Videos.Models.VideoDb context)
        {
        context.Videos.AddOrUpdate(v => v.Title,
            new Video() { Title = "MyTitle1", Length = 150 },
            new Video() { Title = "MyTitle2", Length = 270 }
            );

        context.SaveChanges();
        }