Programs & Examples On #Content model

Google Chromecast sender error if Chromecast extension is not installed or using incognito

Update: After several attempts, it looks like this may have been fixed in latest Chrome builds (per Paul Irish's comment below). That would suggest we will see this fixed in stable Chrome June-July 2016. Let's see ...

This is a known bug with the official Chromecast JavaScript library. Instead of failing silently, it dumps these error messages in all non-Chrome browsers as well as Chrome browsers where the Chromecast extension isn't present.

The Chromecast team have indicated they won't fix this bug.

If you are a developer shipping with this library, you can't do anything about it according to Chromecast team. You can only inform users to ignore the errors. (I believe Chromecast team is not entirely correct as the library could, at the least, avoid requesting the extension scipt if the browser is not Chrome. And I suspect it could be possible to suppress the error even if it is Chrome, but haven't tried anything.)

If you are a user annoyed by these console messages, you can switch to Chrome if not using it already. Within Chrome, either:

Update [Nov 13, 2014]: The problem has now been acknowledged by Google. A member of the Chromecast team seems to suggest the issue will be bypassed by a change the team is currently working on.

Update 2 [Feb 17, 2015]: The team claim there's nothing they can do to remove the error logs as it's a standard Chrome network error and they are still working on a long-term fix. Public comments on the bug tracker were closed with that update.

Update 3 [Dec 4, 2015]: This has finally been fixed! In the end, Chrome team simply added some code to block out this specific error. Hopefully some combination of devtools and extensions API will be improved in the future to make it possible to fix this kind of problem without patching the browser. Chrome Canary already has the patch, so it should roll out to all users around mid-January. Additionally, the team has confirmed the issue no longer affects other browsers as the SDK was updated to only activate if it's in Chrome.

Update 4 (April 30): Nope, not yet anyway. Thankfully Google's developer relations team are more aware than certain other stakeholders how badly this has affected developer experience. More whitelist updates have recently been made to clobber these log messages. Current status at top of the post.

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

How do I check if a column is empty or null in MySQL?

This statement is much cleaner and more readable for me:

select * from my_table where ISNULL(NULLIF(some_col, ''));

Binding Button click to a method

You have various possibilies. The most simple and the most ugly is:

XAML

<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/> 

Code Behind

private void Button_Clicked(object sender, RoutedEventArgs e) { 
    FrameworkElement fe=sender as FrameworkElement;
    ((YourClass)fe.DataContext).DoYourCommand();     
} 

Another solution (better) is to provide a ICommand-property on your YourClass. This command will have already a reference to your YourClass-object and therefore can execute an action on this class.

XAML

<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>

Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.

Cast a Double Variable to Decimal

Well this is an old question and I indeed made use of some of the answers shown here. Nevertheless, in my particular scenario it was possible that the double value that I wanted to convert to decimal was often bigger than decimal.MaxValue. So, instead of handling exceptions I wrote this extension method:

    public static decimal ToDecimal(this double @double) => 
        @double > (double) decimal.MaxValue ? decimal.MaxValue : (decimal) @double;

The above approach works if you do not want to bother handling overflow exceptions and if such a thing happen you want just to keep the max possible value(my case), but I am aware that for many other scenarios this would not be the expected behavior and may be the exception handling will be needed.

how to save and read array of array in NSUserdefaults in swift?

Swift 4.0

Store:

let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]    

 //store in user default
 UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")

Fetch:

if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
        print(arr)
    }

When to use LinkedList over ArrayList in Java?

Yeah, I know, this is an ancient question, but I'll throw in my two cents:

LinkedList is almost always the wrong choice, performance-wise. There are some very specific algorithms where a LinkedList is called for, but those are very, very rare and the algorithm will usually specifically depend on LinkedList's ability to insert and delete elements in the middle of the list relatively quickly, once you've navigated there with a ListIterator.

There is one common use case in which LinkedList outperforms ArrayList: that of a queue. However, if your goal is performance, instead of LinkedList you should also consider using an ArrayBlockingQueue (if you can determine an upper bound on your queue size ahead of time, and can afford to allocate all the memory up front), or this CircularArrayList implementation. (Yes, it's from 2001, so you'll need to generify it, but I got comparable performance ratios to what's quoted in the article just now in a recent JVM)

SQL Server : trigger how to read value for Insert, Update, Delete

Here is the syntax to create a trigger:

CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
        [ WITH APPEND ]
        [ NOT FOR REPLICATION ]
        AS
        [ { IF UPDATE ( column )
            [ { AND | OR } UPDATE ( column ) ]
                [ ...n ]
        | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
                { comparison_operator } column_bitmask [ ...n ]
        } ]
        sql_statement [ ...n ]
    }
} 

If you want to use On Update you only can do it with the IF UPDATE ( column ) section. That's not possible to do what you are asking.

adding text to an existing text element in javascript via DOM

   <!DOCTYPE html>
   <html>
   <head>
   <script   src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
   $("#btn1").click(function(){
    $("p").append(" <b>Appended text</b>.");
   });

  });
 </script>
  </head>
 <body>

 <p>This is a paragraph.</p>
  <p>This is another paragraph.</p>



 <button id="btn1">Append text</button>


</body>
</html>

Background Image for Select (dropdown) does not work in Chrome

Generally, it's considered a bad practice to style standard form controls because the output looks so different on each browser. See: http://www.456bereastreet.com/lab/styling-form-controls-revisited/select-single/ for some rendered examples.

That being said, I've had some luck making the background color an RGBA value:

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        background: #d00;
      }
      select {
        background: rgba(255,255,255,0.1) url('http://www.google.com/images/srpr/nav_logo6g.png') repeat-x 0 0; 
        padding:4px; 
        line-height: 21px;
        border: 1px solid #fff;
      }
    </style>
  </head>
  <body>
    <select>
      <option>Foo</option>
      <option>Bar</option>      
      <option>Something longer</option>     
  </body>
</html>

Google Chrome still renders a gradient on top of the background image in the color that you pass to rgba(r,g,b,0.1) but choosing a color that compliments your image and making the alpha 0.1 reduces the effect of this.

how to change default python version?

Check the execution path of python3 where it has libraries

$ which python3
/usr/local/bin/python3  some OS might have /usr/bin/python3

open bash_profile file and add an alias

vi ~/.bash_profile  
alias python='/usr/local/bin/python3' or alias python='/usr/bin/python3'

Reload bash_profile to take effect of modifications

source ~/.bash_profile

Run python command and check whether it's getting loading with python3

$ python --version
Python 3.6.5

Run a command shell in jenkins

For Windows slave, please use Execute Windows batch command.
For Unix-like slave like linux or Mac, Execute shell is the option.

Execute Windows Command shell

HTML Script tag: type or language (or omit both)?

The language attribute has been deprecated for a long time, and should not be used.

When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.

For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>

You will be informed of the following error:

Line 4, Column 41: required attribute "type" not specified

So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.

How do you synchronise projects to GitHub with Android Studio?

First time I have added a video link for solving your problem but I learned it was a bad idea. This time I'll explain it briefly.

Android studio is compatible with github but you need adjust something:

  1. Setup Android Studio
  2. Setup the Github plugins in the Android Studio settings

    • Android Studio settings >> Plugins page enter image description here
  3. Download the git version control system from this link and setup https://git-scm.com/

  4. After the installation, open Android Studio settings page and select the git.exe
    • settings >> version control >> git
    • Usually the path to git.exe is program files >> git >> bin >> git.exe
  5. Go to Settings >> Version control >> Github you will see login and password for your Github account. Apply the settings.
  6. For updating the project, go in Android Studio top line click VCS >> enable version control integration >> git
  7. One more time VCS >> import into version control >> share project on Github and enter your master password.

Now you can use VCS update buttons for updating your project to Github

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How to test web service using command line curl

Answering my own question.

curl -X GET --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X DELETE --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
     -d 'param2_name=param2_value' https://www.example.com/mobile/resource

POSTing a file and additional parameter

curl -X POST -F 'param_name=@/filepath/filename' \
     -F 'extra_param_name=extra_param_value' --basic --user username:password \
     https://www.example.com/mobile/resource

'printf' vs. 'cout' in C++

Two points not otherwise mentioned here that I find significant:

1) cout carries a lot of baggage if you're not already using the STL. It adds over twice as much code to your object file as printf. This is also true for string, and this is the major reason I tend to use my own string library.

2) cout uses overloaded << operators, which I find unfortunate. This can add confusion if you're also using the << operator for its intended purpose (shift left). I personally don't like to overload operators for purposes tangential to their intended use.

Bottom line: I'll use cout (and string) if I'm already using the STL. Otherwise, I tend to avoid it.

Resetting Select2 value in dropdown with reset button

According to the latest version (select2 3.4.5) documented here, it would be as simple as:

 $("#my_select").select2("val", "");

How to decorate a class?

No one has explained that you can dynamically define classes. So you can have a decorator that defines (and returns) a subclass:

def addId(cls):

    class AddId(cls):

        def __init__(self, id, *args, **kargs):
            super(AddId, self).__init__(*args, **kargs)
            self.__id = id

        def getId(self):
            return self.__id

    return AddId

Which can be used in Python 2 (the comment from Blckknght which explains why you should continue to do this in 2.6+) like this:

class Foo:
    pass

FooId = addId(Foo)

And in Python 3 like this (but be careful to use super() in your classes):

@addId
class Foo:
    pass

So you can have your cake and eat it - inheritance and decorators!

What does the term "Tuple" Mean in Relational Databases?

As I understand it a table has a set K of keys and a typing function T with domain K. A row, or "tuple", of the table is a function r with domain K such that r(k) is an element of T(k) for each key k. So the terminology is misleading in that a "tuple" is really more like an associative array.

How to get response status code from jQuery.ajax?

jqxhr is a json object:

complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

see: jQuery ajax

so you would do:

jqxhr.status to get the status

How to install popper.js with Bootstrap 4?

npm install bootstrap jquery --save

You don't have to install popper.js with npm as it comes with npm Bootstrap in bootstrap.bundle.js.

Bundled JS files (bootstrap.bundle.js and minified bootstrap.bundle.min.js) include Popper, but not jQuery.

Source to Verify: Link

Now you only have to do this in your HTML file:

<script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Finding out the name of the original repository you cloned from in Git

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

It was tested with three different URL styles:

echo "Fetch URL: http://user@pass:gitservice.org:20080/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: Fetch URL: [email protected]:home1-oss/oss-build.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: https://github.com/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

How to put Google Maps V2 on a Fragment using ViewPager

The following approach works for me.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * A fragment that launches other parts of the demo application.
 */
public class MapFragment extends Fragment {

MapView mMapView;
private GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // inflat and return the layout
    View v = inflater.inflate(R.layout.fragment_location_info, container,
            false);
    mMapView = (MapView) v.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume();// needed to get the map to display immediately

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    googleMap = mMapView.getMap();
    // latitude and longitude
    double latitude = 17.385044;
    double longitude = 78.486671;

    // create marker
    MarkerOptions marker = new MarkerOptions().position(
            new LatLng(latitude, longitude)).title("Hello Maps");

    // Changing marker icon
    marker.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

    // adding marker
    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
    googleMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));

    // Perform any camera updates here
    return v;
}

@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}

@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}
}

fragment_location_info.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

What are queues in jQuery?

Function makeRed and makeBlack use queue and dequeue to execute each other. The effect is that, the '#wow' element blinks continuously.

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
          $('#wow').click(function(){
            $(this).delay(200).queue(makeRed);
            });
          });

      function makeRed(){
        $('#wow').css('color', 'red');
        $('#wow').delay(200).queue(makeBlack);
        $('#wow').dequeue();
      }

      function makeBlack(){
        $('#wow').css('color', 'black');
        $('#wow').delay(200).queue(makeRed);
        $('#wow').dequeue();
      }
    </script>
  </head>
  <body>
    <div id="wow"><p>wow</p></div>
  </body>
</html>

Why doesn't Java support unsigned ints?

Your question is "Why doesn't Java support unsigned ints"?

And my answer to your question is that Java wants that all of it's primitive types: byte, char, short, int and long should be treated as byte, word, dword and qword respectively, exactly like in assembly, and the Java operators are signed operations on all of it's primitive types except for char, but only on char they are unsigned 16 bit only.

So static methods suppose to be the unsigned operations also for both 32 and 64 bit.

You need final class, whose static methods can be called for the unsigned operations.

You can create this final class, call it whatever name you want and implement it's static methods.

If you have no idea about how to implement the static methods then this link may help you.

In my opinion, Java is not similar to C++ at all, if it neither support unsigned types nor operator overloading, so I think that Java should be treated as completely different language from both C++ and from C.

It is also completely different in the name of the languages by the way.

So I don't recommend in Java to type code similar to C and I don't recommend to type code similar to C++ at all, because then in Java you won't be able to do what you want to do next in C++, i.e. the code won't continue to be C++ like at all and for me this is bad to code like that, to change the style in the middle.

I recommend to write and use static methods also for the signed operations, so you don't see in the code mixture of operators and static methods for both signed and unsigned operations, unless you need only signed operations in the code, and it's okay to use the operators only.

Also I recommend to avoid using short, int and long primitive types, and use word, dword and qword respectively instead, and you are about call the static methods for unsigned operations and/or signed operations instead of using operators.

If you are about to do signed operations only and use the operators only in the code, then this is okay to use these primitive types short, int and long.

Actually word, dword and qword don't exist in the language, but you can create new class for each and the implementation of each should be very easy:

The class word holds the primitive type short only, the class dword holds the primitive type int only and the class qword holds the primitive type long only. Now all the unsigned and the signed methods as static or not as your choice, you can implement in each class, i.e. all the 16 bit operations both unsigned and signed by giving meaning names on the word class, all the 32 bit operations both unsigned and signed by giving meaning names on the dword class and all the 64 bit operations both unsigned and signed by giving meaning names on the qword class.

If you don't like giving too many different names for each method, you can always use overloading in Java, good to read that Java didn't remove that too!

If you want methods rather than operators for 8 bit signed operations and methods for 8 bit unsigned operations that have no operators at all, then you can create the Byte class (note that the first letter 'B' is capital, so this is not the primitive type byte) and implement the methods in this class.

About passing by value and passing by reference:

If I am not wrong, like in C#, primitive objects are passed by value naturally, but class objects are passed by reference naturally, so that means that objects of type Byte, word, dword and qword will be passed by reference and not by value by default. I wish Java had struct objects as C# has, so all Byte, word, dword and qword could be implemented to be struct instead of class, so by default they were passed by value and not by reference by default, like any struct object in C#, like the primitive types, are passed by value and not by reference by default, but because that Java is worse than C# and we have to deal with that, then there is only classes and interfaces, that are passed by reference and not by value by default. So if you want to pass Byte, word, dword and qword objects by value and not by reference, like any other class object in Java and also in C#, you will have to simply use the copy constructor and that's it.

That's the only solution that I can think about. I just wish that I could just typedef the primitive types to word, dword and qword, but Java neither support typedef nor using at all, unlike C# that supports using, which is equivalent to the C's typedef.

About output:

For the same sequence of bits, you can print them in many ways: As binary, as decimal (like the meaning of %u in C printf), as octal (like the meaning of %o in C printf), as hexadecimal (like the meaning of %x in C printf) and as integer (like the meaning of the %d in C printf).

Note that C printf doesn't know the type of the variables being passed as parameters to the function, so printf knows the type of each variable only from the char* object passed to the first parameter of the function.

So in each of the classes: Byte, word, dword and qword, you can implement print method and get the functionality of printf, even though the primitive type of the class is signed, you still can print it as unsigned by following some algorithm involving logical and shift operations to get the digits to print to the output.

Unfortunately the link I gave you doesn't show how to implement these print methods, but I am sure you can google for the algorithms you need to implement these print methods.

That's all I can answer your question and suggest you.

Check if an HTML input element is empty or has no value entered by user

You want:

if (document.getElementById('customx').value === ""){
    //do something
}

The value property will give you a string value and you need to compare that against an empty string.

How to edit binary file on Unix systems

Bless is a high quality, full featured hex editor.

It is written in mono/Gtk# and its primary platform is GNU/Linux. However it should be able to run without problems on every platform that mono and Gtk# run. Main Features Bless currently provides the following features:

  • Efficient editing of large data files and block devices.
  • Multilevel undo - redo operations.
  • Customizable data views.
  • Fast data rendering on screen.
  • Multiple tabs.
  • Fast find and replace operations.
  • A data conversion table.
  • Advanced copy/paste capabilities.
  • Highlighting of selection pattern matches in the file.
  • Plugin based architecture.
  • Export of data to text and html (others with plugins).
  • Bitwise operations on data.
  • A comprehensive user manual.

copied from http://home.gna.org/bless/

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

Change encoding in notepad++ UTF-8 with BOM. That is how it worked for me

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

The only difference : synchronized blocks allows granular locking unlike synchronized method

Basically synchronized block or methods have been used to write thread safe code by avoiding memory inconsistency errors.

This question is very old and many things have been changed during last 7 years. New programming constructs have been introduced for thread safety.

You can achieve thread safety by using advanced concurrency API instead of synchronied blocks. This documentation page provides good programming constructs to achieve thread safety.

Lock Objects support locking idioms that simplify many concurrent applications.

Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.

Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.

ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.

Better replacement for synchronized is ReentrantLock, which uses Lock API

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

Example with locks:

class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.

Refer to this related question too:

Synchronization vs Lock

How to write LaTeX in IPython Notebook?

If your main objective is doing math, SymPy provides an excellent approach to functional latex expressions that look great.

HTTP Basic Authentication credentials passed in URL and encryption

Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text

How do you loop in a Windows batch file?

Try this code:

@echo off
color 02
set num1=0
set num2=1 
set terminator=5
:loop
set /a num1= %num1% + %num2%
if %num1%==%terminator% goto close
goto open
:close
echo %num1%
pause 
exit
:open
echo %num1%
goto loop

num1 is the number to be incremented and num2 is the value added to num1 and terminator is the value where the num1 will end. You can indicate different value for terminator in this statement (if %num1%==%terminator% goto close). This is the boolean expression goto close is the process if the boolean is true and goto open is the process if the boolean is false.

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.

Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.

How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.

How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.

How can I center <ul> <li> into div

I have been looking for the same case and tried all answers by change the width of <li>.
Unfortunately all were failed to get the same distance on left and right of the <ul> box.

The closest match is this answer but it needs to adjust the change of width with padding

.container ul {
    ...
    padding: 10px 25px;
}

.container li {
  ...
  width: 100px;
}

See the result below, all distance between <li> also to the <ul> box are the same. enter image description here

You may check it on this jsFiddle:
http://jsfiddle.net/qwbexxog/14/

jQuery Set Select Index

NB:

$('#selectBox option')[3].attr('selected', 'selected') 

is incorrect, the array deference gets you the dom object, not a jquery object, so it will fail with a TypeError, for instance in FF with: "$('#selectBox option')[3].attr() not a function."

Get file version in PowerShell

[System.Diagnostics.FileVersionInfo]::GetVersionInfo("Path\To\File.dll")

get launchable activity name of package from adb

Since Android 7.0 you can use adb shell cmd package resolve-activity command to get the default activity of an installed app like this:

adb shell "cmd package resolve-activity --brief com.google.android.calculator | tail -n 1"
com.google.android.calculator/com.android.calculator2.Calculator

Why use String.Format?

Besides being a bit easier to read and adding a few more operators, it's also beneficial if your application is internationalized. A lot of times the variables are numbers or key words which will be in a different order for different languages. By using String.Format, your code can remain unchanged while different strings will go into resource files. So, the code would end up being

String.Format(resource.GetString("MyResourceString"), str1, str2, str3);

While your resource strings end up being

English: "blah blah {0} blah blah {1} blah {2}"

Russian: "{0} blet blet blet {2} blet {1}"

Where Russian may have different rules on how things get addressed so the order is different or sentence structure is different.

java.lang.IllegalArgumentException: View not attached to window manager

I may have a workaround.

Was having the same issue, where I am loading lots of items (via the file system) into a ListView via an AsyncTask. Had the onPreExecute() firing up a ProgressDialog, and then both onPostExecute() and onCancelled() (called when the task is cancelled explicitly via AsyncTask.cancel()) closing it via .cancel().

Got the same "java.lang.IllegalArgumentException: View not attached to window manager" error when I was killing the dialog in the onCancelled() method of the AsyncTask (I'd seen this done in the excellent Shelves app).

The workaround was to create a public field in the AsyncTask that contains the ProgressDialog:

public ProgressDialog mDialog;

Then, in onDestroy() when I cancel my AsyncTask, I can also kill the associated dialog via:

AsyncTask.mDialog.cancel();

Calling AsyncTask.cancel() DOES trigger onCancelled() in the AsyncTask, but for some reason by the time that method is called, the View has already been destroyed and thus cancelling the dialog is failing.

Store an array in HashMap

Not sure of the exact question but is this what you are looking for?

public class TestRun
{
     public static void main(String [] args)
     {
        Map<String, Integer[]> prices = new HashMap<String, Integer[]>();

        prices.put("milk", new Integer[] {1, 3, 2});
        prices.put("eggs", new Integer[] {1, 1, 2});
     }
}

Python Script Uploading files via FTP

You can use the below function. I haven't tested it yet, but it should work fine. Remember the destination is a directory path where as source is complete file path.

import ftplib
import os

def uploadFileFTP(sourceFilePath, destinationDirectory, server, username, password):
    myFTP = ftplib.FTP(server, username, password)
    if destinationDirectory in [name for name, data in list(remote.mlsd())]:
        print "Destination Directory does not exist. Creating it first"
        myFTP.mkd(destinationDirectory)
    # Changing Working Directory
    myFTP.cwd(destinationDirectory)
    if os.path.isfile(sourceFilePath):
        fh = open(sourceFilePath, 'rb')
        myFTP.storbinary('STOR %s' % f, fh)
        fh.close()
    else:
        print "Source File does not exist"

Web-scraping JavaScript page with Python

I recently used requests_html library to solve this problem.

Their expanded documentation at readthedocs.io is pretty good (skip the annotated version at pypi.org). If your use case is basic, you are likely to have some success.

from requests_html import HTMLSession
session = HTMLSession()
response = session.request(method="get",url="www.google.com/")
response.html.render()

If you are having trouble rendering the data you need with response.html.render(), you can pass some javascript to the render function to render the particular js object you need. This is copied from their docs, but it might be just what you need:

If script is specified, it will execute the provided JavaScript at runtime. Example:

script = """
    () => {
        return {
            width: document.documentElement.clientWidth,
            height: document.documentElement.clientHeight,
            deviceScaleFactor: window.devicePixelRatio,
        }
    } 
"""

Returns the return value of the executed script, if any is provided:

>>> response.html.render(script=script)
{'width': 800, 'height': 600, 'deviceScaleFactor': 1}

In my case, the data I wanted were the arrays that populated a javascript plot but the data wasn't getting rendered as text anywhere in the html. Sometimes its not clear at all what the object names are of the data you want if the data is populated dynamically. If you can't track down the js objects directly from view source or inspect, you can type in "window" followed by ENTER in the debugger console in the browser (Chrome) to pull up a full list of objects rendered by the browser. If you make a few educated guesses about where the data is stored, you might have some luck finding it there. My graph data was under window.view.data in the console, so in the "script" variable passed to the .render() method quoted above, I used:

return {
    data: window.view.data
}

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

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

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

What is token-based authentication?

The question is old and the technology has advanced, here is the current state:

JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for passing claims between parties in web application environment. The tokens are designed to be compact, URL-safe and usable especially in web browser single sign-on (SSO) context.

https://en.wikipedia.org/wiki/JSON_Web_Token

How to remove all namespaces from XML with C#?

And this is the perfect solution that will also remove XSI elements. (If you remove the xmlns and don't remove XSI, .Net shouts at you...)

string xml = node.OuterXml;
//Regex below finds strings that start with xmlns, may or may not have :and some text, then continue with =
//and ", have a streach of text that does not contain quotes and end with ". similar, will happen to an attribute
// that starts with xsi.
string strXMLPattern = @"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
xml = Regex.Replace(xml, strXMLPattern, "");

jQuery Event : Detect changes to the html/text of a div

DOMSubtreeModified is not a good solution. It's can cause infinite loops if you decide to change the DOM inside the event handler, hence it has been disabled in a number of browsers. MutationObserver will be the answer.

MDN Doc

const onChangeElement = (qSelector, cb)=>{
 const targetNode = document.querySelector(qSelector);
 if(targetNode){
    const config = { attributes: true, childList: false, subtree: false };
    const callback = function(mutationsList, observer) {
        cb($(qSelector))
    };
    const observer = new MutationObserver(callback);
    observer.observe(targetNode, config);
 }else {
    console.error("onChangeElement: Invalid Selector")
 }
}

And you can use it,

onChangeElement('mydiv', function(jqueryElement){
   alert('changed')
})

Is there a php echo/print equivalent in javascript

From w3school's page on JavaScript output,

JavaScript can "display" data in different ways:

Writing into an alert box, using window.alert().

Writing into the HTML output using document.write().

Writing into an HTML element, using innerHTML.

Writing into the browser console, using console.log().

Where does SVN client store user authentication data?

Read SVNBook | Client Credentials.

With modern SVN you can just run svn auth to display the list of cached credentials. Don't forget to make sure that you run up-to-date SVN client version because svn auth was introduced in version 1.9. The last line will specify the path to credential store which by default is %APPDATA%\Subversion\auth on Windows and ~/.subversion/auth/ on Unix-like systems.

PS C:\Users\MyUser> svn auth
------------------------------------------------------------------------
Credential kind: svn.simple
Authentication realm: <https://svn.example.local:443> VisualSVN Server
Password cache: wincrypt
Password: [not shown]
Username: user

Credentials cache in 'C:\Users\MyUser\AppData\Roaming\Subversion' contains 5 credentials

How to pass parameters in $ajax POST?

Try using GET method,

var request = $.ajax({
    url: 'url',
    type: 'GET',
    data: { field1: "hello", field2 : "hello2"} ,
    contentType: 'application/json; charset=utf-8'
});

request.done(function(data) {
      // your success code here
});

request.fail(function(jqXHR, textStatus) {
      // your failure code here
});

You cannot see parameters in URL with POST method.

Edit:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

How to declare 2D array in bash

One can simply define two functions to write ($4 is the assigned value) and read a matrix with arbitrary name ($1) and indexes ($2 and $3) exploiting eval and indirect referencing.

#!/bin/bash

matrix_write () {
 eval $1"_"$2"_"$3=$4
 # aux=$1"_"$2"_"$3          # Alternative way
 # let $aux=$4               # ---
}

matrix_read () {
 aux=$1"_"$2"_"$3
 echo ${!aux}
}

for ((i=1;i<10;i=i+1)); do
 for ((j=1;j<10;j=j+1)); do 
  matrix_write a $i $j $[$i*10+$j]
 done
done

for ((i=1;i<10;i=i+1)); do
 for ((j=1;j<10;j=j+1)); do 
  echo "a_"$i"_"$j"="$(matrix_read a $i $j)
 done
done

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I have solved it by importing FormModule in a shared.module and importing the shared.module in all other modules. My case is the FormModule is used in multiple modules.

How to get the groups of a user in Active Directory? (c#, asp.net)

GetAuthorizationGroups() does not find nested groups. To really get all groups a given user is a member of (including nested groups), try this:

using System.Security.Principal

private List<string> GetGroups(string userName)
{
    List<string> result = new List<string>();
    WindowsIdentity wi = new WindowsIdentity(userName);

    foreach (IdentityReference group in wi.Groups)
    {
        try
        {
            result.Add(group.Translate(typeof(NTAccount)).ToString());
        }
        catch (Exception ex) { }
    }
    result.Sort();
    return result;
}

I use try/catch because I had some exceptions with 2 out of 200 groups in a very large AD because some SIDs were no longer available. (The Translate() call does a SID -> Name conversion.)

How do I center this form in css?

body { text-align: center; }
     /* center all items within body, this property is inherited */
body > * { text-align: left; }
     /* left-align the CONTENTS all items within body, additionally
        you can add this text-align: left property to all elements
        manually */
form { display: inline-block; }
     /* reduces the width of the form to only what is necessary */

?

http://jsfiddle.net/sqdBr/4/

Works & tested in Chrome/IE/FF

How do I center text vertically and horizontally in Flutter?

maybe u want to provide the same width and height for 2 container

Container(
            width: size.width * 0.30, height: size.height * 0.4,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6)
            ),
            child: Center(
              child: Text(categoryName, textAlign: TextAlign.center, style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 17,
                color: Colors.white,
              ),),
            ),

How to display (print) vector in Matlab?

Here is a more generalized solution that prints all elements of x the vector x in this format:

x=randperm(3);
s = repmat('%d,',1,length(x));
s(end)=[]; %Remove trailing comma

disp(sprintf(['Answer: (' s ')'], x))

What is the difference between Scrum and Agile Development?

How does Scrum fit into Agile Development?

While the Agile methodology can be applied to product development not only in the software industry but in other industries as well, Scrum is specific to software development.

Scrum is not a methodology. It simply provides structure, discipline and a framework for Agile development. The whole project is made up of a series of Sprints or Sprint Cycles (1 to n) where each Sprint is of the same duration. If ‘time’ is denoted by T, then T1 = T2 = T3 =… Tn. Sprints could be anywhere between 2 to 4 weeks. Sprints shorter than 2 weeks are not ideal and are used less frequently. At the end of each Sprint, a functional / working piece of software is produced that the users can actually test.

Original article is here...

https://www.linkedin.com/pulse/agile-development-using-scrum-what-you-dont-know-sri-prakash?trk=prof-post

Tooltips for cells in HTML table (no Javascript)

An evolution of what BioData41 added...

Place what follows in CSS style

     <style>

        .CellWithComment{position:relative;}

        .CellComment
        {
            visibility: hidden;
            width: auto;
            position:absolute; 
            z-index:100;
            text-align: Left;
            opacity: 0.4;
            transition: opacity 2s;
            border-radius: 6px;
            background-color: #555;
            padding:3px;
            top:-30px; 
            left:0px;
        }   
        .CellWithComment:hover span.CellComment {visibility: visible;opacity: 1;}
</style>

Then, use it like this:

        <table>
            <tr>
                <th class="CellWithComment">Category<span class="CellComment">"Ciaooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"</span></th>
                <th class="CellWithComment">Code<span class="CellComment">"Ciaooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"</span></th>
                <th>Opened</th>
                <th>Event</th>
                <th>Severity</th>           
                <th>Id</th>
                <th>Component Name</th>
            </tr>
            <tr>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
            </tr>
            <tr>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
            </tr>
        </table>

Python: Making a beep noise

I was searching for the same but for Linux shell.

The topic brought me to an answer, -thanks-

Maybe more pythonic manner :

import os
beep = lambda x: os.system("echo -n '\a';sleep 0.2;" * x)
beep(3)

Notes :

  • the sleep value (here 0.2), depends on the length (seconds) of your default beep sound
  • I choosed to use os.system rather then subprocess.Popen for simplicity (it could be bad)
  • the '-n' for echo is to have no more display
  • the last ';' after sleep is necessary for the resulting text sequence (*x)
  • also tested through ssh on an X term

Intercept and override HTTP requests from WebView

This may helps:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
    String url = request.getUrl().toString();
    WebResourceResponse response = super.shouldInterceptRequest(view, request);
    // load native js
    if (url != null && url.contains(INJECTION_TOKEN/* scheme define */)) {

        response = new WebResourceResponse(
                "text/javascript",
                "utf-8",
                loadJsInputStream(url, JsCache.getJsFilePath(path) /* InputStream */));
    }
    return response;
}

How to set time zone in codeigniter?

you can try this:

date_default_timezone_set('Asia/Kolkata');

In application/config.php OR application/autoload.php

There is look like this:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

date_default_timezone_set('Asia/Kolkata');

It's working fine for me, i think this is the best way to define DEFAULT TIMEZONE in codeignitor.

AWS Lambda import module error in python

Sharing my solution for the same issue, just in case it helps anyone.

Issue: I got error: "[ERROR] Runtime.ImportModuleError: Unable to import module 'lambda_function': No module named 'StringIO'" while executing aws-big-data-blog code[1] provided in AWS article[2].

Solution: Changed Runtime from Python 3.7 to Python 2.7

[1] — https://github.com/bsnively/aws-big-data-blog/blob/master/aws-blog-vpcflowlogs-athena-quicksight/CloudwatchLogsToFirehose/lambdacode.py [2] — https://aws.amazon.com/blogs/big-data/analyzing-vpc-flow-logs-with-amazon-kinesis-firehose-amazon-athena-and-amazon-quicksight/

Better/Faster to Loop through set or list?

Just use a set. Its semantics are exactly what you want: a collection of unique items.

Technically you'll be iterating through the list twice: once to create the set, once for your actual loop. But you'd be doing just as much work or more with any other approach.

CAST to DECIMAL in MySQL

MySQL casts to Decimal:

Cast bare integer to decimal:

select cast(9 as decimal(4,2));       //prints 9.00

Cast Integers 8/5 to decimal:

select cast(8/5 as decimal(11,4));    //prints 1.6000

Cast string to decimal:

select cast(".885" as decimal(11,3));   //prints 0.885

Cast two int variables into a decimal

mysql> select 5 into @myvar1;
Query OK, 1 row affected (0.00 sec)

mysql> select 8 into @myvar2;
Query OK, 1 row affected (0.00 sec)

mysql> select @myvar1/@myvar2;   //prints 0.6250

Cast decimal back to string:

select cast(1.552 as char(10));   //shows "1.552"

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

Simple answer:A grammar is said to be an LL(1),if the associated LL(1) parsing table has atmost one production in each table entry.

Take the simple grammar A -->Aa|b.[A is non-terminal & a,b are terminals]
   then find the First and follow sets A.
    First{A}={b}.
    Follow{A}={$,a}.

    Parsing table for Our grammar.Terminals as columns and Nonterminal S as a row element.

        a            b                   $
    --------------------------------------------
 S  |               A-->a                      |
    |               A-->Aa.                    |
    -------------------------------------------- 

As [S,b] contains two Productions there is a confusion as to which rule to choose.So it is not LL(1).

Some simple checks to see whether a grammar is LL(1) or not. Check 1: The Grammar should not be left Recursive. Example: E --> E+T. is not LL(1) because it is Left recursive. Check 2: The Grammar should be Left Factored.

Left factoring is required when two or more grammar rule choices share a common prefix string. Example: S-->A+int|A.

Check 3:The Grammar should not be ambiguous.

These are some simple checks.

How to change legend size with matplotlib.pyplot

Now in 2020, with matplotlib 3.2.2 you can set your legend fonts with

plt.legend(title="My Title", fontsize=10, title_fontsize=15)

where fontsize is the font size of the items in legend and title_fontsize is the font size of the legend title. More information in matplotlib documentation

How to install Anaconda on RaspBerry Pi 3 Model B

If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m in with backticks like so:

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh

Is it possible to import modules from all files in a directory, using a wildcard?

Just an other approach to @Bergi's answer

// lib/things/index.js
import ThingA from './ThingA';
import ThingB from './ThingB';
import ThingC from './ThingC';

export default {
 ThingA,
 ThingB,
 ThingC
}

Uses

import {ThingA, ThingB, ThingC} from './lib/things';

how to initialize a char array?

The C-like method may not be as attractive as the other solutions to this question, but added here for completeness:

You can initialise with NULLs like this:

char msg[65536] = {0};

Or to use zeros consider the following:

char msg[65536] = {'0' another 65535 of these separated by comma};

But do not try it as not possible, so use memset!

In the second case, add the following after the memset if you want to use msg as a string.

msg[65536 - 1] =  '\0'

Answers to this question also provide further insight.

Javascript: Extend a Function

Another option could be:

var initial = function() {
    console.log( 'initial function!' );
}

var iWantToExecuteThisOneToo = function () {
    console.log( 'the other function that i wanted to execute!' );
}

function extendFunction( oldOne, newOne ) {
    return (function() {
        oldOne();
        newOne();
    })();
}

var extendedFunction = extendFunction( initial, iWantToExecuteThisOneToo );

Decimal to Hexadecimal Converter in Java

One possible solution:

import java.lang.StringBuilder;

class Test {
  private static final int sizeOfIntInHalfBytes = 8;
  private static final int numberOfBitsInAHalfByte = 4;
  private static final int halfByte = 0x0F;
  private static final char[] hexDigits = { 
    '0', '1', '2', '3', '4', '5', '6', '7', 
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String decToHex(int dec) {
    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
    hexBuilder.setLength(sizeOfIntInHalfBytes);
    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
    {
      int j = dec & halfByte;
      hexBuilder.setCharAt(i, hexDigits[j]);
      dec >>= numberOfBitsInAHalfByte;
    }
    return hexBuilder.toString(); 
  }

  public static void main(String[] args) {
     int dec = 305445566;
     String hex = decToHex(dec);
     System.out.println(hex);       
  }
}

Output:

1234BABE

Anyway, there is a library method for this:

String hex = Integer.toHexString(dec);

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

Installing R with Homebrew

brew install cask
brew cask install xquartz
brew tap homebrew/science
brew install r

This way, everything is packager managed, so there's no need to manually download and install anything.

How to store standard error in a variable

There are a lot of duplicates for this question, many of which have a slightly simpler usage scenario where you don't want to capture stderr and stdout and the exit code all at the same time.

if result=$(useless.sh 2>&1); then
    stdout=$result
else
    rc=$?
    stderr=$result
fi

works for the common scenario where you expect either proper output in the case of success, or a diagnostic message on stderr in the case of failure.

Note that the shell's control statements already examine $? under the hood; so anything which looks like

cmd
if [ $? -eq 0 ], then ...

is just a clumsy, unidiomatic way of saying

if cmd; then ...

Marker in leaflet, click event

Additional relevant info: A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.

It seems that when we do:

marker.on('click', function(e) {...

The e points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this object which strangely, requires us to use this.options to get to the options object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid then within the function above, we can get the value by invoking: this.options.objid

jQuery click function doesn't work after ajax call?

Here's the FIDDLE

Same code as yours but it will work on dynamically created elements.

$(document).on('click', '.deletelanguage', function () {
    alert("success");
    $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});

Drop all duplicate rows across multiple columns in Python Pandas

If you want result to be stored in another dataset:

df.drop_duplicates(keep=False)

or

df.drop_duplicates(keep=False, inplace=False)

If same dataset needs to be updated:

df.drop_duplicates(keep=False, inplace=True)

Above examples will remove all duplicates and keep one, similar to DISTINCT * in SQL

How to access site running apache server over lan without internet connection

Please reformulate your question. Your first sentence does not make sense. .

To address your question:

http://ip.of.server/ should work in principle. However, depending on configuration (virtual hosting) only using the correct host name may work.

At any rate, if you have a network, you should properly configure DNS, otherwise all kinds of problems (such as this) may occur.

Auto highlight text in a textbox control

It is very easy to achieve with built in method SelectAll

Simply cou can write this:

txtTextBox.Focus();
txtTextBox.SelectAll();

And everything in textBox will be selected :)

Python socket connection timeout

If you are using Python2.6 or newer, it's convenient to use socket.create_connection

sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

Java for loop syntax: "for (T obj : objects)"

Yes, It is called the for-each loop. Objects in the collectionName will be assigned one after one from the beginning of that collection, to the created object reference, 'objectName'. So in each iteration of the loop, the 'objectName' will be assigned an object from the 'collectionName' collection. The loop will terminate once when all the items(objects) of the 'collectionName' Collection have finished been assigning or simply the objects to get are over.

for (ObjectType objectName : collectionName.getObjects()){ //loop body> //You can use the 'objectName' here as needed and different objects will be //reepresented by it in each iteration. }

How do I import other TypeScript files?

import {className} from 'filePath';

remember also. The class you are importing , that must be exported in the .ts file.

Unable to use Intellij with a generated sources folder

i ran mvn generate-resources and then marked the /target/generated-resources folder as "sources" (Project Structure -> Project Settings -> Modules -> Select /target/generated-resources -> Click on blue "Sources" icon.

Psql list all tables

In SQL Query, you can write this code:

select table_name from information_schema.tables where table_schema='YOUR_TABLE_SCHEME';

Replace your table scheme with YOUR_TABLE_SCHEME;

Example:

select table_name from information_schema.tables where table_schema='eLearningProject';

To see all scheme and all tables, there is no need of where clause:

select table_name from information_schema.tables

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

[I was going to post this as a comment on John Cromartie's post, but didn't realize you couldn't use formatting in a comment.]

I agree. Dropping it to a shell with os.execute() will definitely work but in general making shell calls is expensive. Wrapping some C code will be much quicker at run-time. In C/C++ on a Linux system, you could use:

static int lua_sleep(lua_State *L)
{
    int m = static_cast<int> (luaL_checknumber(L,1));
    usleep(m * 1000); 
    // usleep takes microseconds. This converts the parameter to milliseconds. 
    // Change this as necessary. 
    // Alternatively, use 'sleep()' to treat the parameter as whole seconds. 
    return 0;
}

Then, in main, do:

lua_pushcfunction(L, lua_sleep);
lua_setglobal(L, "sleep");

where "L" is your lua_State. Then, in your Lua script called from C/C++, you can use your function by calling:

sleep(1000) -- Sleeps for one second

Adding ID's to google map markers

JavaScript is a dynamic language. You could just add it to the object itself.

var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};

Also, because all v3 objects extend MVCObject(). You can use:

marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");

What is the difference between a heuristic and an algorithm?

A heuristic is usually an optimization or a strategy that usually provides a good enough answer, but not always and rarely the best answer. For example, if you were to solve the traveling salesman problem with brute force, discarding a partial solution once its cost exceeds that of the current best solution is a heuristic: sometimes it helps, other times it doesn't, and it definitely doesn't improve the theoretical (big-oh notation) run time of the algorithm

Add one day to date in javascript

The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.

Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.

A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.

For example,

var dateString = 'Mon Jun 30 2014 00:00:00';

var startDate = new Date(dateString);

// seconds * minutes * hours * milliseconds = 1 day 
var day = 60 * 60 * 24 * 1000;

var endDate = new Date(startDate.getTime() + day);

JSFiddle

Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.

SQL How to replace values of select return?

Replace the value in select statement itself...

(CASE WHEN Mobile LIKE '966%' THEN (select REPLACE(CAST(Mobile AS nvarchar(MAX)),'966','0')) ELSE Mobile END)

How to instantiate a javascript class in another js file?

If you are using javascript in HTML, you should include file1.js and file2.js inside your html:

<script src="path_to/file1.js"></script>
<script src="path_to/file2.js"></script>

Note, file1 should come first before file2.

I want my android application to be only run in portrait mode?

In Android Manifest File, put attribute for your <activity> that android:screenOrientation="portrait"

Get contentEditable caret index position

A few wrinkles that I don't see being addressed in other answers:

  1. the element can contain multiple levels of child nodes (e.g. child nodes that have child nodes that have child nodes...)
  2. a selection can consist of different start and end positions (e.g. multiple chars are selected)
  3. the node containing a Caret start/end may not be either the element or its direct children

Here's a way to get start and end positions as offsets to the element's textContent value:

// node_walk: walk the element tree, stop when func(node) returns false
function node_walk(node, func) {
  var result = func(node);
  for(node = node.firstChild; result !== false && node; node = node.nextSibling)
    result = node_walk(node, func);
  return result;
};

// getCaretPosition: return [start, end] as offsets to elem.textContent that
//   correspond to the selected portion of text
//   (if start == end, caret is at given position and no text is selected)
function getCaretPosition(elem) {
  var sel = window.getSelection();
  var cum_length = [0, 0];

  if(sel.anchorNode == elem)
    cum_length = [sel.anchorOffset, sel.extentOffset];
  else {
    var nodes_to_find = [sel.anchorNode, sel.extentNode];
    if(!elem.contains(sel.anchorNode) || !elem.contains(sel.extentNode))
      return undefined;
    else {
      var found = [0,0];
      var i;
      node_walk(elem, function(node) {
        for(i = 0; i < 2; i++) {
          if(node == nodes_to_find[i]) {
            found[i] = true;
            if(found[i == 0 ? 1 : 0])
              return false; // all done
          }
        }

        if(node.textContent && !node.firstChild) {
          for(i = 0; i < 2; i++) {
            if(!found[i])
              cum_length[i] += node.textContent.length;
          }
        }
      });
      cum_length[0] += sel.anchorOffset;
      cum_length[1] += sel.extentOffset;
    }
  }
  if(cum_length[0] <= cum_length[1])
    return cum_length;
  return [cum_length[1], cum_length[0]];
}

static function in C

pmg is spot on about encapsulation; beyond hiding the function from other translation units (or rather, because of it), making functions static can also confer performance benefits in the presence of compiler optimizations.

Because a static function cannot be called from anywhere outside of the current translation unit (unless the code takes a pointer to its address), the compiler controls all the call points into it.

This means that it is free to use a non-standard ABI, inline it entirely, or perform any number of other optimizations that might not be possible for a function with external linkage.

What is a StackOverflowError?

The term "stack overrun (overflow)" is often used but a misnomer; attacks do not overflow the stack but buffers on the stack.

-- from lecture slides of Prof. Dr. Dieter Gollmann

LINQ to SQL Left Outer Join

Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
        From o In ords.DefaultIfEmpty _
        Select New With {e.FirstName, e.LastName, .Order = o}

ObjectDumper.Write(q) End Sub

Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx

How to check if a value exists in a dictionary (python)

>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True

Out of curiosity, some comparative timing:

>>> T(lambda : 'one' in d.itervalues()).repeat()
[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]
>>> T(lambda : 'one' in d.values()).repeat()
[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]
>>> T(lambda : 'one' in d.viewvalues()).repeat()
[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]

EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:

>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>

EDIT2: As per request in comments...

>>> T(lambda : 'four' in d.itervalues()).repeat()
[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]
>>> T(lambda : 'four' in d.values()).repeat()
[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]
>>> T(lambda : 'four' in d.viewvalues()).repeat()
[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]

html text input onchange event

Well unless I misunderstand you can just use the onChange attribute:

<input type="text" onChange="return bar()">

Note: in FF 3 (at least) this is not called until some the user has confirmed they are changed either by clicking away from the element, clicking enter, or other.

Changing upload_max_filesize on PHP

By default, PHP permits uploading maximum 2 MB file on the server. But you can modify the maximum size of file upload as per your condition. By using the PHP configuration file php.ini, you can increase or decrease the file upload size in PHP.

First open the php.ini file in your text editor. Search the upload_max_filesize variable and stipulate the size which you want to increase.

Search for post_max_size variable and stipulate the size which you want to increase.

post_max_size = 128M

you can check this from here

Java JDBC - How to connect to Oracle using Service Name instead of SID

This should be working: jdbc:oracle:thin//hostname:Port/ServiceName=SERVICE_NAME

How to set java_home on Windows 7?

After hours of work around most of the solutions here, the problem was solved for me just by installing 32-bit JDK.

How do I set the focus to the first input element in an HTML form independent from the id?

You can also try jQuery based method:

$(document).ready(function() {
    $('form:first *:input[type!=hidden]:first').focus();
});

Error loading the SDK when Eclipse starts

Feel tired deleting the android-wear related packages each time upgrading the sdk?

Try to make some changes to devices.xml as following, you can edit the files by hand, or use some batching tools like repl.

repl is written by me, add this line to sources.list and install:

echo 'http://deb.bodz.net/ unstable/' >>/etc/apt/sources.list
alias sagu='sudo apt-get update'
alias sagi='sudo apt-get install'
sagu
sagi repl

Then, remove those <d:skin> lines and replace ###dpi to hdpi or whatever.

repl -r --filter=devices.xml --mode=regexp -- '<d:skin>.*</d:skin>' '' .
repl -r --filter=devices.xml -- '280dpi' 'hdpi' .
repl -r --filter=devices.xml -- '360dpi' 'xhdpi' .

Redirect within component Angular 2

callLog(){
    this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
    .subscribe(data => {
        this.getstud=data as string[];
        if(this.getstud.length!==0) {
            console.log(data)
            this.route.navigate(['home']);// used for routing after importing Router    
        }
    });
}

Is it possible to refresh a single UITableViewCell in a UITableView?

Just to update these answers slightly with the new literal syntax in iOS 6--you can use Paths = @[indexPath] for a single object, or Paths = @[indexPath1, indexPath2,...] for multiple objects.

Personally, I've found the literal syntax for arrays and dictionaries to be immensely useful and big time savers. It's just easier to read, for one thing. And it removes the need for a nil at the end of any multi-object list, which has always been a personal bugaboo. We all have our windmills to tilt with, yes? ;-)

Just thought I'd throw this into the mix. Hope it helps.

Where can I find a list of Mac virtual key codes?

Found an answer here.

So:

  • Command key is 55
  • Shift is 56
  • Caps Lock 57
  • Option is 58
  • Control is 59.

how to upload a file to my server using html

You need enctype="multipart/form-data" otherwise you will load only the file name and not the data.

Add vertical scroll bar to panel

Below is the code that implements custom vertical scrollbar. The important detail here is to know when scrollbar is needed by calculating how much space is consumed by the controls that you add to the panel.

panelUserInput.SuspendLayout();
panelUserInput.Controls.Clear();
panelUserInput.AutoScroll = false;
panelUserInput.VerticalScroll.Visible = false;

// here you'd be adding controls

int x = 20, y = 20, height = 0;
for (int inx = 0; inx < numControls; inx++ )
{
    // this example uses textbox control
    TextBox txt = new TextBox();
    txt.Location = new System.Drawing.Point(x, y);
    // add whatever details you need for this control
    // before adding it to the panel
    panelUserInput.Controls.Add(txt);
    height = y + txt.Height;
    y += 25;
}
if (height > panelUserInput.Height)
{
    VScrollBar bar = new VScrollBar();
    bar.Dock = DockStyle.Right;
    bar.Scroll += (sender, e) => { panelUserInput.VerticalScroll.Value =  bar.Value; };
    bar.Top = 0;
    bar.Left = panelUserInput.Width - bar.Width;
    bar.Height = panelUserInput.Height;
    bar.Visible = true;
    panelUserInput.Controls.Add(bar);
}
panelUserInput.ResumeLayout();

// then update the form
this.PerformLayout();

A div with auto resize when changing window width\height

In this scenario, the outer <div> has a width and height of 90%. The inner div> has a width of 100% of its parent. Both scale when re-sizing the window.

HTML

<div>
    <div>Hello there</div>
</div>

CSS

html, body {
    width: 100%;
    height: 100%;
}

body > div {
    width: 90%;
    height: 100%;
    background: green;
}

body > div > div {
    width: 100%;
    background: red;
}

Demo

Try before buy

How to sort findAll Doctrine's method?

Look at the Doctrine API source-code :

class EntityRepository{
  ...
  public function findAll(){
    return $this->findBy(array());
  }
  ...
}

Encapsulation vs Abstraction?

Lets try to understand in a different way.

What may happen if Abstraction is not there and What may happen if Encapsulation is not there.

If Abstraction is not there, then you can say the object is use less. You cannot identify the object nor can you access any functionality of it. Take a example of a TV, if you do not have an option to power on, change channel, increase or decrease volume etc., then what's the use of TV and how do you use it ?

If Encapsulation is not there or not being implemented properly, then you may misuse the object. There by data/components may get misused. Take the same example of TV, If there is no encapsulation done to the volume of TV, then the volume controller may be misused by making it come below or go beyond its limit (0-40/50).

Difference between HashMap and Map in Java..?

Map is an interface in Java. And HashMap is an implementation of that interface (i.e. provides all of the methods specified in the interface).

PHP Converting Integer to Date, reverse of strtotime

Yes you can convert it back. You can try:

date("Y-m-d H:i:s", 1388516401);

The logic behind this conversion from date to an integer is explained in strtotime in PHP:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

For example, strtotime("1970-01-01 00:00:00") gives you 0 and strtotime("1970-01-01 00:00:01") gives you 1.

This means that if you are printing strtotime("2014-01-01 00:00:01") which will give you output 1388516401, so the date 2014-01-01 00:00:01 is 1,388,516,401 seconds after January 1 1970 00:00:00 UTC.

How can I compile and run c# program without using visual studio?

There are different ways for this:

1.Building C# Applications Using csc.exe

While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.

2.Building .NET Applications Using Notepad++

Another simple text editor I’d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports

3.Building .NET Applications Using SharpDevelop

As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.

How can two strings be concatenated?

> tmp = paste("GAD", "AB", sep = ",")
> tmp
[1] "GAD,AB"

I found this from Google by searching for R concatenate strings: http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html

Automatically open default email client and pre-populate content

As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:

mailto:[email protected]?subject=Subject&body=message%20goes%20here

User doesn't need to click a link if you force it to be opened with JavaScript

window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";

Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.

Logging with Retrofit 2

Retrofit's interceptor is a great feature which allow you work with http requests. There are two types of them: application and network interceptors.

I would recommend to use Charles Web Debugging Proxy Application if you need logging your requests/responses. The output is very similar to Stetho but it is more powerful instrument which you do not need to add as a dependency to an application

How to get a enum value from string in C#?

Using Enum.TryParse you don't need the Exception handling:

baseKey e;

if ( Enum.TryParse(s, out e) )
{
 ...
}

TypeError: 'undefined' is not a function (evaluating '$(document)')

Two things:

  1. Be sure that you have jQuery library added, before your $(document).
  2. Then just change all "$" with: jQuery , as the previous comments.

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Maybe this can help:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: basic-auth-server.herokuapp.com
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
paths:
  /:
    get:
      security:
        - Bearer: []
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

You can copy&paste it out here: http://editor.swagger.io/#/ to check out the results.

There are also several examples in the swagger editor web with more complex security configurations which could help you.

Cron and virtualenv

You should be able to do this by using the python in your virtual environment:

/home/my/virtual/bin/python /home/my/project/manage.py command arg

EDIT: If your django project isn't in the PYTHONPATH, then you'll need to switch to the right directory:

cd /home/my/project && /home/my/virtual/bin/python ...

You can also try to log the failure from cron:

cd /home/my/project && /home/my/virtual/bin/python /home/my/project/manage.py > /tmp/cronlog.txt 2>&1

Another thing to try is to make the same change in your manage.py script at the very top:

#!/home/my/virtual/bin/python

jQuery Select first and second td

You can do in this way also

var prop = $('.someProperty').closest('tr');

If the number of tr is in array

$.each(prop , function() {
  var gotTD = $(this).find('td:eq(1)');                 
});

How to get current time in milliseconds in PHP?

Use microtime(true) in PHP 5, or the following modification in PHP 4:

array_sum(explode(' ', microtime()));

A portable way to write that code would be:

function getMicrotime()
{
    if (version_compare(PHP_VERSION, '5.0.0', '<'))
    {
        return array_sum(explode(' ', microtime()));
    }

    return microtime(true);
}

how to inherit Constructor from super class to sub class

Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.

Here is an example of how this works:

class Foo {
    Foo(String str) { }
}

class Bar extends Foo {
    Bar(String str) {
        // Here I am explicitly calling the superclass 
        // constructor - since constructors are not inherited
        // you must chain them like this.
        super(str);
    }
}

The right way of setting <a href=""> when it's a local file

Try swapping your colon : for a bar |. that should do it

<a href="file://C|/path/to/file/file.html">Link Anchor</a>

Filter values only if not null using lambda in Java8

You can do this in single filter step:

requiredCars = cars.stream().filter(c -> c.getName() != null && c.getName().startsWith("M"));

If you don't want to call getName() several times (for example, it's expensive call), you can do this:

requiredCars = cars.stream().filter(c -> {
    String name = c.getName();
    return name != null && name.startsWith("M");
});

Or in more sophisticated way:

requiredCars = cars.stream().filter(c -> 
    Optional.ofNullable(c.getName()).filter(name -> name.startsWith("M")).isPresent());

WCF change endpoint address at runtime

app.config

<client>
    <endpoint address="" binding="basicHttpBinding" 
    bindingConfiguration="LisansSoap" 
    contract="Lisans.LisansSoap" 
    name="LisansSoap" />
</client>

program

 Lisans.LisansSoapClient test = new LisansSoapClient("LisansSoap",
                         "http://webservis.uzmanevi.com/Lisans/Lisans.asmx");

 MessageBox.Show(test.LisansKontrol("","",""));

JUnit 5: How to assert an exception is thrown?

You can use assertThrows(). My example is taken from the docs http://junit.org/junit5/docs/current/user-guide/

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

....

@Test
void exceptionTesting() {
    Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
        throw new IllegalArgumentException("a message");
    });
    assertEquals("a message", exception.getMessage());
}

How can I clear or empty a StringBuilder?

I think many of the answers here may be missing a quality method included in StringBuilder: .delete(int start, [int] end). I know this is a late reply; however, this should be made known (and explained a bit more thoroughly).

Let's say you have a StringBuilder table - which you wish to modify, dynamically, throughout your program (one I am working on right now does this), e.g.

StringBuilder table = new StringBuilder();

If you are looping through the method and alter the content, use the content, then wish to discard the content to "clean up" the StringBuilder for the next iteration, you can delete it's contents, e.g.

table.delete(int start, int end). 

start and end being the indices of the chars you wish to remove. Don't know the length in chars and want to delete the whole thing?

table.delete(0, table.length());

NOW, for the kicker. StringBuilders, as mentioned previously, take a lot of overhead when altered frequently (and can cause safety issues with regard to threading); therefore, use StringBuffer - same as StringBuilder (with a few exceptions) - if your StringBuilder is used for the purpose of interfacing with the user.

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

jstat -gccapacity javapid  (ex. stat -gccapacity 28745)
jstat -gccapacity javapid gaps frames (ex.  stat -gccapacity 28745 550 10 )

Sample O/P of above command

NGCMN    NGCMX     NGC     S0C  
87040.0 1397760.0 1327616.0 107520.0 

NGCMN   Minimum new generation capacity (KB).
NGCMX   Maximum new generation capacity (KB).
NGC Current new generation capacity (KB).

Get more details about this at http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jstat.html

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

To get it working, I had to go to myaccount.google.com -> "connected apps & sites", and turn "Allow less secure apps" to "ON" (near the bottom of the page).

HTML code for an apostrophe

I've found FileFormat.info's Unicode Character Search to be most helpful in finding exact character codes.

Entering simply ' (the character to the left of the return key on my US Mac keyboard) into their search yields several results of various curls and languages.

I would presume the original question was asking for the typographically correct U+02BC ', rather than the typewriter fascimile U+0027 '.

The W3C recommends hex codes for HTML entities (see below). For U+02BC that would be &#x2bc;, rather than &#x27; for U+0027.

http://www.w3.org/International/questions/qa-escapes

Using character escapes in markup and CSS

Hex vs. decimal. Typically when the Unicode Standard refers to or lists characters it does so using a hexadecimal value. … Given the prevalence of this convention, it is often useful, though not required, to use hexadecimal numeric values in escapes rather than decimal values…

http://www.w3.org/TR/html4/charset.html

5 HTML Document Representation5.4 Undisplayable characters

…If missing characters are presented using their numeric representation, use the hexadecimal (not decimal) form, since this is the form used in character set standards.

How to access a property of an object (stdClass Object) member/element of an array?

Try this, working fine -

$array = json_decode(json_encode($array), true);

Regular Expression to match valid dates

Perl expanded version

Note use of /x modifier.

/^(
      (
        ( # 31 day months
            (0[13578])
          | ([13578])
          | (1[02])
        )
        [\/]
        (
            ([1-9])
          | ([0-2][0-9])
          | (3[01])
        )
      )
    | (
        ( # 30 day months
            (0[469])
          | ([469])
          | (11)
        )
        [\/]
        (
            ([1-9])
          | ([0-2][0-9])
          | (30)
        )
      )
    | ( # 29 day month (Feb)
        (2|02)
        [\/]
        (
            ([1-9])
          | ([0-2][0-9])
        )
      )
    )
    [\/]
    # year
    \d{4}$
  
  | ^\d{4}$ # year only
/x

Original

^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$

How to pass a view's onClick event to its parent on Android?

Sometime only this helps:

View child = parent.findViewById(R.id.btnMoreText);
    child.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            View parent = (View) v.getParent();
            parent.performClick();
        }
    });

Another variant, works not always:

child.setOnClickListener(null);

What is a Python equivalent of PHP's var_dump()?

The closest thing to PHP's var_dump() is pprint() with the getmembers() function in the built-in inspect module:

from inspect import getmembers
from pprint import pprint
pprint(getmembers(yourObj))

How to specify preference of library path?

Specifying the absolute path to the library should work fine:

g++ /my/dir/libfoo.so.0  ...

Did you remember to remove the -lfoo once you added the absolute path?

Showing all session data at once?

echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";

Display yet formatting then you can view properly.

how to reset <input type = "file">

With IE 10 I resolved the problem with :

    var file = document.getElementById("file-input");
    file.removeAttribute('value');
    file.parentNode.replaceChild(file.cloneNode(true),file);

where :

<input accept="image/*" onchange="angular.element(this).scope().uploadFile(this)" id="file-input" type="file"/>

Razor/CSHTML - Any Benefit over what we have?

  1. Everything is encoded by default!!! This is pretty huge.

  2. Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.

  3. You can make a section required which is nice.

Key value pairs using JSON

JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.

Since Javascripts objects consists of key/value pairs its very easy to use and access JSON that way.

So if we have an object:

var myObj = {
    foo:   'bar',
    base:  'ball',
    deep:  {
       java:  'script'
    }
};

We can convert that into a string by calling window.JSON.stringify(myObj); with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}".

The other way around, we would call window.JSON.parse("a json string like the above");.

JSON.parse() returns a javascript object/array on success.

alert(myObj.deep.java);  // 'script'

window.JSON is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.

What is "entropy and information gain"?

As you are reading a book about NLTK it would be interesting you read about MaxEnt Classifier Module http://www.nltk.org/api/nltk.classify.html#module-nltk.classify.maxent

For text mining classification the steps could be: pre-processing (tokenization, steaming, feature selection with Information Gain ...), transformation to numeric (frequency or TF-IDF) (I think that this is the key step to understand when using text as input to a algorithm that only accept numeric) and then classify with MaxEnt, sure this is just an example.

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

How to tell if tensorflow is using gpu acceleration from inside python shell?

Following piece of code should give you all devices available to tensorflow.

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Sample Output

[name: "/cpu:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 4402277519343584096,

name: "/gpu:0" device_type: "GPU" memory_limit: 6772842168 locality { bus_id: 1 } incarnation: 7471795903849088328 physical_device_desc: "device: 0, name: GeForce GTX 1070, pci bus id: 0000:05:00.0" ]

How to check if PHP array is associative or sequential?

One more fast from source. Fit encoding of json_encode (and bson_encode). So has javascript Array compliance.

function isSequential($value){
    if(is_array($value) || ($value instanceof \Countable && $value instanceof \ArrayAccess)){
        for ($i = count($value) - 1; $i >= 0; $i--) {
            if (!isset($value[$i]) && !array_key_exists($i, $value)) {
                return false;
            }
        }
        return true;
    } else {
        throw new \InvalidArgumentException(
            sprintf('Data type "%s" is not supported by method %s', gettype($value), __METHOD__)
        );
    }
}

Traits vs. interfaces

Public Service Announcement:

I want to state for the record that I believe traits are almost always a code smell and should be avoided in favor of composition. It's my opinion that single inheritance is frequently abused to the point of being an anti-pattern and multiple inheritance only compounds this problem. You'll be much better served in most cases by favoring composition over inheritance (be it single or multiple). If you're still interested in traits and their relationship to interfaces, read on ...


Let's start by saying this:

Object-Oriented Programming (OOP) can be a difficult paradigm to grasp. Just because you're using classes doesn't mean your code is Object-Oriented (OO).

To write OO code you need to understand that OOP is really about the capabilities of your objects. You've got to think about classes in terms of what they can do instead of what they actually do. This is in stark contrast to traditional procedural programming where the focus is on making a bit of code "do something."

If OOP code is about planning and design, an interface is the blueprint and an object is the fully constructed house. Meanwhile, traits are simply a way to help build the house laid out by the blueprint (the interface).

Interfaces

So, why should we use interfaces? Quite simply, interfaces make our code less brittle. If you doubt this statement, ask anyone who's been forced to maintain legacy code that wasn't written against interfaces.

The interface is a contract between the programmer and his/her code. The interface says, "As long as you play by my rules you can implement me however you like and I promise I won't break your other code."

So as an example, consider a real-world scenario (no cars or widgets):

You want to implement a caching system for a web application to cut down on server load

You start out by writing a class to cache request responses using APC:

class ApcCacher
{
  public function fetch($key) {
    return apc_fetch($key);
  }
  public function store($key, $data) {
    return apc_store($key, $data);
  }
  public function delete($key) {
    return apc_delete($key);
  }
}

Then, in your HTTP response object, you check for a cache hit before doing all the work to generate the actual response:

class Controller
{
  protected $req;
  protected $resp;
  protected $cacher;

  public function __construct(Request $req, Response $resp, ApcCacher $cacher=NULL) {
    $this->req    = $req;
    $this->resp   = $resp;
    $this->cacher = $cacher;

    $this->buildResponse();
  }

  public function buildResponse() {
    if (NULL !== $this->cacher && $response = $this->cacher->fetch($this->req->uri()) {
      $this->resp = $response;
    } else {
      // Build the response manually
    }
  }

  public function getResponse() {
    return $this->resp;
  }
}

This approach works great. But maybe a few weeks later you decide you want to use a file-based cache system instead of APC. Now you have to change your controller code because you've programmed your controller to work with the functionality of the ApcCacher class rather than to an interface that expresses the capabilities of the ApcCacher class. Let's say instead of the above you had made the Controller class reliant on a CacherInterface instead of the concrete ApcCacher like so:

// Your controller's constructor using the interface as a dependency
public function __construct(Request $req, Response $resp, CacherInterface $cacher=NULL)

To go along with that you define your interface like so:

interface CacherInterface
{
  public function fetch($key);
  public function store($key, $data);
  public function delete($key);
}

In turn you have both your ApcCacher and your new FileCacher classes implement the CacherInterface and you program your Controller class to use the capabilities required by the interface.

This example (hopefully) demonstrates how programming to an interface allows you to change the internal implementation of your classes without worrying if the changes will break your other code.

Traits

Traits, on the other hand, are simply a method for re-using code. Interfaces should not be thought of as a mutually exclusive alternative to traits. In fact, creating traits that fulfill the capabilities required by an interface is the ideal use case.

You should only use traits when multiple classes share the same functionality (likely dictated by the same interface). There's no sense in using a trait to provide functionality for a single class: that only obfuscates what the class does and a better design would move the trait's functionality into the relevant class.

Consider the following trait implementation:

interface Person
{
    public function greet();
    public function eat($food);
}

trait EatingTrait
{
    public function eat($food)
    {
        $this->putInMouth($food);
    }

    private function putInMouth($food)
    {
        // Digest delicious food
    }
}

class NicePerson implements Person
{
    use EatingTrait;

    public function greet()
    {
        echo 'Good day, good sir!';
    }
}

class MeanPerson implements Person
{
    use EatingTrait;

    public function greet()
    {
        echo 'Your mother was a hamster!';
    }
}

A more concrete example: imagine both your FileCacher and your ApcCacher from the interface discussion use the same method to determine whether a cache entry is stale and should be deleted (obviously this isn't the case in real life, but go with it). You could write a trait and allow both classes to use it to for the common interface requirement.

One final word of caution: be careful not to go overboard with traits. Often traits are used as a crutch for poor design when unique class implementations would suffice. You should limit traits to fulfilling interface requirements for best code design.

How can I simulate an array variable in MySQL?

Here’s how I did it.

First, I created a function that checks whether a Long/Integer/whatever value is in a list of values separated by commas:

CREATE DEFINER = 'root'@'localhost' FUNCTION `is_id_in_ids`(
        `strIDs` VARCHAR(255),
        `_id` BIGINT
    )
    RETURNS BIT(1)
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN

  DECLARE strLen    INT DEFAULT 0;
  DECLARE subStrLen INT DEFAULT 0;
  DECLARE subs      VARCHAR(255);

  IF strIDs IS NULL THEN
    SET strIDs = '';
  END IF;

  do_this:
    LOOP
      SET strLen = LENGTH(strIDs);
      SET subs = SUBSTRING_INDEX(strIDs, ',', 1);

      if ( CAST(subs AS UNSIGNED) = _id ) THEN
        -- founded
        return(1);
      END IF;

      SET subStrLen = LENGTH(SUBSTRING_INDEX(strIDs, ',', 1));
      SET strIDs = MID(strIDs, subStrLen+2, strLen);

      IF strIDs = NULL or trim(strIds) = '' THEN
        LEAVE do_this;
      END IF;

  END LOOP do_this;

   -- not founded
  return(0);

END;

So now you can search for an ID in a comma-separated list of IDs, like this:

select `is_id_in_ids`('1001,1002,1003',1002);

And you can use this function inside a WHERE clause, like this:

SELECT * FROM table1 WHERE `is_id_in_ids`('1001,1002,1003',table1_id);

This was the only way I found to pass an "array" parameter to a PROCEDURE.

How to delete from a text file, all lines that contain a specific string?

You can use sed to replace lines in place in a file. However, it seems to be much slower than using grep for the inverse into a second file and then moving the second file over the original.

e.g.

sed -i '/pattern/d' filename      

or

grep -v "pattern" filename > filename2; mv filename2 filename

The first command takes 3 times longer on my machine anyway.

How to save LogCat contents to file?

String filePath = folder.getAbsolutePath()+ "/logcat.txt"; 
Runtime.getRuntime().exec(new String[]{"logcat", "-f", filePath, "MyAppTAG:V", "*:E"});

Handling exceptions from Java ExecutorService tasks

This works

  • It is derived from SingleThreadExecutor, but you can adapt it easily
  • Java 8 lamdas code, but easy to fix

It will create a Executor with a single thread, that can get a lot of tasks; and will wait for the current one to end execution to begin with the next

In case of uncaugth error or exception the uncaughtExceptionHandler will catch it

public final class SingleThreadExecutorWithExceptions {

    public static ExecutorService newSingleThreadExecutorWithExceptions(final Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {

        ThreadFactory factory = (Runnable runnable)  -> {
            final Thread newThread = new Thread(runnable, "SingleThreadExecutorWithExceptions");
            newThread.setUncaughtExceptionHandler( (final Thread caugthThread,final Throwable throwable) -> {
                uncaughtExceptionHandler.uncaughtException(caugthThread, throwable);
            });
            return newThread;
        };
        return new FinalizableDelegatedExecutorService
                (new ThreadPoolExecutor(1, 1,
                        0L, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue(),
                        factory){


                    protected void afterExecute(Runnable runnable, Throwable throwable) {
                        super.afterExecute(runnable, throwable);
                        if (throwable == null && runnable instanceof Future) {
                            try {
                                Future future = (Future) runnable;
                                if (future.isDone()) {
                                    future.get();
                                }
                            } catch (CancellationException ce) {
                                throwable = ce;
                            } catch (ExecutionException ee) {
                                throwable = ee.getCause();
                            } catch (InterruptedException ie) {
                                Thread.currentThread().interrupt(); // ignore/reset
                            }
                        }
                        if (throwable != null) {
                            uncaughtExceptionHandler.uncaughtException(Thread.currentThread(),throwable);
                        }
                    }
                });
    }



    private static class FinalizableDelegatedExecutorService
            extends DelegatedExecutorService {
        FinalizableDelegatedExecutorService(ExecutorService executor) {
            super(executor);
        }
        protected void finalize() {
            super.shutdown();
        }
    }

    /**
     * A wrapper class that exposes only the ExecutorService methods
     * of an ExecutorService implementation.
     */
    private static class DelegatedExecutorService extends AbstractExecutorService {
        private final ExecutorService e;
        DelegatedExecutorService(ExecutorService executor) { e = executor; }
        public void execute(Runnable command) { e.execute(command); }
        public void shutdown() { e.shutdown(); }
        public List shutdownNow() { return e.shutdownNow(); }
        public boolean isShutdown() { return e.isShutdown(); }
        public boolean isTerminated() { return e.isTerminated(); }
        public boolean awaitTermination(long timeout, TimeUnit unit)
                throws InterruptedException {
            return e.awaitTermination(timeout, unit);
        }
        public Future submit(Runnable task) {
            return e.submit(task);
        }
        public  Future submit(Callable task) {
            return e.submit(task);
        }
        public  Future submit(Runnable task, T result) {
            return e.submit(task, result);
        }
        public  List> invokeAll(Collection> tasks)
                throws InterruptedException {
            return e.invokeAll(tasks);
        }
        public  List> invokeAll(Collection> tasks,
                                             long timeout, TimeUnit unit)
                throws InterruptedException {
            return e.invokeAll(tasks, timeout, unit);
        }
        public  T invokeAny(Collection> tasks)
                throws InterruptedException, ExecutionException {
            return e.invokeAny(tasks);
        }
        public  T invokeAny(Collection> tasks,
                               long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return e.invokeAny(tasks, timeout, unit);
        }
    }



    private SingleThreadExecutorWithExceptions() {}
}

Difference between 'cls' and 'self' in Python classes?

The distinction between "self" and "cls" is defined in PEP 8 . As Adrien said, this is not a mandatory. It's a coding style. PEP 8 says:

Function and method arguments:

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

What is the difference between an IntentService and a Service?

service: It runs in the background on your system. For example,

  1. If you went to a hotel and you give your order for a soup to a server
  2. The server gets your order and sends to chef
  3. You don't know how the soup is made in the kitchen and what processes are required for making the soup
  4. Once your order is ready, the server brings you the soup.

background process: chef making soup

IntentService:- it's consecutive service.. (i.e) when you order many food items at a time to server but the server delivers those items one by one and not deliver them all at once.

Count all values in a matrix greater than a value

This is very straightforward with boolean arrays:

p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements

How do I create a SQL table under a different schema?

Shaun F's answer will not work if Schema doesn't exist in the DB. If anyone is looking for way to create schema then just execute following script to create schema.

create schema [schema_name]
CREATE TABLE [schema_name].[table_name](
 ...
) ON [PRIMARY]

While adding new table, go to table design mode and press F4 to open property Window and select the schema from dropdown. Default is dbo.

You can also change the schema of the current Table using Property window.

Refer:

enter image description here

jQuery: Best practice to populate drop down?

Other approach with ES6

fetch('https://restcountries.eu/rest/v1/all')
  .then((response) => {
    return response.json()
  })
  .then((countries) => {
    var options = document.getElementById('someSelect');
    countries.forEach((country) => {
      options.appendChild(new Option(country.name, country.name));
    });
  })

Conditional formatting, entire row based

To set Conditional Formatting for an ENTIRE ROW based on a single cell you must ANCHOR that single cell's column address with a "$", otherwise Excel will only get the first column correct. Why?

Because Excel is setting your Conditional Format for the SECOND column of your row based on an OFFSET of columns. For the SECOND column, Excel has now moved one column to the RIGHT of your intended rule cell, examined THAT cell, and has correctly formatted column two based on a cell you never intended.

Simply anchor the COLUMN portion of your rule cell's address with "$", and you will be happy

For example: You want any row of your table to highlight red if the last cell of that row does not equal 1.

Select the entire table (but not the headings) "Home" > "Conditional Formatting" > "Manage Rules..." > "New Rule" > "Use a formula to determine which cells to format"

Enter: "=$T3<>1" (no quotes... "T" is the rule cell's column, "3" is its row) Set your formatting Click Apply.

Make sure Excel has not inserted quotes into any part of your formula... if it did, Backspace/Delete them out (no arrow keys please).

Conditional Formatting should be set for the entire table.

JAXB Exception: Class not known to this context

Your ProfileDto class is not referenced in SearchResultDto. Try adding @XmlSeeAlso(ProfileDto.class) to SearchResultDto.

Converting DateTime format using razor

I was not able to get this working entirely based on the suggestions above. Including the DataTypeAttribute [DataType(DataType.Date)] seemed to solve my issue, see:

Model

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime RptDate { get; set; }

View

@Html.EditorFor(m => m.CLPosts.RptDate)

HTH

How to implement a Keyword Search in MySQL?

For a single keyword on VARCHAR fields you can use LIKE:

SELECT id, category, location
FROM table
WHERE
(
    category LIKE '%keyword%'
    OR location LIKE '%keyword%'
)

For a description you're usually better adding a full text index and doing a Full-Text Search (MyISAM only):

SELECT id, description
FROM table
WHERE MATCH (description) AGAINST('keyword1 keyword2')

Download a div in a HTML page as pdf using javascript

AFAIK there is no native jquery function that does this. Best option would be to process the conversion on the server. How you do this depends on what language you are using (.net, php etc.). You can pass the content of the div to the function that handles the conversion, which would return a pdf to the user.

How many characters in varchar(max)

For future readers who need this answer quickly:

2^31-1 = 2.147.483.647 characters

How can I read large text files in Python, line by line, without loading it into memory?

Please try this:

with open('filename','r',buffering=100000) as f:
    for line in f:
        print line

How to jQuery clone() and change id?

_x000D_
_x000D_
$('#cloneDiv').click(function(){_x000D_
_x000D_
_x000D_
  // get the last DIV which ID starts with ^= "klon"_x000D_
  var $div = $('div[id^="klon"]:last');_x000D_
_x000D_
  // Read the Number from that DIV's ID (i.e: 3 from "klon3")_x000D_
  // And increment that number by 1_x000D_
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;_x000D_
_x000D_
  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")_x000D_
  var $klon = $div.clone().prop('id', 'klon'+num );_x000D_
_x000D_
  // Finally insert $klon wherever you want_x000D_
  $div.after( $klon.text('klon'+num) );_x000D_
_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>_x000D_
_x000D_
<button id="cloneDiv">CLICK TO CLONE</button> _x000D_
_x000D_
<div id="klon1">klon1</div>_x000D_
<div id="klon2">klon2</div>
_x000D_
_x000D_
_x000D_


Scrambled elements, retrieve highest ID

Say you have many elements with IDs like klon--5 but scrambled (not in order). Here we cannot go for :last or :first, therefore we need a mechanism to retrieve the highest ID:

_x000D_
_x000D_
const $all = $('[id^="klon--"]');_x000D_
const maxID = Math.max.apply(Math, $all.map((i, el) => +el.id.match(/\d+$/g)[0]).get());_x000D_
const nextId = maxID + 1;_x000D_
_x000D_
console.log(`New ID is: ${nextId}`);
_x000D_
<div id="klon--12">12</div>_x000D_
<div id="klon--34">34</div>_x000D_
<div id="klon--8">8</div>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
_x000D_
_x000D_
_x000D_

How do I force my .NET application to run as administrator?

You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.

You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).

How to download files using axios

A more general solution

axios({
  url: 'http://api.dev/file-download', //your url
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', 'file.pdf'); //or any other extension
   document.body.appendChild(link);
   link.click();
});

Check out the quirks at https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743

Full credits to: https://gist.github.com/javilobo8

What exactly is a Context in Java?

A Context represents your environment. It represents the state surrounding where you are in your system.

For example, in web programming in Java, you have a Request, and a Response. These are passed to the service method of a Servlet.

A property of the Servlet is the ServletConfig, and within that is a ServletContext.

The ServletContext is used to tell the servlet about the Container that the Servlet is within.

So, the ServletContext represents the servlets environment within its container.

Similarly, in Java EE, you have EBJContexts that elements (like session beans) can access to work with their containers.

Those are two examples of contexts used in Java today.

Edit --

You mention Android.

Look here: http://developer.android.com/reference/android/content/Context.html

You can see how this Context gives you all sorts of information about where the Android app is deployed and what's available to it.

How to initialize log4j properly?

To enable -Dlog4j.debug, I go to System, Advanced system settings, Environment variables and set system variable _JAVA_OPTIONS to -Dlog4j.debug.

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

CSS how to make an element fade in and then fade out?

I found this link to be useful: css-tricks fade-in fade-out css.

Here's a summary of the csstricks post:

CSS classes:

.m-fadeOut {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s linear 300ms, opacity 300ms;
}
.m-fadeIn {
  visibility: visible;
  opacity: 1;
  transition: visibility 0s linear 0s, opacity 300ms;
}

In React:

toggle(){
    if(true condition){
        this.setState({toggleClass: "m-fadeIn"});
    }else{
        this.setState({toggleClass: "m-fadeOut"});
    }
}

render(){
    return (<div className={this.state.toggleClass}>Element to be toggled</div>)
}

How can I output leading zeros in Ruby?

If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do

str = "file_" + i.to_s.rjust(n, "0")

ToList()-- does it create a new list?

Just stumble upon this old post and thought of adding my two cents. Generally, if I am in doubt, I quickly use the GetHashCode() method on any object to check the identities. So for above -

    public class MyObject
{
    public int SimpleInt { get; set; }
}


class Program
{

    public static void RunChangeList()
    {
        var objs = new List<MyObject>() { new MyObject() { SimpleInt = 0 } };
        Console.WriteLine("objs: {0}", objs.GetHashCode());
        Console.WriteLine("objs[0]: {0}", objs[0].GetHashCode());
        var whatInt = ChangeToList(objs);
        Console.WriteLine("whatInt: {0}", whatInt.GetHashCode());
    }

    public static int ChangeToList(List<MyObject> objects)
    {
        Console.WriteLine("objects: {0}", objects.GetHashCode());
        Console.WriteLine("objects[0]: {0}", objects[0].GetHashCode());
        var objectList = objects.ToList();
        Console.WriteLine("objectList: {0}", objectList.GetHashCode());
        Console.WriteLine("objectList[0]: {0}", objectList[0].GetHashCode());
        objectList[0].SimpleInt = 5;
        return objects[0].SimpleInt;

    }

    private static void Main(string[] args)
    {
        RunChangeList();
        Console.ReadLine();
    }

And answer on my machine -

  • objs: 45653674
  • objs[0]: 41149443
  • objects: 45653674
  • objects[0]: 41149443
  • objectList: 39785641
  • objectList[0]: 41149443
  • whatInt: 5

So essentially the object that list carries remain the same in above code. Hope the approach helps.

How can you flush a write using a file descriptor?

You have two choices:

  1. Use fileno() to obtain the file descriptor associated with the stdio stream pointer

  2. Don't use <stdio.h> at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write() call won't even return until the lower-level IO has completed (in theory).

For device-level IO I'd say it's pretty unusual to use stdio. I'd strongly recommend using the lower-level open(), read() and write() functions instead (based on your later reply):

int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);

MySQL my.cnf file - Found option without preceding group

Charset encoding

Check the charset encoding of the file. Make sure that it is in ASCII.

Use the od command to see if there is a UTF-8 BOM at the beginning, for example.

How to make a simple image upload using Javascript/HTML

Here's a simple example with no jQuery. Use URL.createObjectURL, which

creates a DOMString containing a URL representing the object given in the parameter

Then, you can simply set the src of the image to that url:

_x000D_
_x000D_
window.addEventListener('load', function() {
  document.querySelector('input[type="file"]').addEventListener('change', function() {
      if (this.files && this.files[0]) {
          var img = document.querySelector('img');
          img.onload = () => {
              URL.revokeObjectURL(img.src);  // no longer needed, free memory
          }

          img.src = URL.createObjectURL(this.files[0]); // set src to blob url
      }
  });
});
_x000D_
<input type='file' />
<br><img id="myImg" src="#">
_x000D_
_x000D_
_x000D_

How to make an ImageView with rounded corners?

In Layout Make your ImageView like:

<com.example..CircularImageView
    android:id="@+id/profile_image_round_corner"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:scaleType="fitCenter"
    android:padding="2dp"
    android:background="@null"
    android:adjustViewBounds="true"
    android:layout_centerInParent="true"
    android:src="@drawable/dummy"
    />

And Create a Class:

package com.example;

import java.util.Formatter.BigDecimalLayoutForm;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CircularImageView extends ImageView {

    public CircularImageView(Context context) {
        super(context);
    }

    public CircularImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth(), h = getHeight();

        Bitmap roundBitmap = getRoundBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getRoundBitmap(Bitmap bmp, int radius) {
        Bitmap sBmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sBmp = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / factor), (int)(bmp.getHeight() / factor), false);
        } else {
            sBmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xffa19774;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawCircle(radius / 2 + 0.7f,
                radius / 2 + 0.7f, radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sBmp, rect, rect, paint);

        return output;
    }

}

CREATE TABLE LIKE A1 as A2

For MySQL, you can do it like this:

CREATE TABLE New_Users   SELECT * FROM Old_Users group by ID;

Declaring variables inside or outside of a loop

If you don't need to use the str after the while loop (scope related) then the second condition i.e.

  while(condition){
        String str = calculateStr();
        .....
    }

is better since if you define an object on the stack only if the condition is true. I.e. use it if you need it

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:

ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() ); 

Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.

Code that does AES encyrption:

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Test 
{
    final String ALGORITHM = "AES";                       //symmetric algorithm for data encryption
    final String PADDING_MODE = "/CBC/PKCS5Padding";      //Padding for symmetric algorithm
    final String CHAR_ENCODING = "UTF-8";                 //character encoding
    //final String CRYPTO_PROVIDER = "SunMSCAPI";             //provider for the crypto

    int AES_KEY_SIZE = 256;  //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files  installed

    private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
    {
        byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);

        //get the symmetric key generator
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(AES_KEY_SIZE); //set the key size

        //generate the key
        SecretKey skey = keyGen.generateKey();

        //convert to binary
        byte[] rawAesKey = skey.getEncoded();

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);

        //set it to encrypt mode, with the generated key
        aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        //get the initialization vector being used (to be returned)
        byte[] aesIV = aesCipher.getIV();

        //encrypt the data
        byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);    

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);

        //set it to decrypt mode with the AES key, and IV
        aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));

        //decrypt and return the data
        byte[] decryptedData = aesCipherDec.doFinal(encryptedData);

        return new String(decryptedData, CHAR_ENCODING);
    }

    public static void main(String[] args)
    {
        String text = "Lets encrypt me";

        Test test = new Test();

        try {
            System.out.println(test.doCrypto(text));
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Does this code work for you?

You might also want to try specifying your bouncy castle provider in this line:

Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");

And see if it could be an error associated with bouncy castle.

How can one grab a stack trace in C?

Solaris has the pstack command, which was also copied into Linux.

How do browser cookie domains work?

For an extensive coverage review the contents of RFC2965. Of course that doesn't necessarily mean that all browsers behave exactly the same way.

However in general the rule for default Path if none specified in the cookie is the path in the URL from which the Set-Cookie header arrived. Similarly the default for the Domain is the full host name in the URL from which the Set-Cookie arrived.

Matching rules for the domain require the cookie Domain to match the host to which the request is being made. The cookie can specify a wider domain match by include *. in the domain attribute of Set-Cookie (this one area that browsers may vary). Matching the path (assuming the domain matches) is a simple matter that the requested path must be inside the path specified on the cookie. Typically session cookies are set with path=/ or path=/applicationName/ so the cookie is available to all requests into the application.


Response to Added:

  • Will a cookie for .example.com be available for www.example.com? Yes
  • Will a cookie for .example.com be available for example.com? Don't Know
  • Will a cookie for example.com be available for www.example.com? Shouldn't but... *
  • Will a cookie for example.com be available for anotherexample.com? No
  • Will www.example.com be able to set cookie for example.com? Yes
  • Will www.example.com be able to set cookie for www2.example.com? No (Except via .example.com)
  • Will www.example.com be able to set cookie for .com? No (Can't set a cookie this high up the namespace nor can you set one for something like .co.uk).

* I'm unable to test this right now but I have an inkling that at least IE7/6 would treat the path example.com as if it were .example.com.

Is there a Sleep/Pause/Wait function in JavaScript?

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

How to list all files in a directory and its subdirectories in hadoop hdfs

don't use recursive approach (heap issues) :) use a queue

queue.add(param_dir)
while (queue is not empty){

  directory=  queue.pop
 - get items from current directory
 - if item is file add to a list (final list)
 - if item is directory => queue.push
}

that was easy, enjoy!

When to use AtomicReference in Java?

You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.

  1. You can create a copy of the shared object
  2. Modify the shared object
  3. You need to check that the shared object is still the same as before - if yes, then update with the reference of the modified copy.

As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help

How to change color of ListView items on focus and on click

listview.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View view,
                final int position, long id) {
            // TODO Auto-generated method stub

             parent.getChildAt(position).setBackgroundColor(getResources().getColor(R.color.listlongclick_selection));

            return false;
        }
    });

How do I change the default schema in sql developer?

Alternatively, just select 'Other Users' one of the element shows on the left hand side bottom of the current schema.

Select what ever the schema you want from the available list.

enter image description here

Tensorflow image reading & display

According to the documentation you can decode JPEG/PNG images.

It should be something like this:

import tensorflow as tf

filenames = ['/image_dir/img.jpg']
filename_queue = tf.train.string_input_producer(filenames)

reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)

images = tf.image.decode_jpeg(value, channels=3)

You can find a bit more info here

Copy folder structure (without files) from one location to another

If you can get access from a Windows machine, you can use xcopy with /T and /E to copy just the folder structure (the /E includes empty folders)

http://ss64.com/nt/xcopy.html

[EDIT!]

This one uses rsync to recreate the directory structure but without the files. http://psung.blogspot.com/2008/05/copying-directory-trees-with-rsync.html

Might actually be better :)

Detect when browser receives file download

One possible solution uses JavaScript on the client.

The client algorithm:

  1. Generate a random unique token.
  2. Submit the download request, and include the token in a GET/POST field.
  3. Show the "waiting" indicator.
  4. Start a timer, and every second or so, look for a cookie named "fileDownloadToken" (or whatever you decide).
  5. If the cookie exists, and its value matches the token, hide the "waiting" indicator.

The server algorithm:

  1. Look for the GET/POST field in the request.
  2. If it has a non-empty value, drop a cookie (e.g. "fileDownloadToken"), and set its value to the token's value.

Client source code (JavaScript):

function getCookie( name ) {
  var parts = document.cookie.split(name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

function expireCookie( cName ) {
    document.cookie = 
        encodeURIComponent(cName) + "=deleted; expires=" + new Date( 0 ).toUTCString();
}

function setCursor( docStyle, buttonStyle ) {
    document.getElementById( "doc" ).style.cursor = docStyle;
    document.getElementById( "button-id" ).style.cursor = buttonStyle;
}

function setFormToken() {
    var downloadToken = new Date().getTime();
    document.getElementById( "downloadToken" ).value = downloadToken;
    return downloadToken;
}

var downloadTimer;
var attempts = 30;

// Prevents double-submits by waiting for a cookie from the server.
function blockResubmit() {
    var downloadToken = setFormToken();
    setCursor( "wait", "wait" );

    downloadTimer = window.setInterval( function() {
        var token = getCookie( "downloadToken" );

        if( (token == downloadToken) || (attempts == 0) ) {
            unblockSubmit();
        }

        attempts--;
    }, 1000 );
}

function unblockSubmit() {
  setCursor( "auto", "pointer" );
  window.clearInterval( downloadTimer );
  expireCookie( "downloadToken" );
  attempts = 30;
}

Example server code (PHP):

$TOKEN = "downloadToken";

// Sets a cookie so that when the download begins the browser can
// unblock the submit button (thus helping to prevent multiple clicks).
// The false parameter allows the cookie to be exposed to JavaScript.
$this->setCookieToken( $TOKEN, $_GET[ $TOKEN ], false );

$result = $this->sendFile();

Where:

public function setCookieToken(
    $cookieName, $cookieValue, $httpOnly = true, $secure = false ) {

    // See: http://stackoverflow.com/a/1459794/59087
    // See: http://shiflett.org/blog/2006/mar/server-name-versus-http-host
    // See: http://stackoverflow.com/a/3290474/59087
    setcookie(
        $cookieName,
        $cookieValue,
        2147483647,            // expires January 1, 2038
        "/",                   // your path
        $_SERVER["HTTP_HOST"], // your domain
        $secure,               // Use true over HTTPS
        $httpOnly              // Set true for $AUTH_COOKIE_NAME
    );
}

How to determine if a number is positive or negative?

It seems arbitrary to me because I don't know how you would get the number as any type, but what about checking Abs(number) != number? Maybe && number != 0

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")