Programs & Examples On #Oauth provider

jQuery textbox change event doesn't fire until textbox loses focus?

if you write anything in your textbox, the event gets fired.
code as follows :

HTML:

<input type="text" id="textbox" />

JS:

<script type="text/javascript">
  $(function () {
      $("#textbox").bind('input', function() {
      alert("letter entered");
      });
   });
</script>

Safe String to BigDecimal conversion

The following sample code works well (locale need to be obtained dynamically)

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.Locale;

class TestBigDecimal {
    public static void main(String[] args) {

        String str = "0,00";
        Locale in_ID = new Locale("in","ID");
        //Locale in_ID = new Locale("en","US");

        DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance(in_ID);
        nf.setParseBigDecimal(true);

        BigDecimal bd = (BigDecimal)nf.parse(str, new ParsePosition(0));

        System.out.println("bd value : " + bd);
    }
}

Is there a way to programmatically scroll a scroll view to a specific edit text?

My EditText was nested several layers inside my ScrollView, which itself isn't the layout's root view. Because getTop() and getBottom() were seeming to report the coordinates within it's containing view, I had it compute the distance from the top of the ScrollView to the top of the EditText by iterating through the parents of the EditText.

// Scroll the view so that the touched editText is near the top of the scroll view
new Thread(new Runnable()
{
    @Override
    public
    void run ()
    {
        // Make it feel like a two step process
        Utils.sleep(333);

        // Determine where to set the scroll-to to by measuring the distance from the top of the scroll view
        // to the control to focus on by summing the "top" position of each view in the hierarchy.
        int yDistanceToControlsView = 0;
        View parentView = (View) m_editTextControl.getParent();
        while (true)
        {
            if (parentView.equals(scrollView))
            {
                break;
            }
            yDistanceToControlsView += parentView.getTop();
            parentView = (View) parentView.getParent();
        }

        // Compute the final position value for the top and bottom of the control in the scroll view.
        final int topInScrollView = yDistanceToControlsView + m_editTextControl.getTop();
        final int bottomInScrollView = yDistanceToControlsView + m_editTextControl.getBottom();

        // Post the scroll action to happen on the scrollView with the UI thread.
        scrollView.post(new Runnable()
        {
            @Override
            public void run()
            {
                int height =m_editTextControl.getHeight();
                scrollView.smoothScrollTo(0, ((topInScrollView + bottomInScrollView) / 2) - height);
                m_editTextControl.requestFocus();
            }
        });
    }
}).start();

Best practice to validate null and empty collection in Java

For all the collections including map use: isEmpty method which is there on these collection objects. But you have to do a null check before:

Map<String, String> map;

........
if(map!=null && !map.isEmpty())
......

What is the difference between old style and new style classes in Python?

Guido has written The Inside Story on New-Style Classes, a really great article about new-style and old-style class in Python.

Python 3 has only new-style class. Even if you write an 'old-style class', it is implicitly derived from object.

New-style classes have some advanced features lacking in old-style classes, such as super, the new C3 mro, some magical methods, etc.

Check if an array is empty or exists

JavaScript

( typeof(myArray) !== 'undefined' && Array.isArray(myArray) && myArray.length > 0 )

Lodash & Underscore

( _.isArray(myArray) && myArray.length > 0 )

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

You should use "merge a range of revision".

To merge changes from the trunk to a branch, inside the branch working copy choose "merge range of revisions" and enter the trunk URL and the start and end revisions to merge.

The same in the opposite way to merge a branch in the trunk.

About the --reintegrate flag, check the manual here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-merge.html#tsvn-dug-merge-reintegrate

After MySQL install via Brew, I get the error - The server quit without updating PID file

I had this issue on mac 10.10.5 Yosemite

What I did to solve this

cd /usr/local/var/mysql
sudo rm *.err && sudo rm *.pid
sudo reboot
sudo mysql.server start

Storing Objects in HTML5 localStorage

https://github.com/adrianmay/rhaboo is a localStorage sugar layer that lets you write things like this:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');

It doesn't use JSON.stringify/parse because that would be inaccurate and slow on big objects. Instead, each terminal value has its own localStorage entry.

You can probably guess that I might have something to do with rhaboo.

Java: how to import a jar file from command line

try

java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main

If you are on windows, you should use ; instead of :

TypeScript for ... of with index / key?

You can use the for..in TypeScript operator to access the index when dealing with collections.

var test = [7,8,9];
for (var i in test) {
   console.log(i + ': ' + test[i]);
} 

Output:

 0: 7
 1: 8
 2: 9

See Demo

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

How do you run a script on login in *nix?

At login, most shells execute a login script, which you can use to execute your custom script. The login script the shell executes depends, of course, upon the shell:

  • bash: .bash_profile, .bash_login, .profile (for backwards compabitibility)
  • sh: .profile
  • tcsh and csh: .login
  • zsh: .zshrc

You can probably find out what shell you're using by doing

echo $SHELL

from the prompt.

For a slightly wider definition of 'login', it's useful to know that on most distros when X is launched, your .xsessionrc will be executed when your X session is started.

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

FileSystemWatcher Changed event is raised twice

Here's my approach :

// Consider having a List<String> named _changedFiles

private void OnChanged(object source, FileSystemEventArgs e)
{
    lock (_changedFiles)
    {
        if (_changedFiles.Contains(e.FullPath))
        {
            return;
        }
        _changedFiles.Add(e.FullPath);
    }

    // do your stuff

    System.Timers.Timer timer = new Timer(1000) { AutoReset = false };
    timer.Elapsed += (timerElapsedSender, timerElapsedArgs) =>
    {
        lock (_changedFiles)
        {
            _changedFiles.Remove(e.FullPath);
        }
    };
   timer.Start();
}

This is the solution I used to solve this issue on a project where I was sending the file as attachment in a mail. It will easily avoid the twice fired event even with a smaller timer interval but in my case 1000 was alright since I was happier with missing few changes than with flooding the mailbox with > 1 message per second. At least it works just fine in case several files are changed at the exact same time.

Another solution I've thought of would be to replace the list with a dictionary mapping files to their respective MD5, so you wouldn't have to choose an arbitrary interval since you wouldn't have to delete the entry but update its value, and cancel your stuff if it hasn't changed. It has the downside of having a Dictionary growing in memory as files are monitored and eating more and more memory, but I've read somewhere that the amount of files monitored depends on the FSW's internal buffer, so maybe not that critical. Dunno how MD5 computing time would affect your code's performances either, careful =\

if checkbox is checked, do this

It may happen that "this.checked" is always "on". Therefore, I recommend:

$('#checkbox').change(function() {
  if ($(this).is(':checked')) {
    console.log('Checked');
  } else {
    console.log('Unchecked');
  }
});

Get clicked item and its position in RecyclerView

In onViewHolder set onClickListiner to any view and in side click use this code :

Toast.makeText(Drawer_bar.this, "position" + position, Toast.LENGTH_SHORT).show();

Replace Drawer_Bar with your Activity name.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

I had the same issue. The reason was the corporate proxy issue. Solution was to set the proxy setting as @rsp says.

npm config set proxy http://example.com:8080
npm config set https-proxy http://example.com:8080

But later I face the same issue. This time reason was my password contains a special character.

In this command you can’t provide a password with special character

. So solution is to provide percentage encoded special character in the password.

For example # has to provide as %23

https://www.w3schools.com/tags/ref_urlencode.asp

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

I implemented a nested grid view and i faced the same problem .I have used LinkButton instead of image button like this:

before i had a column like this:

<asp:TemplateField ItemStyle-Width="9">
  <ItemTemplate>
 <asp:ImageButton ID="ImgBtn" ImageUrl="Include/images/gridplus.gif" CommandName="Expand"
                        runat="server" />
  </ItemTemplate>
</asp:TemplateField>

I have replaced like this.

<asp:TemplateField>
<ItemTemplate>
     <asp:LinkButton  CommandName="Expand" ID="lnkBtn"  runat="server" ><asp:Image  ID="Img"  runat="server" ImageUrl="~/Images/app/plus.gif" /></asp:LinkButton>
      </ItemTemplate>
</asp:TemplateField> 

How can I get a list of Git branches, ordered by most recent commit?

Adds some color (since pretty-format isn't available)

[alias]
    branchdate = for-each-ref --sort=-committerdate refs/heads/ --format="%(authordate:short)%09%(objectname:short)%09%1B[0;33m%(refname:short)%1B[m%09"

How to execute a file within the python interpreter?

I'm trying to use variables and settings from that file, not to invoke a separate process.

Well, simply importing the file with import filename (minus .py, needs to be in the same directory or on your PYTHONPATH) will run the file, making its variables, functions, classes, etc. available in the filename.variable namespace.

So if you have cheddar.py with the variable spam and the function eggs – you can import them with import cheddar, access the variable with cheddar.spam and run the function by calling cheddar.eggs()

If you have code in cheddar.py that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.

Excel VBA Loop on columns

If you want to stick with the same sort of loop then this will work:

Option Explicit

Sub selectColumns()

Dim topSelection As Integer
Dim endSelection As Integer
topSelection = 2
endSelection = 10

Dim columnSelected As Integer
columnSelected = 1
Do
   With Excel.ThisWorkbook.ActiveSheet
        .Range(.Cells(columnSelected, columnSelected), .Cells(endSelection, columnSelected)).Select
   End With
   columnSelected = columnSelected + 1
Loop Until columnSelected > 10

End Sub

EDIT

If in reality you just want to loop through every cell in an area of the spreadsheet then use something like this:

Sub loopThroughCells()

'=============
'this is the starting point
Dim rwMin As Integer
Dim colMin As Integer
rwMin = 2
colMin = 2
'=============

'=============
'this is the ending point
Dim rwMax As Integer
Dim colMax As Integer
rwMax = 10
colMax = 5
'=============

'=============
'iterator
Dim rwIndex As Integer
Dim colIndex As Integer
'=============

For rwIndex = rwMin To rwMax
        For colIndex = colMin To colMax
            Cells(rwIndex, colIndex).Select
        Next colIndex
Next rwIndex

End Sub

Sending a notification from a service in Android

Well, I'm not sure if my solution is best practice. Using the NotificationBuilder my code looks like that:

private void showNotification() {
    Intent notificationIntent = new Intent(this, MainActivity.class);

    PendingIntent contentIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());
    }

Manifest:

    <activity
        android:name=".MainActivity"
        android:launchMode="singleInstance"
    </activity>

and here the Service:

    <service
        android:name=".services.ProtectionService"
        android:launchMode="singleTask">
    </service>

I don't know if there really is a singleTask at Service but this works properly at my application...

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

Best way to do this is to use a function:

<div ng-repeat="product in products | filter: myFilter">

$scope.myFilter = function (item) { 
    return item === 'red' || item === 'blue'; 
};

Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

I had this error when I tried to create a replicationcontroller. The issue was, I wrongly spelt the nginx image name in template definition.

Note: This error occurs when kubernetes is unable to pull the specified image from the repository.

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

Notification bar icon turns white in Android 5 Lollipop

Notifications are greyscale as explained below. They are not black-and-white, despite what others have written. You have probably seen icons with multiple shades, like network strength bars.

Prior to API 21 (Lollipop 5.0), colour icons work. You could force your application to target API 20, but that limits the features available to your application, so it is not recommended. You could test the running API level and set either a colour icon or a greyscale icon appropriately, but this is likely not worthwhile. In most cases, it is best to go with a greyscale icon.

Images have four channels, RGBA (red / green / blue / alpha). For notification icons, Android ignores the R, G, and B channels. The only channel that counts is Alpha, also known as opacity. Design your icon with an editor that gives you control over the Alpha value of your drawing colours.

How Alpha values generate a greyscale image:

  • Alpha = 0 (transparent) — These pixels are transparent, showing the background colour.
  • Alpha = 255 (opaque) — These pixels are white.
  • Alpha = 1 ... 254 — These pixels are exactly what you would expect, providing the shades between transparent and white.

Changing it up with setColor:

  • Call NotificationCompat.Builder.setColor(int argb). From the documentation for Notification.color:

    Accent color (an ARGB integer like the constants in Color) to be applied by the standard Style templates when presenting this notification. The current template design constructs a colorful header image by overlaying the icon image (stenciled in white) atop a field of this color. Alpha components are ignored.

    My testing with setColor shows that Alpha components are not ignored; instead, they still provide greyscale. Higher Alpha values turn a pixel white. Lower Alpha values turn a pixel to the background colour (black on my device) in the notification area, or to the specified colour in the pull-down notification. (It seems others have reported slightly different behavior, so be aware!)

How to reload .bashrc settings without logging out and back in again?

Assuming an interactive shell, and you'd like to keep your current command history and also load /etc/profile (which loads environment data including /etc/bashrc and on Mac OS X loads paths defined in /etc/paths.d/ via path_helper), append your command history and do an exec of bash with the login ('-l') option:

history -a && exec bash -l

How to stop IIS asking authentication for default website on localhost

This is most likely a NT file permissions problem. IUSR_ needs to have file system permissions to read whatever file you're requesting (like /inetpub/wwwroot/index.htm).

If you still have trouble, check the IIS logs, typically at \windows\system32\logfiles\W3SVC*.

Java: is there a map function?

Even though it's an old question I'd like to show another solution:

Just define your own operation using java generics and java 8 streams:

public static <S, T> List<T> map(Collection<S> collection, Function<S, T> mapFunction) {
   return collection.stream().map(mapFunction).collect(Collectors.toList());
}

Than you can write code like this:

List<String> hex = map(Arrays.asList(10, 20, 30, 40, 50), Integer::toHexString);

How do I assert equality on two classes without an equals method?

You can use Apache commons lang ReflectionToStringBuilder

You can either specify the attributes you want to test one by one, or better, exclude those you don't want:

String s = new ReflectionToStringBuilder(o, ToStringStyle.SHORT_PREFIX_STYLE)
                .setExcludeFieldNames(new String[] { "foo", "bar" }).toString()

You then compare the two strings as normal. For the point about reflection being slow, I assume this is only for testing, so shouldn't be so important.

Can I use git diff on untracked files?

git add -A
git diff HEAD

Generate patch if required, and then:

git reset HEAD

Converting Integer to Long

This is null-safe

Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp == null ? null : tmp.longValue();

H.264 file size for 1 hr of HD video

I'm a friend of keeping the original files, so that you can still use the archived original ones and do new encodes from these fresh ones when the old transcodes are out of date. eg. migrating them from previously transocded mpeg2-hd to mpeg4-hd (and perhaps from mpeg4-hd to its successor in sometime). but all of these should be done from the original. any compression step will followed by a loss of quality. it will need some time to redo this again, but in my opinion it's worth the effort.

so, if you want to keep the originals, you can use the running time in seconds of you tapes times the maximum datarate of hdv (constants 27mbit/s I think) to get your needed storage capacity

Disable/Enable Submit Button until all forms have been filled

Here is the code

<html>
   <body>
      <input type="text" name="name" id="name" required="required"                                    aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
      <script>
       function func()
       {
        var namdata=document.form1.name.value;
         if(namdata.match("[a-z]{1,5}"))
        {
         document.getElementById("but1").disabled=false;
        }
        }
        </script>
  </body>
</html>

Using Javascript

What is 'PermSize' in Java?

This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.

There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.

(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.

Add a new item to recyclerview programmatically?

simply add to your data structure ( mItems ) , and then notify your adapter about dataset change

private void addItem(String item) {
  mItems.add(item);
  mAdapter.notifyDataSetChanged();
}

addItem("New Item");

Convert a tensor to numpy array in Tensorflow?

To convert back from tensor to numpy array you can simply run .eval() on the transformed tensor.

Deploying my application at the root in Tomcat

You have a couple of options:

  1. Remove the out-of-the-box ROOT/ directory from tomcat and rename your war file to ROOT.war before deploying it.

  2. Deploy your war as (from your example) war_name.war and configure the context root in conf/server.xml to use your war file :

    <Context path="" docBase="war_name" debug="0" reloadable="true"></Context>
    

The first one is easier, but a little more kludgy. The second one is probably the more elegant way to do it.

Seeking useful Eclipse Java code templates

EasyMock templates

Create Mock

${:importStatic(org.easymock.EasyMock.createMock)}
${type} ${name} = createMock(${type}.class);

Reset Mock

${:importStatic(org.easymock.EasyMock.reset)}
reset(${var});

Replay Mock

${:importStatic(org.easymock.EasyMock.replay)}
replay(${var});

Verify Mock

${:importStatic(org.easymock.EasyMock.verify)}
verify(${var});

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

Add "Are you sure?" to my excel button, how can I?

Just make a custom userform that is shown when the "delete" button is pressed, then link the continue button to the actual code that does the deleting. Make the cancel button hide the userform.

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

Just log out of phpMyAdmin, that is all you need to do

What is an idempotent operation?

An idempotent operation produces the result in the same state even if you call it more than once, provided you pass in the same parameters.

What HTTP status response code should I use if the request is missing a required parameter?

In one of our API project we decide to set a 409 Status to some request, when we can't full fill it at 100% because of missing parameter.

HTTP Status Code "409 Conflict" was for us a good try because it's definition require to include enough information for the user to recognize the source of the conflict.

Reference: w3.org/Protocols/

So among other response like 400 or 404 we chose 409 to enforce the need for looking over some notes in the request helpful to set up a new and right request.

Any way our case it was particular because we need to send out some data eve if the request was not completely correct, and we need to enforce the client to look at the message and understand what was wrong in the request.

In general if we have only some missing parameter we go for a 400 and an array of missing parameter. But when we need to send some more information, like a particular case message and we want to be more sure the client will take care of it we send a 409

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

What is compiler, linker, loader?

Compiler :it is a system software which correct the error of programs,object file ,messages etc

Linker:it is a system software which combines One or more objectfiles and possible some library code into either some exicutable some library or a list of error

Loader: A program which loads the executable file to the primary memory of the machine

Difference between MongoDB and Mongoose

One more difference I found with respect to both is that it is fairly easy to connect to multiple databases with mongodb native driver while you have to use work arounds in mongoose which still have some drawbacks.

So if you wanna go for a multitenant application, go for mongodb native driver.

How can I select all elements without a given class in jQuery?

You can use the .not() method or :not() selector

Code based on your example:

$("ul#list li").not(".active") // not method
$("ul#list li:not(.active)")   // not selector

Android Spinner: Get the selected item change event

take a global variable for current selection of spinner:

int currentItem = 0;

spinner_counter = (Spinner)findViewById(R.id.spinner_counter);
String[] value={"20","40","60","80","100","All"};
aa=new ArrayAdapter<String>(this,R.layout.spinner_item_profile,value);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_counter.setAdapter(aa);

spinner_counter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if(currentItem == position){
                return; //do nothing
            }
            else
            {
                 TextView spinner_item_text = (TextView) view;
                 //write your code here
            }
            currentItem = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

//R.layout.spinner_item_profile
<?xml version="1.0" encoding="utf-8"?>

<TextView  android:id="@+id/spinner_item_text"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" 
android:layout_height="wrap_content"
android:background="@drawable/border_close_profile"
android:gravity="start"  
android:textColor="@color/black"         
android:paddingLeft="5dip"
android:paddingStart="5dip"
android:paddingTop="12dip"
android:paddingBottom="12dip"
/>

//drawable/border_close_profile
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
   <shape android:shape="rectangle">
    <solid android:color="#e2e3d7" />
   </shape>
 </item>
<item android:left="1dp"
android:right="1dp"
android:top="1dp"
android:bottom="1dp">
<shape android:shape="rectangle">
    <solid android:color="@color/white_text" />
</shape>
</item>
</layer-list>

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

How to get the CUDA version?

Use the following command to check CUDA installation by Conda:

conda list cudatoolkit

And the following command to check CUDNN version installed by conda:

conda list cudnn

If you want to install/update CUDA and CUDNN through CONDA, please use the following commands:

conda install -c anaconda cudatoolkit
conda install -c anaconda cudnn

Alternatively you can use following commands to check CUDA installation:

nvidia-smi

OR

nvcc --version

If you are using tensorflow-gpu through Anaconda package (You can verify this by simply opening Python in console and check if the default python shows Anaconda, Inc. when it starts, or you can run which python and check the location), then manually installing CUDA and CUDNN will most probably not work. You will have to update through conda instead.

If you want to install CUDA, CUDNN, or tensorflow-gpu manually, you can check out the instructions here https://www.tensorflow.org/install/gpu

Sublime Text 3 how to change the font size of the file sidebar?

To change the font name use

  "font.face": "Liberation Mono"

in this file, in my case with ST3 Default.sublime-theme

Javascript: formatting a rounded number to N decimals

This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):

function roundN(value, digits) {
   var tenToN = 10 ** digits;
   return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}

Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you'd end up with some unexpectedly long decimal part (this is due to floating point arithmetics).

A user comment at Format number to always show 2 decimal places calls this technique scaling.

Some mention there are cases that don't round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

The network path was not found

This is probably related to your database connection string or something like that.

I just solved this exception right now. What was happening is that I was using a connection string intended to be used when debugging in a different machine (the server).

I commented the wrong connection string in Web.config and uncommented the right one. Now I'm back in business... this is something I forget to look at after sometime not working in a given solution. ;)

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

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

 curl_close($curl);

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

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.

stdlib and colored output in C

Dealing with colour sequences can get messy and different systems might use different Colour Sequence Indicators.

I would suggest you try using ncurses. Other than colour, ncurses can do many other neat things with console UI.

jquery how to empty input field

To reset text, number, search, textarea inputs:

$('#shares').val('');

To reset select:

$('#select-box').prop('selectedIndex',0);

To reset radio input:

$('#radio-input').attr('checked',false);

To reset file input:

$("#file-input").val(null);

using jquery $.ajax to call a PHP function

I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php

After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.

For ease of use reference the function in a simple manner:

    var P = $.fn.php;

Then initialize the plugin:

P('init', 
{
    // The path to our function request handler is absolutely required
    'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',

    // Synchronous requests are required for method chaining functionality
    'async': false,

    // List any user defined functions in the manner prescribed here
            // There must be user defined functions with these same names in your PHP
    'userFunctions': {

        languageFunctions: 'someFunc1 someFunc2'
    }
});             

And now some usage scenarios:

// Suspend callback mode so we don't work with the DOM
P.callback(false);

// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

Demonstrating PHP function chaining:

var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );

Demonstrating sending a JSON block of PHP pseudo-code:

var data1 = 
        P.block({
    $str: "Let's use PHP's file_get_contents()!",
    $opts: 
    [
        {
            http: {
                method: "GET",
                header: "Accept-language: en\r\n" +
                        "Cookie: foo=bar\r\n"
            }
        }
    ],
    $context: 
    {
        stream_context_create: ['$opts']
    },
    $contents: 
    {
        file_get_contents: ['http://www.github.com/', false, '$context']
    },
    $html: 
    {
        htmlentities: ['$contents']
    }
}).data();
    console.log( data1 );

The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.

Rails - passing parameters in link_to

First of all, link_to is a html tag helper, its second argument is the url, followed by html_options. What you would like is to pass account_id as a url parameter to the path. If you have set up named routes correctly in routes.rb, you can use path helpers.

link_to "+ Service", new_my_service_path(:account_id => acct.id)

I think the best practice is to pass model values as a param nested within :

link_to "+ Service", new_my_service_path(:my_service => { :account_id => acct.id })

# my_services_controller.rb
def new
  @my_service = MyService.new(params[:my_service])
end

And you need to control that account_id is allowed for 'mass assignment'. In rails 3 you can use powerful controls to filter valid params within the controller where it belongs. I highly recommend.

http://apidock.com/rails/ActiveModel/MassAssignmentSecurity/ClassMethods

Also note that if account_id is not freely set by the user (e.g., a user can only submit a service for the own single account_id, then it is better practice not to send it via the request, but set it within the controller by adding something like:

@my_service.account_id = current_user.account_id 

You can surely combine the two if you only allow users to create service on their own account, but allow admin to create anyone's by using roles in attr_accessible.

hope this helps

Distinct pair of values SQL

This will give you the result you're giving as an example:

SELECT DISTINCT a, b
FROM pairs

exception in initializer error in java when using Netbeans

@Christian Ullenboom' explanation is correct.

I'm surmising that the OBD2nerForm code you posted is a static initializer block and that it is all generated. Based on that and on the stack trace, it seems likely that generated code is tripping up because it has found some component of your form that doesn't have the type that it is expecting.

I'd do the following to try and diagnose this:

  • Google for reports of similar problems with NetBeans generated forms.
  • If you are running an old version of NetBeans, scan through the "bugs fixed" pages for more recent releases. Or just upgrade try a newer release anyway to see if that fixes the problem.
  • Try cutting bits out of the form design until the problem "goes away" ... and try to figure out what the real cause is that way.
  • Run the application under a debugger to figure out what is being (incorrectly) type cast as what. Just knowing the class names may help. And looking at the instance variables of the objects may reveal more; e.g. which specific form component is causing the problem.

My suspicion is that the root cause is a combination of something a bit unusual (or incorrect) with your form design, and bugs in the NetBeans form generator that is not coping with your form. If you can figure it out, a workaround may reveal itself.

Recursively looping through an object to build a property list

Suppose that you have a JSON object like:

var example = {
    "prop1": "value1",
    "prop2": [ "value2_0", "value2_1"],
    "prop3": {
         "prop3_1": "value3_1"
    }
}

The wrong way to iterate through its 'properties':

function recursivelyIterateProperties(jsonObject) {
    for (var prop in Object.keys(jsonObject)) {
        console.log(prop);
        recursivelyIterateProperties(jsonObject[prop]);
    }
}

You might be surprised of seeing the console logging 0, 1, etc. when iterating through the properties of prop1 and prop2 and of prop3_1. Those objects are sequences, and the indexes of a sequence are properties of that object in Javascript.

A better way to recursively iterate through a JSON object properties would be to first check if that object is a sequence or not:

function recursivelyIterateProperties(jsonObject) {
    for (var prop in Object.keys(jsonObject)) {
        console.log(prop);
        if (!(typeof(jsonObject[prop]) === 'string')
            && !(jsonObject[prop] instanceof Array)) {
                recursivelyIterateProperties(jsonObject[prop]);

            }
     }
}

If you want to find properties inside of objects in arrays, then do the following:

function recursivelyIterateProperties(jsonObject) {

    if (jsonObject instanceof Array) {
        for (var i = 0; i < jsonObject.length; ++i) {
            recursivelyIterateProperties(jsonObject[i])
        }
    }
    else if (typeof(jsonObject) === 'object') {
        for (var prop in Object.keys(jsonObject)) {
            console.log(prop);
            if (!(typeof(jsonObject[prop]) === 'string')) {
                recursivelyIterateProperties(jsonObject[prop]);
            }
        }
    }
}

Which characters need to be escaped when using Bash?

format that can be reused as shell input

Edit february 2021: ${var@Q}

Under bash, you could store your variable content with Parameter Expansion's @ command for Parameter transformation:

${parameter@operator}
       Parameter transformation.  The expansion is either a transforma-
       tion of the value of parameter or  information  about  parameter
       itself,  depending on the value of operator.  Each operator is a
       single letter:

       Q      The expansion is a string that is the value of  parameter
              quoted in a format that can be reused as input.
...
       A      The  expansion  is  a string in the form of an assignment
              statement or declare command  that,  if  evaluated,  will
              recreate parameter with its attributes and value.

Sample:

$ var=$'Hello\nGood world.\n'
$ echo "$var"
Hello
Good world.

$ echo "${var@Q}"
$'Hello\nGood world.\n'

$ echo "${var@A}"
var=$'Hello\nGood world.\n'

Old answer

There is a special printf format directive (%q) built for this kind of request:

printf [-v var] format [arguments]

 %q     causes printf to output the corresponding argument
        in a format that can be reused as shell input.

Some samples:

read foo
Hello world
printf "%q\n" "$foo"
Hello\ world

printf "%q\n" $'Hello world!\n'
$'Hello world!\n'

This could be used through variables too:

printf -v var "%q" "$foo
"
echo "$var"
$'Hello world\n'

Quick check with all (128) ascii bytes:

Note that all bytes from 128 to 255 have to be escaped.

for i in {0..127} ;do
    printf -v var \\%o $i
    printf -v var $var
    printf -v res "%q" "$var"
    esc=E
    [ "$var" = "$res" ] && esc=-
    printf "%02X %s %-7s\n" $i $esc "$res"
done |
    column

This must render something like:

00 E ''         1A E $'\032'    34 - 4          4E - N          68 - h      
01 E $'\001'    1B E $'\E'      35 - 5          4F - O          69 - i      
02 E $'\002'    1C E $'\034'    36 - 6          50 - P          6A - j      
03 E $'\003'    1D E $'\035'    37 - 7          51 - Q          6B - k      
04 E $'\004'    1E E $'\036'    38 - 8          52 - R          6C - l      
05 E $'\005'    1F E $'\037'    39 - 9          53 - S          6D - m      
06 E $'\006'    20 E \          3A - :          54 - T          6E - n      
07 E $'\a'      21 E \!         3B E \;         55 - U          6F - o      
08 E $'\b'      22 E \"         3C E \<         56 - V          70 - p      
09 E $'\t'      23 E \#         3D - =          57 - W          71 - q      
0A E $'\n'      24 E \$         3E E \>         58 - X          72 - r      
0B E $'\v'      25 - %          3F E \?         59 - Y          73 - s      
0C E $'\f'      26 E \&         40 - @          5A - Z          74 - t      
0D E $'\r'      27 E \'         41 - A          5B E \[         75 - u      
0E E $'\016'    28 E \(         42 - B          5C E \\         76 - v      
0F E $'\017'    29 E \)         43 - C          5D E \]         77 - w      
10 E $'\020'    2A E \*         44 - D          5E E \^         78 - x      
11 E $'\021'    2B - +          45 - E          5F - _          79 - y      
12 E $'\022'    2C E \,         46 - F          60 E \`         7A - z      
13 E $'\023'    2D - -          47 - G          61 - a          7B E \{     
14 E $'\024'    2E - .          48 - H          62 - b          7C E \|     
15 E $'\025'    2F - /          49 - I          63 - c          7D E \}     
16 E $'\026'    30 - 0          4A - J          64 - d          7E E \~     
17 E $'\027'    31 - 1          4B - K          65 - e          7F E $'\177'
18 E $'\030'    32 - 2          4C - L          66 - f      
19 E $'\031'    33 - 3          4D - M          67 - g      

Where first field is hexa value of byte, second contain E if character need to be escaped and third field show escaped presentation of character.

Why ,?

You could see some characters that don't always need to be escaped, like ,, } and {.

So not always but sometime:

echo test 1, 2, 3 and 4,5.
test 1, 2, 3 and 4,5.

or

echo test { 1, 2, 3 }
test { 1, 2, 3 }

but care:

echo test{1,2,3}
test1 test2 test3

echo test\ {1,2,3}
test 1 test 2 test 3

echo test\ {\ 1,\ 2,\ 3\ }
test  1 test  2 test  3

echo test\ {\ 1\,\ 2,\ 3\ }
test  1, 2 test  3 

jQuery to remove an option from drop down list, given option's text/value

I have used the above option to .hide entries from 2 drops down boxes (first you select the city, then you selected the area within that city). It works fine on screen but the hidden options are still selectable via keyboard inputs.

How to return multiple objects from a Java method?

Before Java 5, I would kind of agree that the Map solution isn't ideal. It wouldn't give you compile time type checking so can cause issues at runtime. However, with Java 5, we have Generic Types.

So your method could look like this:

public Map<String, MyType> doStuff();

MyType of course being the type of object you are returning.

Basically I think that returning a Map is the right solution in this case because that's exactly what you want to return - a mapping of a string to an object.

CSS blur on background image but not on content

backdrop-filter

Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.

MDN (Mozilla Developer Network) article: https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter

Mozilla implementation: https://bugzilla.mozilla.org/show_bug.cgi?id=1178765

From the MDN documentation page:

/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);

/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);

/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);

Get a list of dates between two dates

I would use something similar to this:

DECLARE @DATEFROM AS DATETIME
DECLARE @DATETO AS DATETIME
DECLARE @HOLDER TABLE(DATE DATETIME)

SET @DATEFROM = '2010-08-10'
SET @DATETO = '2010-09-11'

INSERT INTO
    @HOLDER
        (DATE)
VALUES
    (@DATEFROM)

WHILE @DATEFROM < @DATETO
BEGIN

    SELECT @DATEFROM = DATEADD(D, 1, @DATEFROM)
    INSERT 
    INTO
        @HOLDER
            (DATE)
    VALUES
        (@DATEFROM)
END

SELECT 
    DATE
FROM
    @HOLDER

Then the @HOLDER Variable table holds all the dates incremented by day between those two dates, ready to join at your hearts content.

How to resize superview to fit all subviews with autolayout?

Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.

Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end

How to resize superview to fit all subviews with autolayout.png

Split a vector into chunks

Sorry if this answer comes so late, but maybe it can be useful for someone else. Actually there is a very useful solution to this problem, explained at the end of ?split.

> testVector <- c(1:10) #I want to divide it into 5 parts
> VectorList <- split(testVector, 1:5)
> VectorList
$`1`
[1] 1 6

$`2`
[1] 2 7

$`3`
[1] 3 8

$`4`
[1] 4 9

$`5`
[1]  5 10

What causes: "Notice: Uninitialized string offset" to appear?

It means one of your arrays isn't actually an array.

By the way, your if check is unnecessary. If $varsCount is 0 the for loop won't execute anyway.

MySQL Trigger - Storing a SELECT in a variable

You can declare local variables in MySQL triggers, with the DECLARE syntax.

Here's an example:

DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
  i SERIAL PRIMARY KEY
);

DELIMITER //
DROP TRIGGER IF EXISTS bar //

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = NEW.i;
  SET @a = x; -- set user variable outside trigger
END//

DELIMITER ;

SET @a = 0;

SELECT @a; -- returns 0

INSERT INTO foo () VALUES ();

SELECT @a; -- returns 1, the value it got during the trigger

When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row".

You can use LIMIT or MAX() to make sure that the local variable is set to a single value.

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT age FROM users WHERE name = 'Bill'); 
  -- ERROR 1242 if more than one row with 'Bill'
END//

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
  -- OK even when more than one row with 'Bill'
END//

Inheriting from a template class in c++

Rectangle will have to be a template, otherwise it is just one type. It cannot be a non-template whilst its base magically is. (Its base may be a template instantiation, though you seem to want to maintain the base's functionality as a template.)

Javascript Equivalent to PHP Explode()

var str = '0000000020C90037:TEMP:data';    // str = "0000000020C90037:TEMP:data"
str = str.replace(/^[^:]+:/, "");          // str = "TEMP:data"

LINQ query to find if items in a list are contained in another list

var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);

Faster version as per Tim's suggestion:

var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

Making a WinForms TextBox behave like your browser's address bar

private bool _isSelected = false;
private void textBox_Validated(object sender, EventArgs e)
{
    _isSelected = false;
}

private void textBox_MouseClick(object sender, MouseEventArgs e)
{
    SelectAllText(textBox);
}

private void textBox_Enter(object sender, EventArgs e)
{
    SelectAllText(textBox);
}

private void SelectAllText(TextBox text)
{
    if (!_isSelected)
    {
        _isSelected = true;
        textBox.SelectAll();
    }
}

After installation of Gulp: “no command 'gulp' found”

That's perfectly normal. If you want gulp-cli available on the command line, you need to install it globally.

npm install --global gulp-cli

See the install instruction.

Also, node_modules/.bin/ isn't in your $PATH. But it is automatically added by npm when running npm scripts (see this blog post for reference).

So you could add scripts to your package.json file:

{
    "name": "your-app",
    "version": "0.0.1",
    "scripts": {
        "gulp": "gulp",
        "minify": "gulp minify"
    }
}

You could then run npm run gulp or npm run minify to launch gulp tasks.

if block inside echo statement?

You can always use the ( <condition> ? <value if true> : <value if false> ) syntax (it's called the ternary operator - thanks to Mark for remining me :) ).

If <condition> is true, the statement would be evaluated as <value if true>. If not, it would be evaluated as <value if false>

For instance:

$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";

This is the same as:

$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
  echo "Fourteen is more than twelve";
}else{
  echo "Fourteen is not more than twelve";
}

Scroll back to the top of scrollable div

For me the scrollTop way did not work, but I found other:

element.style.display = 'none';
setTimeout(function() { element.style.display = 'block' }, 100);

Did not check the minimum time for reliable css rendering though, 100ms might be overkill.

Pass a password to ssh in pure bash

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

To use sshpass, you need to install it first. Then

sshpass -f <(printf '%s\n' your_password) ssh user@hostname

instead of using sshpass -p your_password. As mentioned by Charles Duffy in the comments, it is safer to supply the password from a file or from a variable instead of from command line.

BTW, a little explanation for the <(command) syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe

Printing without newline (print 'a',) prints a space, how to remove?

From PEP 3105: print As a Function in the What’s New in Python 2.6 document:

>>> from __future__ import print_function
>>> print('a', end='')

Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_function at the beginning). The print statement was removed and became the print() function by default in Python 3.0.

Requested bean is currently in creation: Is there an unresolvable circular reference?

In my case, I was defining a bean and autowiring it in the constructor of the same class file.

@SpringBootApplication
public class MyApplication {
    private MyBean myBean;

    public MyApplication(MyBean myBean) {
        this.myBean = myBean;
    }

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

My solution was to move the bean definition to another class file.

@Configuration
public CustomConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

Python - Join with newline

You have to print it:

In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'

In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

MVC Form not able to post List of objects

Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId, planCompareViewModel[1].PlanId to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model) use for loop and render names with indexes.

Excel Reference To Current Cell

Inside tables you can use [@] which (unfortunately) Excel automatically expands to Table1[@] but it does work. (I'm using Excel 2010)

For example when having two columns [Change] and [Balance], putting this in the [Balance] column:

=OFFSET([@], -1, 0) + [Change]

Note of course that this depends on the order of the rows (just like most any other solution), so it's a bit fragile.

React.js: onChange event for contentEditable

This is the is simplest solution that worked for me.

<div
  contentEditable='true'
  onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>

Insert HTML with React Variable Statements (JSX)

You can also include this HTML in ReactDOM like this:

var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);

ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));

Here are two links link and link2 from React documentation which could be helpful.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I had this error and found the reason for the error in my case. I'm still answering to this old post because it ranks pretty high on Google.

The variables of both of the column I wanted to link were integers but one of the ints had 'unsigned' checked on. Simply un-checking that fixed my error.

Remove non-utf8 characters from string

Slightly different to the question, but what I am doing is to use HtmlEncode(string),

pseudo code here

var encoded = HtmlEncode(string);
encoded = Regex.Replace(encoded, "&#\d+?;", "");
var result = HtmlDecode(encoded);

input and output

"Headlight\x007E Bracket, &#123; Cafe Racer<> Style, Stainless Steel ????"
"Headlight~ Bracket, &#123; Cafe Racer<> Style, Stainless Steel ????"

I know it's not perfect, but does the job for me.

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I also ran into that problem. My MVC4 App is running on a Windows Server 2012 R2 with IIS 8.5. None of these posted solutions worked for me...installing the missing frameworks through IIS Features could have solved it but the installation always failed.

I had to use the Web Platform Installer and installed the following packages:

enter image description here

How to set a background image in Xcode using swift?

I am beginner to iOS development so I would like to share whole info I got in this section.

First from image assets (images.xcassets) create image set .

According to Documentation here is all sizes need to create background image.

For iPhone 5:
   640 x 1136

   For iPhone 6:
   750 x 1334 (@2x) for portrait
   1334 x 750 (@2x) for landscape

   For iPhone 6 Plus:
   1242 x 2208 (@3x) for portrait
   2208 x 1242 (@3x) for landscape

   iPhone 4s (@2x)      
   640 x 960

   iPad and iPad mini (@2x) 
   1536 x 2048 (portrait)
   2048 x 1536 (landscape)

   iPad 2 and iPad mini (@1x)
   768 x 1024 (portrait)
   1024 x 768 (landscape)

   iPad Pro (@2x)
   2048 x 2732 (portrait)
   2732 x 2048 (landscape)

call the image background we can call image from image assets by using this method UIImage(named: "background") here is full code example

  override func viewDidLoad() {
          super.viewDidLoad()
             assignbackground()
            // Do any additional setup after loading the view.
        }

  func assignbackground(){
        let background = UIImage(named: "background")

        var imageView : UIImageView!
        imageView = UIImageView(frame: view.bounds)
        imageView.contentMode =  UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        imageView.image = background
        imageView.center = view.center
        view.addSubview(imageView)
        self.view.sendSubviewToBack(imageView)
    }

Redirect from an HTML page

You could use a META "redirect":

<meta http-equiv="refresh" content="0; url=http://new.example.com/address" />

or JavaScript redirect (note that not all users have JavaScript enabled so always prepare a backup solution for them)

<script language="javascript">
  window.location = "http://new.example.com/address";
</script>

But I'd rather recommend using mod_rewrite, if you have the option.

Configuration with name 'default' not found. Android Studio

I am facing same problem, I was fixed it by generating gradle project and then adding lib project to android studio

First, See build.gradle file is present in project root directory

if not then, Create gradle project,

  1. export your required lib project from eclipse then (File->Export->Android->generate Gradle build file
  2. Click on Next->Next->Select your lib project from project listing->Next->Next->Finish
  3. See build.gradle file present in your project root directory
  4. Move this project to Android Studio

.htaccess file to allow access to images folder to view pictures?

Give permission in .htaccess as follows:

<Directory "Your directory path/uploads/">
Allow from all
</Directory>

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

How to find numbers from a string?

This a variant of brettdj's & pstraton post.

This will return a true Value and not give you the #NUM! error. And \D is shorthand for anything but digits. The rest is much like the others only with this minor fix.

Function StripChar(Txt As String) As Variant
With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "\D"
    StripChar = Val(.Replace(Txt, " "))
End With
End Function

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

I had the same issue. In my home folder I've got a script named sqlplus.sh that takes care of this for me, containing:

ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export ORACLE_HOME
ORACLE_SID=XE
export ORACLE_SID
NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export NLS_LANG
PATH=$ORACLE_HOME/bin:$PATH
export PATH
sqlplus /nolog

How to assign a heredoc value to a variable in Bash?

There is still no solution that preserves newlines.

This is not true - you're probably just being misled by the behaviour of echo:

echo $VAR # strips newlines

echo "$VAR" # preserves newlines

updating nodejs on ubuntu 16.04

Using Node Version Manager (NVM):

Install it:

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

Test your installation:

close your current terminal, open a new terminal, and run:

command -v nvm

Use it to install as many versions as u like:

nvm install 8              # Install nodejs 8
nvm install --lts          # Install latest LTS (Long Term Support) version

List installed versions:

nvm ls

Use a specific version:

nvm use 8                  # Use this version on this shell

Set defaults:

nvm alias default 8        # Default to nodejs 8 on this shell
nvm alias default node     # always use latest available as default nodejs for all shells

How to convert a Collection to List?

Here is a sub-optimal solution as a one-liner:

Collections.list(Collections.enumeration(coll));

Full Screen Theme for AppCompat

You can follow below step:-

AndoridMenifest.xml

<activity
            android:name=".ui.FullImageActivity"
            android:label="@string/title_activity_main"
            android:screenOrientation="landscape"
            android:theme="@style/DialogTheme">
        </activity>

Style.xml

<style name="DialogTheme" parent="android:Theme.Dialog">

    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">fill_parent</item>

   <!-- No backgrounds, titles or window float -->
    <item name="android:windowNoTitle">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

FullImageActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    setContentView(R.layout.image_view);
     }

I hope it will help..Thanks!!

How to fix System.NullReferenceException: Object reference not set to an instance of an object

I was getting this same error, but for me this was due to a method in a base class (in Project A) having the output type changed from a non-void type to void. A child class existed in Project B (which I didn't want used and had marked obsolete) that I missed when performing this update and hence started throwing this error.

1>CSC : error CS8104: An error occurred while writing the output file: System.NullReferenceException: Object reference not set to an instance of an object.

Original Code:

[Obsolete("Calling this method will throw an error")]
public override CompletionStatus Run()
{
    throw new CustomException("Run process not supported.");
}

Revised Code:

[Obsolete("Calling this method will throw an error")]
public override void Run()
{
    throw new CustomException("Run process not supported.");
}

What is the difference between Hibernate and Spring Data JPA

Hibernate is a JPA implementation, while Spring Data JPA is a JPA data access abstraction. Spring Data JPA cannot work without a JPA provider.

Spring Data offers a solution to the DDD Repository pattern or the legacy GenericDao custom implementations. It can also generate JPA queries on your behalf through method name conventions.

With Spring Data, you may use Hibernate, EclipseLink, or any other JPA provider. A very interesting benefit of using Spring or Java EE is that you can control transaction boundaries declaratively using the @Transactional annotation.

Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC to deal with the JDBC verbosity.

Therefore, Hibernate and Spring Data are complementary rather than competitors.

Update just one gem with bundler

bundler update --source gem-name will update the revision hash in Gemfile.lock which you can compare with the last commit hash of that git branch (master by default).

GIT remote: [email protected]:organization/repo-name.git revision: c810f4a29547b60ca8106b7a6b9a9532c392c954

can be found at github.com/organization/repo-name/commits/c810f4a2 (I used shorthand 8 character commit hash for the url)

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

How do I prevent DIV tag starting a new line?

The div tag is a block element, causing that behavior.

You should use a span element instead, which is inline.

If you really want to use div, add style="display: inline". (You can also put that in a CSS rule)

How to unescape a Java string literal in Java?

Java 13 added a method which does this: String#translateEscapes.

It was a preview feature in Java 13 and 14, but was promoted to a full feature in Java 15.

Get random sample from list while maintaining ordering of items?

Apparently random.sample was introduced in python 2.3

so for version under that, we can use shuffle (example for 4 items):

myRange =  range(0,len(mylist)) 
shuffle(myRange)
coupons = [ bestCoupons[i] for i in sorted(myRange[:4]) ]

How to plot ROC curve in Python

There is a library called metriculous that will do that for you:

$ pip install metriculous

Let's first mock some data, this would usually come from the test dataset and the model(s):

import numpy as np

def normalize(array2d: np.ndarray) -> np.ndarray:
    return array2d / array2d.sum(axis=1, keepdims=True)

class_names = ["Cat", "Dog", "Pig"]
num_classes = len(class_names)
num_samples = 500

# Mock ground truth
ground_truth = np.random.choice(range(num_classes), size=num_samples, p=[0.5, 0.4, 0.1])

# Mock model predictions
perfect_model = np.eye(num_classes)[ground_truth]
noisy_model = normalize(
    perfect_model + 2 * np.random.random((num_samples, num_classes))
)
random_model = normalize(np.random.random((num_samples, num_classes)))

Now we can use metriculous to generate a table with various metrics and diagrams, including ROC curves:

import metriculous

metriculous.compare_classifiers(
    ground_truth=ground_truth,
    model_predictions=[perfect_model, noisy_model, random_model],
    model_names=["Perfect Model", "Noisy Model", "Random Model"],
    class_names=class_names,
    one_vs_all_figures=True, # This line is important to include ROC curves in the output
).save_html("model_comparison.html").display()

The ROC curves in the output: metriculous ROC curves

The plots are zoomable and draggable, and you get further details when hovering with your mouse over the plot:

metriculous ROC curve

How to hide command output in Bash

>/dev/null 2>&1 will mute both stdout and stderr

yum install nano >/dev/null 2>&1

Cannot get OpenCV to compile because of undefined references?

For me, this type of error:

mingw-w64-x86_64/lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld: mingw-w64-x86_64/x86_64-w64-mingw32/lib/libTransform360.a(VideoFrameTransform.cpp.obj):VideoFrameTransform.cpp:(.text+0xc7c):
undefined reference to `cv::Mat::Mat(cv::Mat const&, cv::Rect_<int> const&)'

meant load order, I had to do -lTransform360 -lopencv_dnn345 -lopencv... just like that, that order. And putting them right next to each other helped too, don't put -lTransform360 all the way at the beginning...or you'll get, for some freaky reason:

undefined reference to `VideoFrameTransform_new'
undefined reference to `VideoFrameTransform_generateMapForPlane'

...

How to pass multiple parameters to a get method in ASP.NET Core

Why not using just one controller action?

public string Get(int? id, string firstName, string lastName, string address)
{
   if (id.HasValue)
      GetById(id);
   else if (string.IsNullOrEmpty(address))
      GetByName(firstName, lastName);
   else
      GetByNameAddress(firstName, lastName, address);
}

Another option is to use attribute routing, but then you'd need to have a different URL format:

//api/person/byId?id=1
[HttpGet("byId")] 
public string Get(int id)
{
}

//api/person/byName?firstName=a&lastName=b
[HttpGet("byName")]
public string Get(string firstName, string lastName, string address)
{
}

Rendering HTML elements to <canvas>

Here is code to render arbitrary HTML into a canvas:

function render_html_to_canvas(html, ctx, x, y, width, height) {
    var xml = html_to_xml(html);
    xml = xml.replace(/\#/g, '%23');
    var data = "data:image/svg+xml;charset=utf-8,"+'<svg xmlns="http://www.w3.org/2000/svg" width="'+width+'" height="'+height+'">' +
                        '<foreignObject width="100%" height="100%">' +
                        xml+
                        '</foreignObject>' +
                        '</svg>';

    var img = new Image();
    img.onload = function () {
        ctx.drawImage(img, x, y);
    }
    img.src = data;
}

function html_to_xml(html) {
    var doc = document.implementation.createHTMLDocument('');
    doc.write(html);

    // You must manually set the xmlns if you intend to immediately serialize     
    // the HTML document to a string as opposed to appending it to a
    // <foreignObject> in the DOM
    doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);

    // Get well-formed markup
    html = (new XMLSerializer).serializeToString(doc.body);
    return html;
}

example:

_x000D_
_x000D_
const ctx = document.querySelector('canvas').getContext('2d');
const html = `
<p>this
<p>is <span style="color:red; font-weight: bold;">not</span>
<p><i>xml</i>!
<p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABWElEQVQ4jZ2Tu07DQBBFz9jjvEAQqAlQ0CHxERQ0/AItBV9Ew8dQUNBQIho6qCFE4Nhex4u85OHdWAKxzfWsx0d3HpazdGITA4kROjl0ckFrnYJmQlJrKsQZxFOIMyEqIMpADGhSZpikB1hAGsovdxABGuepC/4L0U7xRTG/riG3J8fuvdifPKnmasXp5c2TB1HNPl24gNTnpeqsgmj1eFgayoHvRDWbLBOKJbn9WLGYflCCpmM/2a4Au6/PTjdH+z9lCJQ9vyeq0w/ve2kA3vaOnI6k4Pz+0Y24yP3Gapy+Bw6qdfsCRZfWSWgclCCVXTZu5LZFXKJJ2sepW2KYNCENB3U5pw93zLoDjNK6E7rTFcgbkGYJtiLckxCiw4W1OURsxUE5BokQiQj3JIToVtKwlhsurq+YDYbMBjuU/W3KtT3xIbrpAD7E60lwQohuaMtP8ldI0uMbGfC1r1zyWPUAAAAASUVORK5CYII=">`;
render_html_to_canvas(html, ctx, 0, 0, 300, 150);


function render_html_to_canvas(html, ctx, x, y, width, height) {
  var data = "data:image/svg+xml;charset=utf-8," + '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' +
    '<foreignObject width="100%" height="100%">' +
    html_to_xml(html) +
    '</foreignObject>' +
    '</svg>';

  var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, x, y);
  }
  img.src = data;
}

function html_to_xml(html) {
  var doc = document.implementation.createHTMLDocument('');
  doc.write(html);

  // You must manually set the xmlns if you intend to immediately serialize     
  // the HTML document to a string as opposed to appending it to a
  // <foreignObject> in the DOM
  doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);

  // Get well-formed markup
  html = (new XMLSerializer).serializeToString(doc.body);
  return html;
}
_x000D_
<canvas></canvas>
_x000D_
_x000D_
_x000D_

Node.js project naming conventions for files & folders

According to me: For files, use lower camel case if module.exports is an object, I mean a singleton module. This is also applicable to JSON files as they are also in a way single ton. Use upper camel case if module.exports returns a constructor function where it acts like a class.

For folders use short names. If there is need to have multiple words, let it be completely lower case separated by "-" so that it works across all platforms consistently.

Losing Session State

Had a problem on IIS 8 when retrieving Content via Ajax. The issue was that MaximumWorkerProcesses was set to 2 and Javascript opened 17 concurrent requests. That was more than the AppPool could handle and a new pool (without auth-data) was opened.

Solution was to Change MaximumWorkerProcesses to 0 in IIS -> Server -> Application Pools -> [myPool] -> Advanced Settings -> Process Model -> MaximumWorkerProcesses.

Android Fragment handle back button press

if you overide the onKey method for the fragment view you're gonna need :

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i(tag, "keyCode: " + keyCode);
                if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                    Log.i(tag, "onKey Back listener is working!!!");
                    getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    return true;
                } 
                return false;
            }
        });

Installing tkinter on ubuntu 14.04

Install the package python-tk like

sudo apt-get install python-tk

That is described (with apt-cache search python-tk as)

Tkinter - Writing Tk applications with Python

add created_at and updated_at fields to mongoose schemas

we may can achieve this by using schema plugin also.

In helpers/schemaPlugin.js file

module.exports = function(schema) {

  var updateDate = function(next){
    var self = this;
    self.updated_at = new Date();
    if ( !self.created_at ) {
      self.created_at = now;
    }
    next()
  };
  // update date for bellow 4 methods
  schema.pre('save', updateDate)
    .pre('update', updateDate)
    .pre('findOneAndUpdate', updateDate)
    .pre('findByIdAndUpdate', updateDate);
};

and in models/ItemSchema.js file:

var mongoose = require('mongoose'),
  Schema   = mongoose.Schema,
  SchemaPlugin = require('../helpers/schemaPlugin');

var ItemSchema = new Schema({
  name    : { type: String, required: true, trim: true },
  created_at    : { type: Date },
  updated_at    : { type: Date }
});
ItemSchema.plugin(SchemaPlugin);
module.exports = mongoose.model('Item', ItemSchema);

How to output (to a log) a multi-level array in a format that is human-readable?

This will help you

echo '<pre>';

$output = print_r($array,1);

echo '</pre>';

EDIT

using echo '<pre>'; is useless, but var_export($var); will do the thing which you are expecting.

How can I disable a button in a jQuery dialog from a function?

From a usability perspective, it's usually better to leave the button enabled but show an error message if someone tries to submit an incomplete form. It drives me nuts when the button I want to click is disabled and there is no clue to why.

No module named 'pymysql'

sudo apt-get install python3-pymysql

This command also works for me to install the package required for Flask app to tun on ubuntu 16x with WISG module on APACHE2 server.

BY default on WSGI uses python 3 installation of UBUNTU.

Anaconda custom installation won't work.

Difference between "while" loop and "do while" loop

While Loop:

while(test-condition)
{
      statements;
      increment/decrement;
}
  1. Lower Execution Time and Speed
  2. Entry Conditioned Loop
  3. No fixed number of iterations

Do While Loop:

do
{
      statements;
      increment/decrement;
}while(test-condition);
  1. Higher Execution Time and Speed
  2. Exit Conditioned Loop
  3. Minimum one number of iteration

Find out more on this topic here: Difference Between While and Do While Loop

This is valid for C programming, Java programming and other languages as well because the concepts remain the same, only the syntax changes.

Also, another small but a differentiating factor to note is that the do while loop consists of a semicolon at the end of the while condition.

Getting URL hash location, and using it in jQuery

For those who are looking for pure javascript solution

 document.getElementById(location.hash.substring(1)).style.display = 'block'

Hope this saves you some time.

JavaScript require() on client side

If you want to have Node.js style require you can use something like this:

var require = (function () {
    var cache = {};
    function loadScript(url) {
        var xhr = new XMLHttpRequest(),
            fnBody;
        xhr.open('get', url, false);
        xhr.send();
        if (xhr.status === 200 && xhr.getResponseHeader('Content-Type') === 'application/x-javascript') {
            fnBody = 'var exports = {};\n' + xhr.responseText + '\nreturn exports;';
            cache[url] = (new Function(fnBody)).call({});
        }
    }
    function resolve(module) {
        //TODO resolve urls
        return module;
    }
    function require(module) {
        var url = resolve(module);
        if (!Object.prototype.hasOwnProperty.call(cache, url)) {
            loadScript(url);
        }
        return cache[url];
    }
    require.cache = cache;
    require.resolve = resolve;
    return require;
}());

Beware: this code works but is incomplete (especially url resolving) and does not implement all Node.js features (I just put this together last night). YOU SHOULD NOT USE THIS CODE in real apps but it gives you a starting point. I tested it with this simple module and it works:

function hello() {
    console.log('Hello world!');
}

exports.hello = hello;

When should I write the keyword 'inline' for a function/method?

1) Nowadays, pretty much never. If it's a good idea to inline a function, the compiler will do it without your help.

2) Always. See #1.

(Edited to reflect that you broke your question into two questions...)

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

We are doing the same thing. To support only TLS 1.2 and no SSL protocols, you can do this:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

SecurityProtocolType.Tls is only TLS 1.0, not all TLS versions.

As a side: If you want to check that your site does not allow SSL connections, you can do so here (I don't think this will be affected by the above setting, we had to edit the registry to force IIS to use TLS for incoming connections): https://www.ssllabs.com/ssltest/index.html

To disable SSL 2.0 and 3.0 in IIS, see this page: https://www.sslshopper.com/article-how-to-disable-ssl-2.0-in-iis-7.html

Open directory using C

You should really post your code(a), but here goes. Start with something like:

    #include <stdio.h>
    #include <dirent.h>

    int main (int argc, char *argv[]) {
        struct dirent *pDirent;
        DIR *pDir;

        // Ensure correct argument count.

        if (argc != 2) {
            printf ("Usage: testprog <dirname>\n");
            return 1;
        }

        // Ensure we can open directory.

        pDir = opendir (argv[1]);
        if (pDir == NULL) {
            printf ("Cannot open directory '%s'\n", argv[1]);
            return 1;
        }

        // Process each entry.

        while ((pDirent = readdir(pDir)) != NULL) {
            printf ("[%s]\n", pDirent->d_name);
        }

        // Close directory and exit.

        closedir (pDir);
        return 0;
    }

You need to check in your case that args[1] is both set and refers to an actual directory. A sample run, with tmp is a subdirectory off my current directory but you can use any valid directory, gives me: testprog tmp

[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]

Note also that you have to pass a directory in, not a file. When I execute:

testprog tmp/file1.txt

I get:

Cannot open directory 'tmp/file1.txt'

That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1])) if the initial diropen fails).


(a) This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.

How to have css3 animation to loop forever

add this styles

animation-iteration-count:infinite;

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I had the same problem. mysql -u root -p worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password, if you did not set one. More info here.

Deep cloning objects

In general, you implement the ICloneable interface and implement Clone yourself. C# objects have a built-in MemberwiseClone method that performs a shallow copy that can help you out for all the primitives.

For a deep copy, there is no way it can know how to automatically do it.

Invoking a PHP script from a MySQL trigger

Run away from store procedures as much as possible. They are pretty hard to maintain and are VERY OLD STUFF ;)

Changing user agent on urllib2.urlopen

All these should work in theory, but (with Python 2.7.2 on Windows at least) any time you send a custom User-agent header, urllib2 doesn't send that header. If you don't try to send a User-agent header, it sends the default Python / urllib2

None of these methods seem to work for adding User-agent but they work for other headers:

opener = urllib2.build_opener(proxy)
opener.addheaders = {'User-agent':'Custom user agent'}
urllib2.install_opener(opener)

request = urllib2.Request(url, headers={'User-agent':'Custom user agent'})

request.headers['User-agent'] = 'Custom user agent'

request.add_header('User-agent', 'Custom user agent')

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

How to break a while loop from an if condition inside the while loop?

while(something.hasnext())
do something...
   if(contains something to process){
      do something...
      break;
   }
}

Just use the break statement;

For eg:this just prints "Breaking..."

while (true) {
     if (true) {
         System.out.println("Breaking...");
         break;
     }
     System.out.println("Did this print?");
}

Install Application programmatically on Android

Try this - Write on Manifest:

uses-permission android:name="android.permission.INSTALL_PACKAGES"
        tools:ignore="ProtectedPermissions"

Write the Code:

File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/Download";// + "app-release.apk";
File file = new File(fileStr, "app-release.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");

startActivity(promptInstall);

How to use jQuery to call an ASP.NET web service?

I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...

There is a line of code to uncommment in order to have it return JSON.

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

If you are using Visual Studio 2017 Community, the location is:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\ReferenceAssemblies\v2.0

The DLL you want is there: Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

Apparently it is located in the C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\ directory for Visual Studio 2010 Professional version, but take note that the 10.0 will change to correspond with the release year, i.e. VS 2013 was version 12.0, VS 2015 was version 14.0, VS 2017 is 15.0. (VS Express is not supported and would require installing the NUnit NuGet package, through the NuGet Package Manager, instead.)

You go to References, right-click, select Add Reference, Browse. Navigate to the path, then double-click the file.

Then, you need a using statement at the top of your Unit Test class:

using Microsoft.VisualStudio.TestTools.UnitTesting;

Can an ASP.NET MVC controller return an Image?

Why not go simple and use the tilde ~ operator?

public FileResult TopBanner() {
  return File("~/Content/images/topbanner.png", "image/png");
}

How to call a function within class?

Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

How to get to Model or Viewbag Variables in a Script Tag

What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.

var val = '@ViewBag.ForSection';

If it's an integer you need to parse it as one i.e.

var val = parseInt(@ViewBag.ForSection);

How to loop through an associative array and get the key?

Nobody answered with regular for loop? Sometimes I find it more readable and prefer for over foreach
So here it is:

$array = array('key1' => 'value1', 'key2' => 'value2'); 

$keys = array_keys($array);

for($i=0; $i < count($keys); ++$i) {
    echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}

/*
  prints:
  key1 value1
  key2 value2
*/

Can't push to remote branch, cannot be resolved to branch

it seems that you try to rename your master branch to Main. by using this command git branch -M Main where you were on master branch. execute this git command, il will work :

git push --all -u

after this you can run git branch to see your branches then you can delete the master branch like this :

git branch -D master

Why do we use __init__ in Python classes?

Classes are objects with attributes (state, characteristic) and methods (functions, capacities) that are specific for that object (like the white color and fly powers, respectively, for a duck).

When you create an instance of a class, you can give it some initial personality (state or character like the name and the color of her dress for a newborn). You do this with __init__.

Basically __init__ sets the instance characteristics automatically when you call instance = MyClass(some_individual_traits).

"Gradle Version 2.10 is required." Error

You need to change File > Settings > Builds,Execution,Deployment > Build Tools > Gradle >Gradle home path

On Mac OS, change the path in Android Studio > Preferences > Builds,Execution,Deployment > Build Tools > Gradle >Gradle home

Or set Use default gradle wrapper and edit Project\gradle\wrapper\gradle-wrapper.properties files field distributionUrl like this

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

How to iterate object keys using *ngFor

I know this question is already answered but I have one solution for this same.

You can also use Object.keys() inside of *ngFor to get required result.

I have created a demo on stackblitz. I hope this will help/guide to you/others.

CODE SNIPPET

HTML Code

<div *ngFor="let key of Object.keys(myObj)">
  <p>Key-> {{key}} and value is -> {{myObj[key]}}</p>
</div>

.ts file code

Object = Object;

myObj = {
    "id": 834,
    "first_name": "GS",
    "last_name": "Shahid",
    "phone": "1234567890",
    "role": null,
    "email": "[email protected]",
    "picture": {
        "url": null,
        "thumb": {
            "url": null
        }
    },
    "address": "XYZ Colony",
    "city_id": 2,
    "provider": "email",
    "uid": "[email protected]"
}

Read an Excel file directly from a R script

EDIT 2015-October: As others have commented here the openxlsx and readxl packages are by far faster than the xlsx package and actually manage to open larger Excel files (>1500 rows & > 120 columns). @MichaelChirico demonstrates that readxl is better when speed is preferred and openxlsx replaces the functionality provided by the xlsx package. If you are looking for a package to read, write, and modify Excel files in 2015, pick the openxlsx instead of xlsx.

Pre-2015: I have used xlsxpackage. It changed my workflow with Excel and R. No more annoying pop-ups asking, if I am sure that I want to save my Excel sheet in .txt format. The package also writes Excel files.

However, I find read.xlsx function slow, when opening large Excel files. read.xlsx2 function is considerably faster, but does not quess the vector class of data.frame columns. You have to use colClasses command to specify desired column classes, if you use read.xlsx2 function. Here is a practical example:

read.xlsx("filename.xlsx", 1) reads your file and makes the data.frame column classes nearly useful, but is very slow for large data sets. Works also for .xls files.

read.xlsx2("filename.xlsx", 1) is faster, but you will have to define column classes manually. A shortcut is to run the command twice (see the example below). character specification converts your columns to factors. Use Dateand POSIXct options for time.

coln <- function(x){y <- rbind(seq(1,ncol(x))); colnames(y) <- colnames(x)
rownames(y) <- "col.number"; return(y)} # A function to see column numbers

data <- read.xlsx2("filename.xlsx", 1) # Open the file 

coln(data)    # Check the column numbers you want to have as factors

x <- 3 # Say you want columns 1-3 as factors, the rest numeric

data <- read.xlsx2("filename.xlsx", 1, colClasses= c(rep("character", x),
rep("numeric", ncol(data)-x+1)))

jQuery function to open link in new window

Try adding return false; in your click callback like this -

$(document).ready(function() {
  $('.popup').click(function(event) {
      window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
      return false;
  });
});

Scala check if element is present in a list

And if you didn't want to use strict equality, you could use exists:


myFunction(strings.exists { x => customPredicate(x) })

Android WebView, how to handle redirects in app instead of opening a browser

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    super.onPageStarted(view, url, favicon);
    if (url.equals("your url")) {
        
            Intent intent = new Intent(view.getContext(), TransferAllDoneActivity.class);
            startActivity(intent);
        
    }
}

vertical-align image in div

you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-

inline-elements :- <img style="vertical-align:middle" ...>
                   <span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>  

block-elements :- <td style="vertical-align:middle"> ... </td>
                  <div style="display:table-cell; vertical-align:middle"> ... </div>

see the demo:- http://jsfiddle.net/Ewfkk/2/

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

How can I check if a user is logged-in in php?

You may do a session and place it:

// Start session
session_start();

// Check do the person logged in
if($_SESSION['username']==NULL){
    // Haven't log in
    echo "You haven't log in";
}else{
    // Logged in
    echo "Successfully logged in!";
}

Note: you must make a form which contain $_SESSION['username'] = $login_input_username;

How to update a value in a json file and save it through node.js

addition to the previous answer add file path directory for the write operation

 fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {}

How to save username and password with Mercurial?

No one mentioned the keyring extension. It will save the username and password into the system keyring, which is far more secure than storing your passwords in a static file as mentioned above. Perform the steps below and you should be good to go. I had this up and running on Ubuntu in about 2 minutes.

>> sudo apt-get install python-pip
>> sudo pip install keyring
>> sudo pip install mercurial_keyring

**Edit your .hgrc file to include the extension**
[extensions]
mercurial_keyring = 

https://www.mercurial-scm.org/wiki/KeyringExtension

How to get the index of an element in an IEnumerable?

I'd question the wisdom, but perhaps:

source.TakeWhile(x => x != value).Count();

(using EqualityComparer<T>.Default to emulate != if needed) - but you need to watch to return -1 if not found... so perhaps just do it the long way

public static int IndexOf<T>(this IEnumerable<T> source, T value)
{
    int index = 0;
    var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
    foreach (T item in source)
    {
        if (comparer.Equals(item, value)) return index;
        index++;
    }
    return -1;
}

How do I fix MSB3073 error in my post-build event?

For what it's worth, the problem in my case was caused by using '/' as the directory separator in a copy command. Must use backslashes.

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

Is SQL syntax case sensitive?

In Sql Server it is an option. Turning it on sucks.

I'm not sure about MySql.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

You can do it like this

new DirectoryInfo(path).GetFiles().Where(Current => Regex.IsMatch(Current.Extension, "\\.(aspx|ascx)", RegexOptions.IgnoreCase)

How to pass arguments and redirect stdin from a file to program run in gdb?

Start GDB on your project.

  1. Go to project directory, where you've already compiled the project executable. Issue the command gdb and the name of the executable as below:

    gdb projectExecutablename

This starts up gdb, prints the following: GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ................................................. Type "apropos word" to search for commands related to "word"... Reading symbols from projectExecutablename...done. (gdb)

  1. Before you start your program running, you want to set up your breakpoints. The break command allows you to do so. To set a breakpoint at the beginning of the function named main:

    (gdb) b main

  2. Once you've have the (gdb) prompt, the run command starts the executable running. If the program you are debugging requires any command-line arguments, you specify them to the run command. If you wanted to run my program on the "xfiles" file (which is in a folder "mulder" in the project directory), you'd do the following:

    (gdb) r mulder/xfiles

Hope this helps.

Disclaimer: This solution is not mine, it is adapted from https://web.stanford.edu/class/cs107/guide_gdb.html This short guide to gdb was, most probably, developed at Stanford University.

Displaying better error message than "No JSON object could be decoded"

I had a similar problem and it was due to singlequotes. The JSON standard(http://json.org) talks only about using double quotes so it must be that the python json library supports only double quotes.

How to center a table of the screen (vertically and horizontally)

This guy had the magic wand we were looking for, guys.

To quote his answer:

just add "position:fixed" and it will keep it in view even if you scroll down. see it at http://jsfiddle.net/XEUbc/1/

#mydiv {
    position:fixed;
    top: 50%;
    left: 50%;
    width:30em;
    height:18em;
    margin-top: -9em; /*set to a negative number 1/2 of your height*/
    margin-left: -15em; /*set to a negative number 1/2 of your width*/
    border: 1px solid #ccc;
    background-color: #f3f3f3;
}

Fatal error: Call to undefined function curl_init()

This is from the official website. php.net

After installation of PHP.

Windows

Move to Windows\system32 folder: libssh2.dll, php_curl.dll, ssleay32.dll, libeay32.dll

Linux

Move to Apache24\bin folder libssh2.dll

Then uncomment extension=php_curl.dll in php.ini

How to read the value of a private field from a different class in Java?

Just an additional note about reflection: I have observed in some special cases, when several classes with the same name exist in different packages, that reflection as used in the top answer may fail to pick the correct class from the object. So if you know what is the package.class of the object, then it's better to access its private field values as follows:

org.deeplearning4j.nn.layers.BaseOutputLayer ll = (org.deeplearning4j.nn.layers.BaseOutputLayer) model.getLayer(0);
Field f = Class.forName("org.deeplearning4j.nn.layers.BaseOutputLayer").getDeclaredField("solver");
f.setAccessible(true);
Solver s = (Solver) f.get(ll);

(This is the example class that was not working for me)

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

Restart IntelliJ and reimport the Project and import it as maven. It should work then. The error occurs because IntelliJ keeps track of module through .iml files so any changes in these files can cause this error. Reimporting the project regenerates the .iml file so generally, it solves the error.

How do I disable a Pylint warning?

pylint --generate-rcfile shows it like this:

[MESSAGES CONTROL]

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time.
#enable=

# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
#disable=

So it looks like your ~/.pylintrc should have the disable= line/s in it inside a section [MESSAGES CONTROL].

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

What is the difference between MVC and MVVM?

Well, generally MVC is used in Web development and MVVM is most popular in WPF/Silverlight development. However, sometimes the web architecute might have a mix of MVC and MVVM.

For example: you might use knockout.js and in this case you will have MVVM on your client side. And your MVC's server side can also change. In the complex apps, nobody uses the pure Model. It might have a sense to use a ViewModel as a "Model" of MVC and your real Model basically will be a part of this VM. This gives you an extra abstraction layer.

Repeat rows of a data.frame

try using for example

N=2
rep(1:4, each = N) 

as an index

How to remove/ignore :hover css style on touch devices

This might not be a perfect solution yet (and it’s with jQuery) but maybe it’s a direction / concept to work on: what about doing it the other way round? Which means deactivating the :hover css states by default and activate them if a mousemove event is detected anywhere on the document. Of course this does not work if someone deactivated js. What else might speak against doing it this way round?

Maybe like this:

CSS:

/* will only work if html has class "mousedetected" */
html.mousedetected a:hover {
   color:blue;
   border-color:green;
}

jQuery:

/* adds "mousedetected" class to html element if mouse moves (which should never happen on touch-only devices shouldn’t it?) */
$("body").mousemove( function() {
    $("html").addClass("mousedetected");
});

If input field is empty, disable submit button

For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.

$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
    $('#new_post button').prop 'disabled', if @value == '' then true else false
    return

javascript popup alert on link click

You can use the onclick attribute, just return false if you don't want continue;

<script type="text/javascript">
function confirm_alert(node) {
    return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>

Put request with simple string as request body

This worked for me:

export function modalSave(name,id){
  console.log('modalChanges action ' + name+id);  

  return {
    type: 'EDIT',
    payload: new Promise((resolve, reject) => {
      const value = {
        Name: name,
        ID: id,
      } 

      axios({
        method: 'put',
        url: 'http://localhost:53203/api/values',
        data: value,
        config: { headers: {'Content-Type': 'multipart/form-data' }}
      })
       .then(function (response) {
         if (response.status === 200) {
           console.log("Update Success");
           resolve();
         }
       })
       .catch(function (response) {
         console.log(response);
         resolve();
       });
    })
  };
}

How to display list items on console window in C#

Console.WriteLine(string.Join<TYPE>("\n", someObjectList));

C# - Substring: index and length must refer to a location within the string

Here is another suggestion. If you can prepend http:// to your url string you can do this

  string path = "http://www.example.com/aaa/bbb.jpg";
  Uri uri = new Uri(path);            
  string expectedString = 
      uri.PathAndQuery.Remove(uri.PathAndQuery.LastIndexOf("."));

How to scroll UITableView to specific position

Use [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES]; Scrolls the receiver until a row identified by index path is at a particular location on the screen.

And

scrollToNearestSelectedRowAtScrollPosition:animated:

Scrolls the table view so that the selected row nearest to a specified position in the table view is at that position.

ASP.NET set hiddenfield a value in Javascript

asp:HiddenField as:

<asp:HiddenField runat="server" ID="hfProduct" ClientIDMode="Static" />

js code:

$("#hfProduct").val("test")

and the code behind:

hfProduct.Value.ToString();

How to change MySQL timezone in a database connection using Java?

JDBC uses a so-called "connection URL", so you can escape "+" by "%2B", that is

useTimezone=true&serverTimezone=GMT%2B8

Force sidebar height 100% using CSS (with a sticky bottom image)?

I realise this is an old post but I was trying to work something out for my site to have a sidebar. Would this work?

#sidebar-background
{
    position:fixed;
    width:250px;
    top:0;
    bottom:0;
    background-color:orange;
}

#content-background
{
    position:fixed;
    right:0;
    top:0;
    bottom:0;
    left:250px;
    background-color:pink;
}

#sidebar
{
    float:left;
    width:250px;
}

#content
{
    float:left;
    width:600px;
}

<div id="sidebar-background"></div>
<div id="content-background"></div>

<div id="sidebar">Sidebar stuff here</div>
<div id="content">Stuff in here</div>

Excel function to get first word from sentence in other cell

I found this on exceljet.net and works for me:

=LEFT(B4,FIND(" ",B4)-1)

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

What is the "double tilde" (~~) operator in JavaScript?

~(5.5)   // => -6
~(-6)    // => 5
~~5.5    // => 5  (same as Math.floor(5.5))
~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )

For more info, see:

How can I change image tintColor in iOS and WatchKit

For swift 3 purposes

theImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

difference between throw and throw new Exception()

The first preserves the original stacktrace:

try { ... }
catch
{
    // Do something.
    throw;
}

The second allows you to change the type of the exception and/or the message and other data:

try { ... } catch (Exception e)
{
    throw new BarException("Something broke!");
}

There's also a third way where you pass an inner exception:

try { ... }
catch (FooException e) {
    throw new BarException("foo", e);
} 

I'd recommend using:

  • the first if you want to do some cleanup in error situation without destroying information or adding information about the error.
  • the third if you want to add more information about the error.
  • the second if you want to hide information (from untrusted users).

How do I clear my Jenkins/Hudson build history?

This one is the best option available.

Jenkins.instance.getAllItems(AbstractProject.class).each {it -> Jenkins.instance.getItemByFullName(it.fullName).builds.findAll { it.number > 0 }.each { it.delete() } }

This code will delete all Jenkins Job build history.

Editing an item in a list<T>

  1. You can use the FindIndex() method to find the index of item.
  2. Create a new list item.
  3. Override indexed item with the new item.

List<Class1> list = new List<Class1>();

int index = list.FindIndex(item => item.Number == textBox6.Text);

Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";

list[index] = newItem;

Create a File object in memory from a string in Java

No; instances of class File represent a path in a filesystem. Therefore, you can use that function only with a file. But perhaps there is an overload that takes an InputStream instead?

How to set max and min value for Y axis

This is for Charts.js 2.0:

The reason some of these are not working is because you should declare your options when you create your chart like so:

$(function () {
    var ctxLine = document.getElementById("myLineChart");
    var myLineChart = new Chart(ctxLine, {
        type: 'line',
        data: dataLine,
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        min: 0,
                        beginAtZero: true
                    }
                }]
            }
        }

    });
})

Documentation for this is here: http://www.chartjs.org/docs/#scales

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

Here's the proper way to do things:

<?PHP
$sql = 'some query...';
$result = mysql_query($q);

if (! $result){
   throw new My_Db_Exception('Database error: ' . mysql_error());
}

while($row = mysql_fetch_assoc($result)){
  //handle rows.
}

Note the check on (! $result) -- if your $result is a boolean, it's certainly false, and it means there was a database error, meaning your query was probably bad.

Sorting Python list based on the length of the string

When you pass a lambda to sort, you need to return an integer, not a boolean. So your code should instead read as follows:

xs.sort(lambda x,y: cmp(len(x), len(y)))

Note that cmp is a builtin function such that cmp(x, y) returns -1 if x is less than y, 0 if x is equal to y, and 1 if x is greater than y.

Of course, you can instead use the key parameter:

xs.sort(key=lambda s: len(s))

This tells the sort method to order based on whatever the key function returns.

EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len directly as the key parameter to the function, thus eliminating the need for a lambda:

xs.sort(key=len)

And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort method, which creates a new list rather than sorting the existing one in-place:

print(sorted(xs, key=len))

Resize image in PHP

private function getTempImage($url, $tempName){
  $tempPath = 'tempFilePath' . $tempName . '.png';
  $source_image = imagecreatefrompng($url); // check type depending on your necessities.
  $source_imagex = imagesx($source_image);
  $source_imagey = imagesy($source_image);
  $dest_imagex = 861; // My default value
  $dest_imagey = 96;  // My default value

  $dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);

  imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);

  imagejpeg($dest_image, $tempPath, 100);

  return $tempPath;

}

This is an adapted solution based on this great explanation. This guy made a step by step explanation. Hope all enjoy it.

How do I access command line arguments in Python?

Python code:

import sys

# main
param_1= sys.argv[1] 
param_2= sys.argv[2] 
param_3= sys.argv[3]  
print 'Params=', param_1, param_2, param_3

Invocation:

$python myfile.py var1 var2 var3

Output:

Params= var1 var2 var3 

Display A Popup Only Once Per User

The code to show only one time the popup (Bootstrap Modal in the case) :

modal.js

 $(document).ready(function() {
     if (Cookies('pop') == null) {
         $('#ModalIdName').modal('show');
         Cookies('pop', '365');
     }
 });

Here is the full code snipet for Rails :

Add the script above to your js repo (in Rails : app/javascript/packs)

In Rails we have a specific packing way for script, so :

  1. Download the js-cookie plugin (needed to work with Javascript Cokkies) https://github.com/js-cookie/js-cookie (the name should be : 'js.cookie.js')

    /*!
     * JavaScript Cookie v2.2.0
     * https://github.com/js-cookie/js-cookie
     *
     * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
     * Released under the MIT license
     */
    ;(function (factory) {
      var registeredInModuleLoader = false;
      if (typeof define === 'function' && define.amd) {
        define(factory);
        registeredInModul
     ...
    
  2. Add //= require js.cookie to application.js

It will works perfectly for 365 days!